system
September 4, 2019, 11:13pm
1
Attention
Topic was automatically imported from the old Question2Answer platform.
Asked By
Titox
How do I create a function that generates a random number from 1
- 40
without it repeating any number at all.This function will be in a for
loop so it will only be called 40
times.
Thanks
system
September 4, 2019, 11:21pm
2
Reply From:
Titox
Funny enough, immediately after asking this question I thought of an answer:
func rand_num(from,to,index):
var arr = []
for i in range(from,to):
arr.append(i)
arr.shuffle()
return arr[index]
This function still returns a random number which can repeat, and is very inefficient.
It is far much easier to do from + randi() % (to - from)
.
Or, if you actually want to generate 40 random numbers between 1 and 40 without any repetition, your code should be:
func get_random_numbers(from, to):
var arr = []
for i in range(from,to):
arr.append(i)
arr.shuffle()
return arr
And only then, you iterate over the returned array, and you will see they don’t repeat.
var arr = get_random_numbers(1, 40)
for number in arr:
print(number)
Zylann | 2019-09-05 12:56
Thank you!
PudimLaranja | 2022-12-27 04:21