Page 1 of 1

Choose from a list of numbers?

Posted: Fri Apr 28, 2017 12:23 am
by Electriic
Hiya, this is my first post here, so if I'm breaking any rules here please let me know.

I'm trying to find a way to choose a random number from a specified list. Something like this:

Code: Select all

x = x + choose(1, 2, 3, ...)
I've searched through the Lua documentation and the Love documentation and didn't see anything.
Is there a way to do this?

Re: Choose from a list of numbers?

Posted: Fri Apr 28, 2017 3:01 am
by davisdude
Sure. It depends on what you mean by "random list of numbers," though.

For instance, if you want a random integer, try

Code: Select all

love.math.random( lowest, highest )
where lowest and highest are the (inclusive) range of the values you would expect.

If you have a "list" (integer-indexed table) of pre-generated values and you would like to choose one randomly, try:

Code: Select all

list = { 1, 2, 47, 3, math.pi }
print( list[love.math.random( #list )] )

Re: Choose from a list of numbers?

Posted: Fri Apr 28, 2017 3:25 am
by Electriic
The second method is exactly what I was looking for. Thanks!

Re: Choose from a list of numbers?

Posted: Fri Apr 28, 2017 10:48 am
by Roland_Yonaba
I recently added in the 1.6.0 release of Moses (a utility-belt library for Lua I am maintaining), two utility functions: sample and sampleProb.
The first one will pick randomly one value in a supplied list. We can even specify a certain number of values to pick. It roughly works as davisdude suggested.

The latter might be slightly more interesting, as it performs probabilistic sampling . It considers every single element in the array and given a probability, will decide (randomly) if the element should be part of the returned sample or not.