Now, this is obviously inefficient, because it must rebuild a list of keys each time, which can be bad for large hashes (like a hash representing a dictionary). Now, one possible solution is an array and a hash working together:# ($k,$v) = rhe_1(%hash); sub rhe_1 (\%) { my $key = (keys %{ $_[0] })[rand keys %{ $_[0] }]; return ($key, delete $_[0]{$key}); }
That trades the slowness of splice() for the possible slowness of having to reselect a random index. However, this requires an extra N amount of memory allocated.# @keys = keys %hash; # done ONCE # ($k,$v) = rhe_2(%hash,@keys); sub rhe_2 (\%\@) { my $key; do { $key = rand @keys } until exists $_[0]{$_[1][$key]}; return ($_[0]{$_[1][$key]}, delete $_[0]{$_[1][$key]}); }
I'd be glad to hear any ideas.# %seen = (); # done ONCE # @array = ([k,v], [k,v], ...); # ($k,$v) = rhe_3(@array,%seen); sub rhe_3 (\@\%) { my $idx; do { $idx = rand @{ $_[0] } } while $_[1]{int $idx}++; return @{ $_[0][$idx] }; }
|
---|
Replies are listed 'Best First'. | |
---|---|
(tye)Re: Efficient random hash stuff
by tye (Sage) on Nov 17, 2000 at 01:18 UTC | |
by japhy (Canon) on Nov 17, 2000 at 01:28 UTC | |
by tye (Sage) on Nov 17, 2000 at 01:34 UTC | |
by japhy (Canon) on Nov 17, 2000 at 01:40 UTC | |
Re: Efficient random hash stuff
by Dominus (Parson) on Nov 17, 2000 at 01:24 UTC | |
by japhy (Canon) on Nov 17, 2000 at 01:30 UTC | |
Re: Efficient random hash stuff
by Fastolfe (Vicar) on Nov 17, 2000 at 01:25 UTC |