shuffle.ts
· 439 B · TypeScript
Raw
/**
* Fisher-Yates shuffle algorithm, based on these answers:
* https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
*/
export function shuffle<T>(arr: T[]): T[] {
let ret = [...arr];
for (let i = ret.length - 1; i >= 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
if (i === j) continue;
const x = ret[i]!;
ret[i] = ret[j]!;
ret[j] = x;
}
return ret;
}
| 1 | /** |
| 2 | * Fisher-Yates shuffle algorithm, based on these answers: |
| 3 | * https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array |
| 4 | */ |
| 5 | export function shuffle<T>(arr: T[]): T[] { |
| 6 | let ret = [...arr]; |
| 7 | for (let i = ret.length - 1; i >= 0; i--) { |
| 8 | const j = Math.floor(Math.random() * (i + 1)); |
| 9 | if (i === j) continue; |
| 10 | const x = ret[i]!; |
| 11 | ret[i] = ret[j]!; |
| 12 | ret[j] = x; |
| 13 | } |
| 14 | return ret; |
| 15 | } |