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.


In reply to Random 1-1 mapping by tomazos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.