• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# 随机数和数组乱序

4周前 (10-30) 18次浏览

https://juejin.im/post/6844903863812620296

## 随机数

py的numpy里有很多种随机算法, 最常用的是线性分布和正太分布, js里面用的不多

``````const size = 1000;
const count = 100000;
const list = Array(size).fill(0);
for (let i = 0; i < count; i++) {
const v = (Math.random() * size) | 0;
list[v]++;
}

console.log("[" + list.join(",") + "],");
``````

https://chancejs.com/

``````const random = require("random");
const size = 1000;
const count = 100000;
const list = Array(size).fill(0);
const f = random.uniformInt(0, size - 1)
for (let i = 0; i < count; i++) {
const v = f()
list[v]++;
}
console.log("[" + list.join(",") + "],");
``````

## 数组乱序

``````const random = require("random");
const _ = require("lodash");
function test_shuffle(shuffleFn) {
// 多次乱序数组的次数
let n = 100000;
// 保存每个元素在每个位置上出现的次数
let countObj = {
a: Array.from({ length: 10 }).fill(0),
b: Array.from({ length: 10 }).fill(0),
c: Array.from({ length: 10 }).fill(0),
d: Array.from({ length: 10 }).fill(0),
e: Array.from({ length: 10 }).fill(0),
f: Array.from({ length: 10 }).fill(0),
g: Array.from({ length: 10 }).fill(0),
h: Array.from({ length: 10 }).fill(0),
i: Array.from({ length: 10 }).fill(0),
j: Array.from({ length: 10 }).fill(0),
};
for (let i = 0; i < n; i++) {
let arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
arr = shuffleFn(arr);
countObj.a[arr.indexOf("a")]++;
countObj.b[arr.indexOf("b")]++;
countObj.c[arr.indexOf("c")]++;
countObj.d[arr.indexOf("d")]++;
countObj.e[arr.indexOf("e")]++;
countObj.f[arr.indexOf("f")]++;
countObj.g[arr.indexOf("g")]++;
countObj.h[arr.indexOf("h")]++;
countObj.i[arr.indexOf("i")]++;
countObj.j[arr.indexOf("j")]++;
}
console.table(countObj);
}

const shuffleFn = (list) => {
for (let i = 0; i < list.length - 1; i++) {
const j = random.int(i, list.length - 1);
const t = list[i];
list[i] = list[j];
list[j] = t;
}
return list;
};
//
test_shuffle(shuffleFn);
// test_shuffle(_.shuffle)
``````