in reply to Check randomly generated numbers have not been used before
Presumably you want to be able to generate unique part numbers across many runs of the program and thus need to keep a tally of those already issued. (Issuing part numbers at random is a bit weird, why not just allocate the next one in order? But c'est la vie.)
This will generate N unique part numbers each run without duplicates quite efficiently. It uses a singlefile, just over a megabyte in size, for the db:
#! perl -slw use strict; use constant TALLY => 'tally.bin'; our $N //= 50; my $tally = chr(0) x (10e6 / 8 ); if( -e TALLY ) { open I, '<:raw', TALLY or die $!; my $tally = do{ local $/; <I> }; close I; } sub genPartNo {{ my $partNo = int( 1e6 + rand( 9e6 ) ); redo if vec( $tally, $partNo, 1 ); vec( $tally, $partNo, 1 ) = 1; return $partNo; }} print genPartNo for 1 .. $N; open O, '>:raw', TALLY or die $!; printf O "%s", $tally; close O;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Check randomly generated numbers have not been used before
by oiskuu (Hermit) on Jun 20, 2014 at 23:22 UTC | |
by BrowserUk (Patriarch) on Jun 21, 2014 at 00:52 UTC |