I want to randomly shuffle a list of 4 items but with a seed so that so long as you have the same seed the you will get the same order of items.
["a", "b", "c", "d"]
I figure I can get the seed with Math.random, I don't need something very exact. How do I sort according to the seed?
You can achieve this with a slight modification to Mike Bostock's implementation of the Fisher–Yates algorithm*:
*The
random
function is taken from this SO answer. It is a hack and not entirely random and most importantly not cryptographically secure! Here's a histogram of samples (also in the comments of that response, takes a while to run). Conclusively, you should only use this when these things don't really matter. Alternatively, substitute therandom
function with a better seedable random number generator.You can create random numbers to do the sorting using the XOR Shift method. Example. Then just replace
Math.random()
in your old code withnew Xor128(seed).make(3)[2] / 4294967296 * 2
SeededShuffle
Works on node and browser.
jsFiddle Demo
You would need to seed a random value for each value in the array as far as I can tell. In that regards, you would probably want to do something like this:
Where you are insuring that
length
is the same length that the seed is for. This would be 4 for your simple example. Once that was done, you could pass the seed into your shuffle (or sort) function to ensure that the same results were obtained. The shuffle would need to use it in a loop as wellSo here is what it all breaks down into
The seed function which will store the array of seeds
A pretty basic shuffle
Being used