我尝试着在每次加载网页时都以同样的方式对javascript数组进行混洗。
我可以随机调整数组,但每次重新加载页面时都会有不同的顺序。
我希望它在每次页面加载时都以相同的方式对数组进行混洗。有许多数组,它们是程序生成的世界的一部分。
发布于 2015-02-01 05:30:36
Chance.js运行得非常完美。谢谢你比利·穆恩。
我的例子:
<script type="text/javascript" src="assets/js/chance.js"></script>
var chance1 = new Chance(124); // you can choose a seed here, i chose 124
console.log(chance1.shuffle(['alpha', 'bravo', 'charlie', 'delta', 'echo']));
// Array [ "alpha", "delta", "echo", "charlie", "bravo" ]只要你用新的机会(Xxx)设置种子,你每次都会得到相同的结果。
发布于 2015-02-01 05:11:54
看一看chancejs.com's seed函数。
发布于 2019-04-03 02:00:32
为了以看似随机和预先确定的方式对数组进行混洗,可以将问题分成两部分。
1.生成伪随机数
你可以使用不同的PRNG,但是Xorshift非常简单,初始化和单步执行都很快,而且分布均匀。
此函数接受一个整数作为种子值,并返回一个随机函数,该函数始终返回0到1范围内的相同浮点值。
const xor = seed => {
const baseSeeds = [123456789, 362436069, 521288629, 88675123]
let [x, y, z, w] = baseSeeds
const random = () => {
const t = x ^ (x << 11)
;[x, y, z] = [y, z, w]
w = w ^ (w >> 19) ^ (t ^ (t >> 8))
return w / 0x7fffffff
}
;[x, y, z, w] = baseSeeds.map(i => i + seed)
;[x, y, z, w] = [0, 0, 0, 0].map(() => Math.round(random() * 1e16))
return random
}2.使用可配置的随机函数进行混洗
Fisher Yates shuffle是一种分布均匀的高效混洗算法。
const shuffle = (array, random = Math.random) => {
let m = array.length
let t
let i
while (m) {
i = Math.floor(random() * m--)
t = array[m]
array[m] = array[i]
array[i] = t
}
return array
}把它们放在一起
// passing an xor with the same seed produces same order of output array
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(1))) // [ 3, 4, 2, 6, 7, 1, 8, 9, 5 ]
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(1))) // [ 3, 4, 2, 6, 7, 1, 8, 9, 5 ]
// changing the seed passed to the xor function changes the output
console.log(shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9], xor(2))) // [ 4, 2, 6, 9, 7, 3, 8, 1, 5 ]https://stackoverflow.com/questions/28256506
复制相似问题