看播放器代碼時發現的這個洗牌算法,再網上查了一番javascript
做用是把數組變成隨機序列,原理相似於從牌堆A中隨機抽牌放進牌堆Bjava
代碼1: 返回一個由(數組下標)組成的數組算法
function random(length) { function shuffle (arr) { for (let i = arr.length - 1; i >= 0; i--) { const randomIndex = Math.floor(Math.random() * (i + 1)); const itemAtIndex = arr[randomIndex]; arr[randomIndex] = arr[i]; arr[i] = itemAtIndex; } return arr; } return shuffle([...Array(length)].map(function (item, i) { return i; })); }
代碼2:數組
function shuffle(array) { var copy = [], n = array.length, i; // 若是還剩有元素則繼續。。。 while (n) { // 隨機抽取一個元素 i = Math.floor(Math.random() * array.length); // 若是這個元素以前沒有被選中過。。 if (i in array) { copy.push(array[i]); delete array[i]; n--; } } return copy; }