Created
July 24, 2023 01:47
-
-
Save hungdoansy/f789984f7807e1f90090559b03135085 to your computer and use it in GitHub Desktop.
Shuffle a list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://stackoverflow.com/a/2450976/6812545 | |
const shuffle = <T>(array: T[]): T[] => { | |
let currentIndex = array.length, randomIndex; | |
// While there remain elements to shuffle. | |
while (currentIndex != 0) { | |
// Pick a remaining element. | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex--; | |
// And swap it with the current element. | |
[array[currentIndex], array[randomIndex]] = [ | |
array[randomIndex], array[currentIndex]]; | |
} | |
return array; | |
} | |
// Used like so | |
const arr = [2, 11, 37, 42]; | |
shuffle(arr); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment