Array shuffling, the most recent direct idea is to randomly take an element from an array and put it in another array, but the elements to be removed are duplicated, and a certain way must be ensured:
1. Elements cannot be duplicated
2. The probability of the element being extracted is equal, namely randomness
There are two classical algorithms of array shuffling:
1. Fisher-yates Shuffle (complexity (N^2))
The deletion of the array and the new copy array are both time-and space-consuming.
JavaScript implementation
function Fyshuffle (arr) { var copy = [], = arr.length, N; while (len) = Math.floor (Math.random () * len--); Res.push (Arr.splice (n,1) [0]); } return copy;}
2. Knuth-durstenfeld Shuffle (n), an improved version of the fisher-yates algorithm)
kd method is a In-place replacement method, saving space, performance, and randomness, Python built-in random.shuffle used this algorithm.
JavaScript implementation
function Kdshuffle (arr) { var len = arr.length, i,temp; while (len) { = Math.floor (Math.random () * len--); = Arr[i]; = Arr[len]; = temp; } return arr;}
Reference: http://www.cnblogs.com/Wayou/p/fisher_yates_shuffle.html
Http://www.cnblogs.com/tudas/p/3-shuffle-algorithm.html
Array shuffling algorithm-shuffle