18.2 The shuffle problem and the probability of selecting m from n elements.

Source: Internet
Author: User
Tags shuffle

Shuffle: recursive thinking. If n-1 elements have been shuffled, the nth element should be from 0 ~ Select the switch destination within the range of N. Recursion to shuffle of an element.

 

N select M: If m has been selected for n-1 elements, the n-th element can be in the range of 0 ~ Select an element randomly within the range of n. If the selected element is within the range of M, remove the original element. Recursion until M is selected.

 

 Public   Void Shuffle ( Int  [] Cards) {random Rand = New  Random ();  For (Int I = 0; I <cards. length; I ++ ){  Int K = Rand. nextint (I + 1 );  Int TMP = Cards [k]; cards [k] = Cards [I]; cards [I] = TMP ;}}  Public Pick ( Int [] Origin, Int  M ){  Int N =Origin. length; random Rand = New  Random ();  Int [] Res = New   Int  [M];  For ( Int I = 0; I <m; I ++ ) {Res [I] = Origin [I];}  For ( Int I = m; I <n; I ++ ){ Int K = Rand. nextint (I + 1 );  If (K < M) {res [k] = Origin [I] ;}} 

 

18.2 The shuffle problem and the probability of selecting m from n elements.

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.