Embed Notice
HTML Code
Corresponding Notice
- Embed this notice@mint @MK2boogaloo @Moon @Zerglingman @allison @gaybot @meso I don't like that they added the "--random-sort" bit to sort(1); it seemed like that should be a different program. On Plan 9, I put a Fischer-Yates shuffle into an awk script:
{a[NR]=$0}
END {
srand()
for(i=length(a); i>1; i--) {
n = 1+sprintf("%d", rand()*(i-1))
t = a[i]
a[i] = a[n]
a[n] = t
}
for(i in a)
print a[i]
}
Before that, on Linux, I'd do this by exploiting some behavior in mawk/gawk that reorders associative arrays by key; mawk doesn't like this behavior but it duplicated the behavior anyway. gawk requires you to seed the RNG, mawk auto-seeds. It's also less perfect than Fischer-Yates, but it works well enough for "random sort" use if not "really unbiased random-sort for the NSA", but it's much shorter:
BEGIN { srand() }
{ a[rand() $0] = $0 }
END { for(k in a) print(a[k]) }