Hey everyone,

I've just a simple question for you. I've an array like a[10] = {23, 17, 35, 67, 43, 52, 97, 83, 73, 29}

How can i shuffle the order of this array's elements? (randomly)

Have a nice day...

Have a look at the 'rand' function.
Generate 2 random numbers, say r1 and r2, restricting them to the size of the array-1 (max index) and do something like:

``````for( int i=0; i<5; ++i )
{
//generate r1 and r2 here
int tmp=a[r2];
a[r2]=a[r1];
a[r1]=tmp;
}``````

That will shuffle them randomly. The more iterations of the loop, the more shuffling happens.

for loop is for the integer "i", but where did you use it?

for loop is for the integer "i", but where did you use it?

I don't. It is used to keep track of the iterations (see the `i<5` in the for loop declaration), if you don't do this it will loop forever.
i is incremented each iteration, then when i fails the check of i<5, i.e when i equals 5 (or more) the for loop terminates.

You could also do:

``````int i=0;
while(i<5)
{
//loop code here
++i;
}``````

Remember 5 is just an arbitrary number, i used 1/2 the array size as the number of shuffles, but the more you do the more it shuffles.

Take a look at this code snippet :)
Or you could use a vector.

``````#include <algorithm>
...
std::random_shuffle(a,a+10);``````

or with PRNG seed:

``````#include <algorithm>
#include <ctime>
...
srand(time(0));
...
std::random_shuffle(a,a+10);``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.