Answer the question
In order to leave comments, you need to log in
How to shuffle an array the same way for everyone?
We have an array (for example) [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
. And there is a number, for example 12837823632
, it changes periodically (I get it from the server).
I need to mix this array on the client, based on the given number. So that if the site is open on 10 devices, the mixing result will be the same. For example, [1, 2, 1, 3, 3, 2, 1, 1, 2, 3, 3, 2, 2, 1, 3]
. But at the same time, the result must be unique, not the same as it was with the previous number.
If you use Math.random()
, then, of course, the result will be different on all devices.
In which direction to dig?
Answer the question
In order to leave comments, you need to log in
Pseudorandom
let arr = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3];
var seed = 12837823631;
arr = arr.sort((a,b)=>rand() - rand());
function rand(){
seed = (45 * seed + 21) % 67;
return seed/67;
}
Here is an algorithm for shuffling an array if you have a deterministic rand() function that you have initialized with some kind of seed.
for (i = 1; i<arr.length; ++i) {
let j = floor(rand()*(i+1));
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
function rand(){
seed = (16,807*seed) % 2,147,483,647;
return seed/2,147,483,647;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question