Last year I wrote about my clumsy implementation of unique random integers system, I’ve used in my Memorable Ladies games. In those the speed isn’t a critical factor. It’s sufficient that the idea works. 🙂
In this post the idea behind unique random integers is the same, but implemented in a faster way.
In the implementation I have used an array that consists of all desired integers and each is drawn in a way that the same integer doesn’t get drawn again. Let’s take a look at the code (I have used Monkey2 programming language in the example):
Local numbers:=New Int(1,3,5,7,9,11,13,15,17,19,21,23)
While (numbers.Length <> 0)
amountNumbers = numbers.Length
index = Int(amountNumbers * Rnd(0,1)) Mod amountNumbers
randomNumber = numbers[index]
For Local i:Int = index To amountNumbers - 2
numbers[i] = numbers[i+1]
amountNumbers = amountNumbers - 1
numbers = numbers.Resize(amountNumbers)
Print "Random number:" + randomNumber
First an array is initialized with desired integers. Then an random integer from the array is fetched using random index inside the array. After that the numbers after the drawn number are moved to “left”. For the end the amount of integers is decreased by 1 and the array is resized by the new amount of integers. That’s it.
This way one gets always different random integer from the set of desired integers.
Furthermore, if one would like to get, for example, number four (4) to be drawn three times, one could just include 4 three times in the array.
Depending on what one is doing, one could keep a copy of the original array for future usage.
Although I have used Monkey2 as example programming language, it should be easy to implement similar implementation to many other programming languages quite straight forwardly.