in reply to (tye)Re: Efficient random hash stuff
in thread Efficient random hash stuff

Wow, that's damn nice. And we could use my just-an-array idea from above:
sub rand_element (\@); @array = ([1,2], [3,4], [5,6]); # etc... ($k,$v) = rand_element(@array); sub rand_element (\@) { my $aref = shift; my $idx = rand @$aref; my ($k,$v) = @{ $aref->[$idx] }; my $last = pop @$aref; $aref->[$idx] = $last if $idx < @$aref; return ($k,$v); }
Thank you muchly, tye. I need to ++ YOU, not your node...

$monks{japhy}++ while $posting;

Replies are listed 'Best First'.
(tye)Re2: Efficient random hash stuff
by tye (Sage) on Nov 17, 2000 at 01:34 UTC

    Note that ([1,2],[3,4],[5,6],...) consumes quite a bit more memory (no, I haven't tested this) than ( [1,3,5,...], [2,4,6,...] ). I agree that this is less elegant, but if memory usage is a primary concern, then the elegance loss might be worth it.

            - tye (but my friends call me "Tye")
      Ok, modified thus:
      sub rand_element (\@); @array = ([1,3,5], [2,4,6]); # [keys], [values] ($k,$v) = rand_element(@array); sub rand_element (\@) { my $aref = shift; my $idx = rand @{$aref->[0]}; my ($k,$v) = ($aref->[0][$idx], $aref->[1][$idx]); my @last = (pop @{$aref->[0]}, pop @{$aref->[1]}); ($aref->[0][$idx],$aref->[1][$idx]) = @last if $idx < @{$aref->[0]}; return ($k,$v); }
      While not tested, I do belive it works -- the code has been changed only to allow for the different structure.

      Thanks again, tye/Tye.

      $monks{japhy}++ while $posting;