How can I ensure that when I shuffle my puzzle I still end up with an even permutation?

后端 未结 5 1335
北恋
北恋 2021-01-05 14:48

I\'m interested making an implementation of the 14-15 puzzle:

5条回答
  •  误落风尘
    2021-01-05 15:32

    You should be able to use Fischer-Yates.

    • Generate a random permutation using Fischer-Yates.
    • Check if it is even.
    • If it is not even, swap the first two elements of the permutation.

    Consider an even permutation P = x1 x2 .... xn.

    Fischer yates generates P with probabilty 1/n!.

    It generates x2 x1 ... xn with probability 1/n!.

    Thus the probability that the above process generates the permutation P is 2/n! = 1/(n!/2)

    n!/2 is the number of even permutations.

    Thus the above process generates even permutations with same probability.

    To check if a permutation is even: count the parity of the number of inversions in the permutation.

提交回复
热议问题