E
E
Extramezz2020-08-16 10:57:23
JavaScript
Extramezz, 2020-08-16 10:57:23

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

4 answer(s)
V
Vitaly Stolyarov, 2020-08-16
@Ni55aN

https://github.com/skratchdot/random-seed

T
twobomb, 2020-08-16
@twobomb

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;
}

W
Wataru, 2020-08-16
@wataru

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;
}

You can use something like the function suggested by twobomb , but I don't recommend using that function - it will give a maximum of 67 different options, but in fact, much less. Use, for example, the parameters from here :
function rand(){
 	seed = (16,807*seed) % 2,147,483,647;
 	return seed/2,147,483,647;
}

X
xmoonlight, 2020-08-16
@xmoonlight

I asked a similar question.
Look .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question