Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Become a Premium Member and unlock a new, free course in leading technologies each month.

Solved

Posted on 2000-04-26

int Array[3] = {0,1,2}

I want an algorithm that will shuffle the order of this array randomly, so that the following six combinations are all equally likely:

{0,1,2}

{0,2,1}

(1,0,2}

{1,2,0}

{2,0,1}

{2,1,0}

Tbe following Fischer-Yates shuffle I was using yields only the combinations {2,0,1} and {1,2,0}:

for (int l=1,l<3,l++)

{ int r = random(l);

int temp = Array[l];

Array[l] = Array[r];

Array [r] = temp;

}

I want an algorithm that will shuffle the order of this array randomly, so that the following six combinations are all equally likely:

{0,1,2}

{0,2,1}

(1,0,2}

{1,2,0}

{2,0,1}

{2,1,0}

Tbe following Fischer-Yates shuffle I was using yields only the combinations {2,0,1} and {1,2,0}:

for (int l=1,l<3,l++)

{ int r = random(l);

int temp = Array[l];

Array[l] = Array[r];

Array [r] = temp;

}

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

- Help others & share knowledge
- Earn cash & points
- Learn & ask questions

2 Comments

Your current code will first swap Array[1] with Array[0] to produce {1,0,2} and then swap Array[2] with either Array[0] or Array[1] to produce either {2,0,1} or {1,2,0}.

Try this instead:

for (int i = 2, i > 0 ,i--)

{

int r = random(i + 1);

int temp = Array[i];

Array[i] = Array[r];

Array[r] = temp;

}

On the first iteration this will produce one of:

{0,1,2} {0,2,1} {2,1,0}

And on the second will produce one of:

{0,1,2} {1,0,2} {0,2,1} {2,0,1} {2,1,0} {1,2,0}

Let me know if my first assumption was wrong and I will fix the algorithm for you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Course of the Month13 days, 9 hours left to enroll

Join the community of 500,000 technology professionals and ask your questions.