随机排列实现 -shuffle算法
洗牌算法(shuffle):原理是,一个数A,随机选一个在这个数A之前的下标,将这个下标对应数字与A对换;之后不再考虑最后的这一个数;
类似于无放回的抽签问题;
function shuffleArray(totalLength) {let randomArray = {}, randomIndex, temp;for (let i = 0; i < totalLength; i ++) {randomArray[i] = i;}//var randomArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};for (let i = totalLength - 1; i >= 0; i --) {randomIndex = Math.floor(Math.random() * (i + 1));temp = randomArray[randomIndex];randomArray[randomIndex] = randomArray[i];randomArray[i] = temp;}return randomArray;}