Let's assume that you have the following array:
javascriptlet array = [1, 2, 3, 4];
You can sort it randomly by:
javascriptlet shuffle = array.map((e, i, a) => { // Getting a random value between [i, a.length] // Math.floor can be translated as ~~ let j = Math.floor(Math.random() * (a.length - i) + i); // Switching the elements of positions i & j [a[i], a[j]] = [a[j], a[i]]; // Returning current value return a[i]; }); console.log(shuffle); // [4, 2, 3, 1]
In one line of code:
javascriptlet shuffle = array.map((e, i, a, j = ~~(Math.random() * (a.length - i) + i)) => ([a[i], a[j]] = [a[j], a[i]], a[i]));
Now you need to check if the distribution is uniform. Create a test of the function and generate the random array a several number of times:
javascriptlet test = {}; for(let i = 0; i < 10000; i ++){ let array = [1, 2, 3, 4]; let shuffle = array.map((e, i, a, j = ~~(Math.random() * (a.length - i) + i)) => ([a[i], a[j]] = [a[j], a[i]], a[i])); let string = shuffle.join(''); if(test[string] >= 0) test[string] ++; else test[string] = 0; }
Here you have the total times an array has been created.
For example, the array [1, 2, 4, 3]
has been created 396 times.
console.log(test); /* 1234: 418 1243: 396 1324: 425 1342: 364 1423: 420 1432: 396 2134: 434 2143: 413 2314: 399 2341: 429 2413: 423 2431: 395 3124: 351 3142: 434 3214: 409 3241: 448 3412: 421 3421: 451 4123: 397 4132: 429 4213: 437 4231: 428 4312: 429 4321: 430 */
It looks like a uniform distribution, because all the possible results have been created with equal probabilty.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.