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

前端 未结 12 1501
旧时难觅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:26

    The best explanation I've seen for this effect was from Jeff Atwood on his CodingHorror blog (The Danger of Naïveté).

    Using this code to simulate a 3-card random shuffle...

    for (int i = 0; i < cards.Length; i++)
    {
        int n = rand.Next(cards.Length);
        Swap(ref cards[i], ref cards[n]);
    }
    

    ...you get this distribution.

    Distribution of 3-card shuffle

    The shuffle code (above) results in 3^3 (27) possible deck combinations. But the mathematics tell us that there are really only 3! or 6 possible combinations of a 3 card deck. So some of the combinations are over-represented.

    You would need to use a Fisher-Yates shuffle to properly (randomly) shuffle a deck of cards.

提交回复
热议问题