in reply to Generating 0 .. N Randomly and Efficiently

This looks like shuffling a deck of cards. Wouldn't it be easier to create an array of the appropriate size, populate it, shuffle it, and then print the numbers?

#!/usr/bin/perl use strict; use warnings; my $SIZE = 10; my @a = (0..$SIZE); for (@a) { my $i = int(rand($SIZE+1)); ($a[$i],$a[$_])=($a[$_],$a[$i]) } print "$_\n" for @a;

Hope this helped,
-v
"Perl. There is no substitute."

Replies are listed 'Best First'.
Re^2: Generating 0 .. N Randomly and Efficiently
by Limbic~Region (Chancellor) on Oct 19, 2004 at 16:23 UTC
    Velaki,
    Wouldn't it be easier...

    Yes of course, but that's not the point. The point is to learn new things by removing tools (memory) from the toolbox.

    Cheers - L~R

      How does Velaki's solution use more memory (except maybe for (@a), which could be replaced with for ($j=0; $j<@a; $j++))?

      Update: Ah yes, you return an interator instead of building an actual list.

        ikegami,
        As you noted, the list is never constructed - there is only an iterator that finds the next randomly chosen number. Additionally, a bitstring is compact. If you wanted to generate 0 .. 80_000_000, it would create a bitstring only about 1 mb in size.

        Cheers - L~R