Choose from a list of numbers?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Electriic
Prole
Posts: 2
Joined: Thu Feb 23, 2017 9:22 pm

Choose from a list of numbers?

Post 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?
davisdude
Party member
Posts: 1154
Joined: Sun Apr 28, 2013 3:29 am
Location: North Carolina

Re: Choose from a list of numbers?

Post 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 )] )
GitHub | MLib - Math and shape intersections library | Walt - Animation library | Brady - Camera library with parallax scrolling | Vim-love-docs - Help files and syntax coloring for Vim
User avatar
Electriic
Prole
Posts: 2
Joined: Thu Feb 23, 2017 9:22 pm

Re: Choose from a list of numbers?

Post by Electriic »

The second method is exactly what I was looking for. Thanks!
User avatar
Roland_Yonaba
Inner party member
Posts: 1563
Joined: Tue Jun 21, 2011 6:08 pm
Location: Ouagadougou (Burkina Faso)
Contact:

Re: Choose from a list of numbers?

Post 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.
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 56 guests