Predictable Javascript array shuffle

≯℡__Kan透↙ 提交于 2020-01-11 09:43:28

问题


I'm trying to predictably shuffle javascript arrays the same way each time the webpage is loaded.

I can shuffle the arrays randomly, but every time i reload the page it's a different sequence.

I'd like it to shuffle the arrays the same way every time the page loads. There are many arrays and they are part of a procedurally generated world.


回答1:


Chance.js worked perfectly. Thank you Billy Moon.

My Example:

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

As long as you set the seed with new Chance(xxx) you get the same result every time.




回答2:


Take a look at chancejs.com's seed function.




回答3:


In order to shuffle an array in a seemingly random and predetermined way, you can break the problem into two parts.

1. Generate pseudo random numbers

You could use a different PRNG, but the Xorshift is very simple, fast to both initialise and step through, and evenly distributed.

This function takes an integer as a seed value, and returns a random function that always returns the same floating point values in the range 0 to 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. Shuffle using configurable random function

The Fisher Yates shuffle is an efficient shuffle algorithm with even distribution.

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
}

Putting it together

// 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/predictable-javascript-array-shuffle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!