看播放器代码时发现的这个洗牌算法,再网上查了一番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; }