Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I make a random number generator but chances are high it gives a low number?

Asked by 1 year ago

I'm really stuck on this for my game. I have no idea where to even start. if anyone knows a way please comment. Thanks

2 answers

Log in to vote
0
Answered by
CDXKIE 130
1 year ago

Alright, so normally I'd say that this is for bugs, and you can't just ask for an entire code without trying yourself, but this is genuinely hard. So, here's some instructions.

1: Make a table, with the value, and the weight (probability) of that value. So for numbers, it would be:

local table = {
    {
        Value = 1,
        Weight = 5 --[[(the higher the number, the higher the chances.)]]
    },
    {
        Value = 2,
        Weight = 3
    }

    -- And so on...
}

Then, create a function to get the random number.

local function GetRandom(tableToGetRandomFrom --[[just in case you want to get it from different tables, put the table you want to get in from in there.]])
    local random = Random.new()
    local totalWeight = 0
    for i, info in tableToGetRandomFrom do
        totalWeight += info.Weight
    end

    return random:NextInteger(1, totalWeight)
end

Then, to get the random number as a variable, do:

local random = GetRandom(table)

:D

0
Thank you Ill try this! masilasi2008 10 — 1y
0
Oh, woops, this wouldn't work. I'll edit it later to show the correct way of doing it. CDXKIE 130 — 1y
Ad
Log in to vote
0
Answered by 1 year ago

I don't really get what you are asking for but this is an easy fix I guess

local max = math.random(1,100)
local number = math.random(1, max)

-- if the number is something like 100 then it's going to pick numbers until 100. if it's like 50 then it will pick numbers until 50 and so on

-- you can make it rarer and rarer by adding more maxes. For example:
local max1 = math.random(1,100)
local max2 = math.random(1, max1)
local max3 = math.random(1, max2)
local number = math.random(1, max3)
-- I hope you understand it

or you can make it pick again if the number is too high

local test = math.random(1,100)
if test > 50 then
    test = math.random(1,100)
end
-- again. this can be scaled

local test = math.random(1,100)
if test > 50 then
    test = math.random(1,100)
    if test > 50 then
        test = math.random(1,100)
    end
end
-- this might not be as good tho

or you can do the same thing in a different way

local test = math.random(1,100)
if test > 50 then
    local pick = math.random(1,2)
    if pick > 1 then
        test = math.random(1,50)
    else
        test = math.random(1,100)
    end
end

Hope you understand the ways

Answer this question