If you want to walk the list in a random order ("without replacement" in the vernacular), then you need something to maintain state, and be aware of the size of your list (both initially and at each call).

Your claims of no spare memory make this difficult. Either you need a scheme that implicitly keeps track of which elements have already been returned, or you need to explicitly keep track of them.

On the explicit front, you can keep a record in a bit vector, with one bit for each element already used. However, to get the last element of a large list, using a PRNG will take a long time.

On the implicit front, you need an iterator thats reasonably random, yet is exactly uniformly distributed regardless of the size of your list. This makes me think of a prime modulo operation:

#!/your/perl/here use strict; use warnings; { # closure for "static" variables my $mult = 2**15-1; my $offset = 76543; my $state = 0; sub get_rand { my $list = shift; # ref $state = ($state*$mult+$offset)%scalar(@{$list}); return $list->[$state]; } sub init_get_rand { my $list = shift; $state = rand(scalar(@{$list})); } } my $list = [0..17]; for (1..2) { init_get_rand($list); for ( 1..@{$list} ) { print get_rand($list), " "; } print "\n"; } __OUTPUT__ 8 9 16 11 12 1 14 15 4 17 0 7 2 3 10 5 6 13 2 3 10 5 6 13 8 9 16 11 12 1 14 15 4 17 0 7
Now, I'll be the first to admit I haven't checked on good values for $mult, $offset, or whether lists of certain sizes will cause you to miss values, etc. But you should be able to look up a good PRNG on your own ;)

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re: Random 1-1 mapping by QM
in thread 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.