why does this simple shuffle algorithm produce biased results? what is a simple reason?

前端 未结 12 1468
旧时难觅i
旧时难觅i 2020-11-27 03:17

it seems that this simple shuffle algorithm will produce biased results:

# suppose $arr is filled with 1 to 52

for ($i < 0; $i < 52; $i++) { 
  $j = r         


        
12条回答
  •  温柔的废话
    2020-11-27 03:35

    See the Coding Horror post The Danger of Naïveté.

    Basically (suposing 3 cards):

    The naive shuffle results in 33 (27) possible deck combinations. That's odd, because the mathematics tell us that there are really only 3! or 6 possible combinations of a 3 card deck. In the KFY shuffle, we start with an initial order, swap from the third position with any of the three cards, then swap again from the second position with the remaining two cards.

提交回复
热议问题