可预测的 Javascript 数组洗牌



每次加载网页时,我都试图以相同的方式对javascript数组进行可预测的洗牌。

我可以随机洗牌数组,但每次重新加载页面时,它都是不同的序列。

我希望它每次加载页面时都以相同的方式洗牌数组。有许多数组,它们是程序生成世界的一部分。

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" ]

只要你用新的Chance(xxx)设置种子,你每次都会得到相同的结果。

看看chancejs.com的seed函数。

为了以看似随机和预定的方式洗牌数组,您可以将问题分为两部分。

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. 使用可配置的随机函数进行随机洗牌

费舍尔耶茨洗牌是一种具有均匀分布的高效洗牌算法。

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 ]

最新更新