# Create random array

• 09-21-2007
Hunter_wow
Create random array
Hello. I´m looking for a good way to make a array in random order. But I really cant come up with anything good. Thought of something like this(sorry if syntax is wrong, but I guess you can see what I´m trying to do):

Code:

```// variable to set the number in correct place in second array int i = 0; // Create 1 array with values and one where we will make the numbers in random order int[3] numbers = {1,2,3}; int[3] randomNum = {}; // run as long as the last element in the second array is empty while(randomNum[2] == null){   // take a random element from first array and put it into the second array   int random = rand()%2;   randomNum[i] = numbers[random];   i++; }```
Just one problem here is that I might take same numbers from the first array many times. Maybe can be solved by setting the value taken from first array to "null" into the while{} somehow? Feels like a bad solution. Or? What do you think. Any tips?
• 09-21-2007
anon
For such purposes I find std::random_shuffle in <algorithm> useful.

Code:

```#include <algorithm> int main() {     const int MAX = 3;     int numbers[MAX] = {1, 2, 3};     std::random_shuffle(numbers, numbers + MAX);     //values are now in random order in numbers }```
• 09-21-2007
matsp
Anon's solution is a good one.

If you want to do this yourself, you will need to keep a list of which numbers you've taken (or perhaps, if that's more appropriate, remove the "taken" from the original list, e.g set numbers[random] = 0, and check the picking method to see if the number is zero, in which case you start again).

--
Mats
• 09-21-2007
Hunter_wow
Tons of thanks. That random_shuffle was very easy. Perfect for my purpose =)