How can I choose between two numbers randomly?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By arthurZ

I want to know how to choose between two numbers (not a range) randomly.
For example, choosing 4 or 130, the result will be only 4 or 130.

Thanks a lot for this help.

:bust_in_silhouette: Reply From: rolfpancake

Just one way of implementing this:

var x
var first_value = bool(randi() % 2)
if first_value:
    x = 4
else:
    x = 130

Another:

var x = 4
if randf() < 0.5:
    x = 130

You can put this into a function as well:

func choose_randomly(list_of_entries):
    return list_of_entries[randi() % list_of_entries.size()]

func _ready():
   randomize()
   print(choose_randomly([1,2,3,4]))
1 Like
:bust_in_silhouette: Reply From: SingingApple

This is an awesome way to do this:

var nums = [4,130] #list to choose from
return nums[randi() % nums.size()]

Note: This method works with lists as huge as you want. It just returns a random element from the list.

Edit: OMG! So many upvotes! Thank you, guys!

Edit: You should also use the randomize() function in ready to give pure random results. (in a computer sense. Computers simply cannot produce completely random results because it uses algorithms.)

Cleaner and faster than my own answer. :smiley:

rolfpancake | 2018-02-19 15:39

2 Likes

How can I make it return more than one value from the list?

Probably run the chooser as a function until you have a desired number of unique results.

Do it twice. If you want two different values you can have it check if the two values are the same if they are generate another random number.

Shuffle the list and just get the first two numbers