GetRandomInt() not getting the same value again

Hey there!
I’m currently working on a map in UEFN & want to randomly spawn blocks.
For example: If there are 2 players there should just randomly spawn 1 block of all blocks & if there are 3 players there should spawn 2 blocks of all blocks, but now there is a problem that when I try to get 2 random integers that there is a chance to get the same integer.
I there a way to avoid getting the same integer?
Later in the game both of the integer should be available to get again.

Greetings!

There are many ways to achieve this:

  • start off with all your blocks in a list, remove each block from the list when you pick it randomly
  • keep a list of all the integers you have picked, when you want to pick a new one make a loop that keeps guessing until it finds one that isn’t in that list
  • create a list of the integers in order, then swap them around until the list is in a random order, then pick the next value from the list each time
    In all of these, you’ll want a function to Reset the list when it is time to start again, and you should include code to protect against the list being empty or all the numbers being used already (avoid infinite loops!)
2 Likes

note that this solution is ok. but has the potential of being increasingly slow. since the more numbers you have picked, the less chances of getting a new number, the more retries. and you never know how many times it will retry maybe 1 maybe 1 million (since it’s random).
It also has the possibility of locking your game if you accidentally request a number when you already exhausted all your possible numbers. (since it will loop forever since there are no more available numbers).

the other 2 solutions are great.

the one to pick a number from a shuffled list has always been very reliable to me, and you can easily check when you exhausted your numbers and reshuffle.
getting a new “random” number is constant in speed. and shuffling an array is pretty easy (and unreal has that functionality built in).

2 Likes

In case this is still helpful to you or anyone else that reads this I wrote this logic on top of Mark Wahlbeck’s array’s lesson on YT.
Github Code Link

It outlines how you can create an array, then shuffle it for randomness. Once shuffled you can then grab the value at index 0, and then increase the index the function looks for by 1. So next time the loop runs it’ll take index 1, and so on and so forth until you tell it to exit the loop, and reset the value back to 0.

It reshuffles the array each time it runs, and resets itself at the end so you can reuse this with new a new series of random results and avoid repeating any results.

2 Likes