–1 vote

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

asked Sep 4 in Engine by Titox (58 points)
edited Sep 4 by Titox

1 Answer

0 votes
Best answer

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]
answered Sep 4 by Titox (58 points)
selected Sep 4 by Titox

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)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.