Last active
March 6, 2023 16:45
-
-
Save joshwashywash/98303ea29775feb052b1c722adf921d0 to your computer and use it in GitHub Desktop.
shuffles an array in place
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
const swap = <T>(t: T[], i: number, j: number) => { | |
[t[i], t[j]] = [t[j], t[i]]; | |
}; | |
export const shuffle = <T>(t: T[]) => { | |
for (let i = t.length - 1; i > 0; i -= 1) { | |
const j = Math.floor(Math.random() * (i + 1)); | |
swap(t, i, j); | |
} | |
}; |
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
import { shuffle } from 'shuffle'; | |
const pokemon = [ | |
'squirtle', | |
'snorlax', | |
'haunter', | |
'mankey', | |
'mewtwo', | |
]; | |
shuffle(pokemon); | |
console.log(pokemon); // some new arrangement |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment