Random shuffling algorithm Knuth shuffle and wrong-row formula

Source: Internet
Author: User
Tags random shuffle shuffle

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.