3 ms·
Same number of keystrokes, but IMHO more idiomatic & readable: perl -ne '$x=$_ if rand()<=(1/$.); END { print $x }'
by microtherion 7y ago
Same number of keystrokes, but IMHO more idiomatic & readable:
perl -ne '$x=$_ if rand()<=(1/$.); END { print $x }'
- zengargoyle 7y agoHa, that's how I originally wrote it, but I thought I should get rid of -n and END{} in an attempt to ward of the eww Perl comments. Sigh. But at least now I know that it's called Reservoir Sampling. I had wondered how to generalize it to wanting N lines.