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

前端 未结 12 1477
旧时难觅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条回答
  •  Happy的楠姐
    2020-11-27 03:37

    The Naive algorithm picks the values of n like so:

    n = rand(3)

    n = rand(3)

    n = rand(3)

    3^3 possible combinations of n

    1,1,1, 1,1,2....3,3,2 3,3,3 (27 combinations) lassevk's answer shows the distribution among the cards of these combinations.

    the better algorithm does:

    n = rand(3)

    n = rand(2)

    n! possible combinations of n

    1,1, 1,2, 2,1 2,2 3,1 3,2 (6 combinations, all of them giving a different result)

    As mentioned in the other answers, if you take 27 attempts to get 6 results, you cannot possibly attain the 6 results with even distribution, since 27 is not divisible by 6. Put 27 marbles into 6 buckets and no matter what you do, some buckets will have more marbles than others, the best you can do is 4,4,4,5,5,5 marbles for buckets 1 through 6.

    the fundamental problem with the naive shuffle is that swaps too many times, to shuffle 3 cards completely, you need only do 2 swaps, and the second swap need only be among the first two cards, since the 3rd card already had a 1/3 chance of being swapped. to continue to swap cards will impart more chances that a given card will be swapped, and these chances will only even out to 1/3, 1/3, 1/3 if your total swap combinations is divisible by 6.

提交回复
热议问题