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)

Thanks for your interest and your help...

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];

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?

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;
  //loop code here

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.

#include <algorithm>

or with PRNG seed:

#include <algorithm>
#include <ctime>
This article has been dead for over six months. Start a new discussion instead.