system
February 19, 2018, 3:05pm
1
Attention
Topic was automatically imported from the old Question2Answer platform.
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.
system
February 19, 2018, 3:16pm
2
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
system
February 19, 2018, 3:18pm
3
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.
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.
E71
May 30, 2024, 4:55am
6
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