## Lua - How can I select numbers from a list randomly, with different probabilities of getting selected for each number?

Typically: "How do I... ", "How can I... " questions
coder212
Posts: 7
Joined: 10 Sep 2021, 13:29

### Lua - How can I select numbers from a list randomly, with different probabilities of getting selected for each number?

I have 4 numbers [1, 2, 3, 4]

I want to pick numbers out of this list randomly while giving the most probability to 1 (approx 0.43), next 3 (approx 0.38), and least and equal probabilities to 2 and 4 (approx 0.09 each).

How can I do this in Lua?

This is what I have tried so far.

Code: Select all

codeList = {1, 2, 3, 4}
number = codeList[math.random(#codeList)]


fferri
Posts: 821
Joined: 09 Sep 2013, 19:28

### Re: Lua - How can I select numbers from a list randomly, with different probabilities of getting selected for each numbe

coppelia
Posts: 8987
Joined: 14 Dec 2012, 00:25

### Re: Lua - How can I select numbers from a list randomly, with different probabilities of getting selected for each numbe

Hello,

maybe something like this?

Code: Select all

function getNumber()
local codeList={1,2,3,4}
local prob={0.43,0.38,0.095,0.095}
local r=math.random()
local index=1
local v=prob[index]
while r>v do
index=index+1
v=v+prob[index]
end
local number=codeList[index]
return number
end
You can probably find a nicer algorithm though ;)

Cheers

coder212
Posts: 7
Joined: 10 Sep 2021, 13:29

### Re: Lua - How can I select numbers from a list randomly, with different probabilities of getting selected for each numbe

This worked! Thank you so much