in reply to Re: random number with range
in thread random number with range

An interesting way to do it. But expensive in memory and time for large ranges. Consider:

my @range = ( -1_000_000 .. 1_000_000 ); my $random_number = $range[rand(@range)];

which takes about 1/2 a second and has about a 100 MB dynamic memory requirement.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^3: random number with range
by ikegami (Patriarch) on Jun 01, 2006 at 18:06 UTC

    Indeed, but the technique is particularly useful for sets. For example,

    my @set = ( 1, 2, 3, 5, 8, 13, 21 ); my $random = $set[rand(@set)];
    my @set = qw( apple orange banana cucumber ); my $random = $set[rand(@set)];
Re^3: random number with range
by Enlil (Parson) on Jun 01, 2006 at 18:17 UTC
    won't disagree, but first thing that came to mind for similar situations where the technique is useful, like the ubiquitous password generator:
    my @chars = ( 'A' .. 'Z', 0 .. 9); my $pw = join('',@chars[ map { rand @chars } ( 1 .. 12 ) ]);