feat: add Random.shuffle() method using Fisher-Yates algorithm

Implement in-place shuffle for lists on the Random class, using the Fisher-Yates algorithm to ensure uniform permutation distribution. Includes documentation with usage examples, Wren source implementation, and a test suite covering empty lists, single-element lists, and verification that all 24 permutations of a 4-element list are reachable.
This commit is contained in:
Bob Nystrom
2016-02-07 18:38:39 +00:00
parent f1babe5ad4
commit 813594b14c
4 changed files with 67 additions and 0 deletions
+12
View File
@@ -46,4 +46,16 @@ foreign class Random {
foreign int()
int(end) { (float() * end).floor }
int(start, end) { (float() * (end - start)).floor + start }
shuffle(list) {
if (list.isEmpty) return
// Fisher-Yates shuffle.
for (i in 0...list.count - 1) {
var from = int(i, list.count)
var temp = list[from]
list[from] = list[i]
list[i] = temp
}
}
}
+12
View File
@@ -48,4 +48,16 @@ static const char* randomModuleSource =
" foreign int()\n"
" int(end) { (float() * end).floor }\n"
" int(start, end) { (float() * (end - start)).floor + start }\n"
"\n"
" shuffle(list) {\n"
" if (list.isEmpty) return\n"
"\n"
" // Fisher-Yates shuffle.\n"
" for (i in 0...list.count - 1) {\n"
" var from = int(i, list.count)\n"
" var temp = list[from]\n"
" list[from] = list[i]\n"
" list[i] = temp\n"
" }\n"
" }\n"
"}\n";