Knuth random Shuffle algorithm: for example, there are now 54 cards, how to shuffle to ensure randomness. You can think of this, from the very end of a card to wash, for each card, numbered in the cards in front of any one of the cards selected and the current card to exchange, until the first card to wash. The reference code is as follows:
void Knuth () { for (int1; i--) { int1 1; Swap (A[i], a[id]); } }
By the above method, each card after shuffling will certainly not appear in the original position, then there will be a total number of cases, which is actually the definition of the wrong row, n number of the number of the wrong row has the following recursive formula:
F (n) = (n-1) (f (n-1) +f (n-2))
Formula derivation: First let us assume that the number of known n-1 number and the number of n-2, and then added a number on the original basis, then if the N number to form a wrong row, the new number must not appear in their own position, so it can only choose the rest of the n-1 location, may wish to choose the K position, Then the number in the first K-position will go to where, there are two cases, the original number of K ran to the nth number of positions up, then the two numbers are exchanged position, the rest of the number of n-2 is completely unaffected, so when there is f (n-2) kind of situation , and then consider the original K number is not in the position of nth number, then remove the nth number, the remaining number of n-1 is the wrong row, the number of rows is f (n-1). A recursive f (n) = (n-1) (f (n-1) +f (n-2)) is available at this point.
Random shuffling algorithm Knuth shuffle and wrong-row formula