If you're a programmer, especially if you like creating games, you'll need a way to generate random numbers that are different from each other. For example, if you have a deck of cards and you need 3 different cards, you'll need 3 different random numbers. 3 random numbers will not do, as they may be random but identical. In this article, you will use pseudo-code; the instructions should be viable for any programming language.
1Determine if your programming language has a random function as well as a function to seed the random number generator. For example the function may be rand() or random() for generating random numbers and random() or srandom() for seeding the random number generator. Most modern languages do and the rand() or random() functions usually return a rational between 0 and 1.
2You need to seed the random number generator first, so that you don't get the same list of numbers each time you run it. To seed the random number generator, you need to pass an integer to the srand function. Example: 'srand( (unsigned int) time(0))'. This would pass the number of seconds since Jan 1, 1970.
3To make it an integer you multiply the result by the top value and round out the result. For example, to get a random number between 0 and 50 type: random() % 50.
4Understand that to get all the numbers to be different you will create a loop until you get as many numbers as you might need and then store the results to check they're not repeated:
5Now, if you don't have that "includes" function, it's quite easy to program:
Iterate as many times as needed in order to fill the array with different numbers. For each random number, we check if it's already in the array. If it isn't, then we push it in, otherwise, we just loop and try again with a different number.
- There are lots of ways to make this faster, but it depends on the programming language you use. For instance, in the .NET Framework you have a Sorted List class. You can store the numbers there, and then make the "includes" function using a binary search, which is much faster.
- The numbers generated by random() n are not truly random, they are pseudo random. As such, they are not appropriate for secure applications.
- Make sure that a list of unique pseudo random numbers is really what you need. For instance, if you are shuffling a deck of cards, there are algorithms written specifically for this (and may do a better job).