http://qs1969.pair.com?node_id=552199

tomazos has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to write a simple shuffling function...

sub shuffle($$$) { my ($seed, $max, $input) = @_; # $max > $input # $max > 0 # $input >= 0 my $result; # calculate $result # $result >= 0 # $result < $max return $result }

...such that shuffle($K1, $K2, $x) == shuffle($K1, $K2, $y) if and only if $x == $y.

shuffle returns a semi-random number.

This could be used to iterate randomly over a read-only list in-place.

ie

get_rand(\@$$) { my ($list, $seed, $input) = @_; return $list->[shuffle($seed, scalar(@$list), $input)]; } my $list = [10, 20, 30, 40, 50, 60]; for (my $i = 0; $i < scalar(@$list); $i++) { print get_rand($list, 42, $i) . ' '; } # might print 40 10 20 60 30 50

Any math geniuses out there care to fill in the calculate $result part? I'm sure it has something to do with moding and hashing and stuff.

(No, this isn't a homework question. :) I actually need it to iterate randomly over a list in a resource-constrained embedded environment where I can't move the memory around - and haven't got spare memory. I knew I shouldn't have slept through my CS lectures.)

Thanks in advance.

-Andrew.