1

I have reading cracking the coding interview book where I have found the below solution for this problem

void shuffleArrayiteratively(int[] cards) {
  for (int i= 0; i < cards.length; i++) {
      int k = rand(0, i); 
      int temp= cards[k]; cards[k] = cards[i];
      cards[i] = temp;
  }
}

In the above code, we are getting random numbers 0 -> i and then swap i with random number but my question is for loop will get a random number in below fashions

ramdon = 0 - 1
random = 0 - 2
random = 0 - 3
...
...
random = 0 - 51

so 0 have 52 chances to swap with another number and 51 have only one chance. Could someone help me understand why this solution has to be equally likely of 52!

Vimit Dhawan
  • 597
  • 1
  • 7
  • 25
  • 1
    Here's a good explanation: https://emctackett.medium.com/fisher-yates-shuffle-randomly-shuffle-a-list-in-place-30a05b05a9cb – Mark Ransom Jun 08 '21 at 04:28

0 Answers0