perlquestion
tomazos
I'm trying to write a simple shuffling function...
<p>
<code>sub shuffle($$$) {
my ($seed, $max, $input) = @_;
# $max > $input
# $max > 0
# $input >= 0
my $result;
# calculate $result
# $result >= 0
# $result < $max
return $result
}</code>
<p>
...such that shuffle($K1, $K2, $x) == shuffle($K1, $K2, $y) if and only if $x == $y.
<p>
shuffle returns a semi-random number.
<p>
This could be used to iterate randomly over a read-only list in-place.
<p>
ie
<p>
<code>
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
</code>
<p>
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.
<p>
(No, this <b>isn't</b> 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.)
<p>
Thanks in advance.
<p>
-Andrew.