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.