数组乱序

96 阅读1分钟

偶然之间看了掘进上文章关于数组乱序的问题,想通过文章来记录个人的学习心得

const a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
// 随机数组的算法
function ajustArr (arr) { 
  let m = arr.length;
  while (m > 1) {
    let randomIndex = Math.floor(Math.random() * m--);
    [arr[m], arr[randomIndex]] = [arr[randomIndex], arr[m]];
  }
  return arr;
}
// 以下为验证随机数组算法的代码
const testCount = 10000;
function test () { 
  let arrLen = a.length;
  let countFrequency = {};
  for (let item of a) {
    // 也可以使用new Array(arrLen).fill(0)        
    countFrequency[item] = Array.from({length: arrLen}).fill(0);
  }
  for (let i = 0; i < testCount; i++) {
    ajustArr(a); 
    // 这里的j可理解为索引位置,即在哪个位置出现
    for (let j = 0; j < arrLen; j++) {
      // 每次生成随机数组后,计算元素在不同位置出现的频率
      // 例如,经过一次随机后,a数组变为:[a, e, b, c, h, d, f, g, j, i]
      countFrequency[a[j]][j]++;
    }
  }
  console.table(countFrequency)
}
test()