可预测的Javascript数组改组

Pro*_*pop 3 javascript arrays random repeat

我正在尝试每次加载网页时都以相同的方式随机播放javascript数组。

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

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

Bil*_*oon 5

看一下chancejs.com 的seed功能。


Pro*_*pop 5

Chance.js完美运行。谢谢Billy Moon。

我的例子:

<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" ]
Run Code Online (Sandbox Code Playgroud)

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


Bil*_*oon 5

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

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
}
Run Code Online (Sandbox Code Playgroud)

2. 使用可配置的随机函数进行随机播放

Fisher Yates 洗牌是一种高效的均匀分布洗牌算法。

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
}
Run Code Online (Sandbox Code Playgroud)

把它放在一起

// 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 ]
Run Code Online (Sandbox Code Playgroud)