TIL randomize Arrays
POSTED ON:
TAGS: javascript
A one line helper function to randomize array items.
let arr = [1, 2, 3];
sortRandom(arr);
// arr = [3, 2, 1]
sortRandom(arr);
// arr = [2, 1, 3]
sortRandom(arr);
// arr = [3, 1, 2]
const sortRandom = (arr) => arr.sort(() => Math.random() - 0.5)
How it works #
That somewhat works, because Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.
NOTE: Not all permutations have the same probability.
To test, https://javascript.info/task/shuffle did a test looping that process a million times, and counting the results.
123: 250706 // WOAH
132: 124425
213: 249618 // WOAH
231: 124880
312: 125148
321: 125223
There are some other ways to do it, that are a bit longer of code to do better randomization.
But for your basic needs, this will do just fine.
The Better but longer way #
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
123: 166693
132: 166647
213: 166628
231: 167517
312: 166199
321: 166316
REFERENCE:
Via this: https://javascript.plainenglish.io/15-helpful-javascript-one-liners-946e1d1a1653
which pointed to this:
https://javascript.info/task/shuffle
Related TILs
Tagged: javascript