in reply to easy way to get random key from hash?
You can see where this is going: choose the nth element if rand() < 1 / n. Translated to Perl this gives something like:
sub choose { my $count = 0; my $result = undef; for( @_ ) { $result = $_ if rand() < 1 / ++$count; } $result; } my $jokekey = choose( keys %knockknocks );
This actually chooses from a list, but then that's what the keys of a hash are, so everything is fine.
The beauty of this approach is that you don't need to know beforehand how many elements you have to choose from. That is, the array in question may shrink or grow in the course of the program's run, and the algorithm will compensate. In fact, you may be able to skip loading the hash in the first place, depending on system load. Just read through the file fortune-at-a-time, and cache the file pointer offset instead. Then, at the end of the file seek back to the cached position and read from there. This means you will be able to add fortunes without having to restart the process.
I first heard about this technique in a book by Jon Bentley, either _Programming Pearls_ or _More Programming Perls_. They are probably verging on the edge of being out of print, but if you can track them down, they are absolute gems.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: easy way to get random key from hash?
by jsprat (Curate) on Aug 05, 2002 at 19:53 UTC | |
|
Re: Re: easy way to get random key from hash?
by Aragorn (Curate) on Aug 05, 2002 at 19:38 UTC |