title: Why does this simple shuffle algorithm produce biased results?
body: <p>It seems that this simple shuffle algorithm will produce biased results:</p>
  <pre><code># suppose $arr is filled with 1 to 52
  
  for ($i &lt; 0; $i &lt; 52; $i++) { 
    $j = rand(0, 51);
  
    # swap the items
  
    $tmp = $arr[j];
    $arr[j] = $arr[i];
    $arr[i] = $tmp;
  }
  </code></pre>
  <p>You can try it... instead of using 52, use 3 (suppose only 3 cards are used), and run it 10,000 times and tally up the results, you will see that the results are skewed towards certain patterns...</p>
  <p>The question is... what is a simple explanation for why it will happen?</p>
  <p>The correct solution is to use something like</p>
  <pre><code>for ($i &lt; 0; $i &lt; 51; $i++) {  # last card need not swap 
    $j = rand($i, 51);        # don't touch the cards that already &quot;settled&quot;
  
    # swap the items
  
    $tmp = $arr[j];
    $arr[j] = $arr[i];
    $arr[i] = $tmp;
  }
  </code></pre>
  <p>But the question is... why does the first method, seemingly also totally random, make the results biased?</p>
  <p><strong>Update 1:</strong> thanks for folks here pointing out that it needs to be rand($i, 51) for it to shuffle correctly.</p>