in reply to Generating random 6 digit numbers
#!perl -w @nums = 100000 .. 999999; # Generate all the possible numbers ## Shuffle them (use a better rand if needed) $_ ne ($a=int( rand( $#nums-$_+1))+$_) and $nums[$_] ^= $nums[$a] ^= $ +nums[$_] ^= $nums[$a] for (0..$#nums); print pop@nums; # pop a new one each time you need it
The array takes about 50 seconds to initialise and shuffle (on my quite whimpy box) but much less storage than using a hash of the same size.
There are less obfu versions of the Fisher-Yates shuffle around too, but this one was handy.
Update: Having read your later posts regarding using the numbers during different runs of the program, I realise you need to save the array somewhere.
Not having made any use of the available persistant storage mechanisms that perl provides, I'd probably do something like:
#!perl -w @nums = 100000 .. 999999; # Generate all the possible numbers ## Shuffle them (use a better rand if needed) $_ ne ($a=int( rand( $#nums-$_+1))+$_) and $nums[$_] ^= $nums[$a] ^= $ +nums[$_] ^= $nums[$a] for (0..$#nums); open OUT, '>randoms' or die $!; print OUT pack 'I*', @numbs; close OUT or warn $!;
And then whenI needed one of them
.... open RNDNUM, '<randoms' or die $!; binmode(RNDNUMS); # If needed! seek RNDNUMS, -4, 2; my $newlen = tell RNDNUM; my $rndnum = do { local $/=\4; unpack 'I',<RNDNUM>; } truncate RNDNUM, $newlen or die $!; close RNDNUM or warn $!; ..... # do whatever with $rndnum
... but that's cos I know how to make this work. The second bit of code is untested, but demos the basic mechanism of pre-generating your random numbers and storing them somewhere, and then throwing them away once you've used them.
Whatever you do, don't generate a random number and then try to verify whether you've used it before. That's a recipe for disaster wasteful.
It will seem ok at first, but once your halfway through your range, you are going to (statistically) have to generate 450,000 random numbers before you find one that you haven't used before!
(I just KNOW a mathematician is gonna correct that last bit:)
Updated: removed falacious Infinite Improbability Drivel* cos the mathematician did!
With apologies to Douglas Adams RIP
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Generating random 6 digit numbers
by Anonymous Monk on Aug 25, 2002 at 18:42 UTC | |
by BrowserUk (Patriarch) on Aug 25, 2002 at 19:07 UTC | |
by Anonymous Monk on Aug 25, 2002 at 19:39 UTC | |
by BrowserUk (Patriarch) on Aug 25, 2002 at 19:48 UTC | |
by sauoq (Abbot) on Aug 26, 2002 at 19:49 UTC | |
by Adam Kensai (Sexton) on Aug 26, 2002 at 12:46 UTC | |
Re: Re: Generating random 6 digit numbers
by ehdonhon (Curate) on Aug 26, 2002 at 04:28 UTC | |
by BrowserUk (Patriarch) on Aug 26, 2002 at 06:52 UTC |