Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-20 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found