nr a révisé ce gist 1 day ago. Aller à la révision
1 file changed, 15 insertions
shuffle.ts(fichier créé)
| @@ -0,0 +1,15 @@ | |||
| 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 | + | } | |
Plus récent
Plus ancien