CoderZone.org

Category: >> Perl Code >> Generate unique strings of random numbers Bookmark and Share

<< lastnext >>

Snippet Name: Generate unique strings of random numbers

Description: This code snippet will produce strings of numbers (1 thru 49) with no repeated numbers in the same string and no duplicated string of numbers in the list of strings.

Comment: (none)

Author: CoderZone
Language: PERL
Highlight Mode: PERL
Last Modified: March 05th, 2009

use warnings;
use strict;
 
my $length = 7; # the amount of numbers per string
my $max = 1000; # the number of strings
my @strings; # array to store the strings
for (1..$max) {
   push @strings, rand_nums($length);
}
print "$_\n" for @strings;
 
{
   my %cache; # create a "static" variable
   sub rand_nums {
      my %local_cache; # create a new hash
      my ($length) = @_; # the length of the random number string passed to the sub
      my $serial = int(rand(49))+1; # get the first number for the serialized string
      $local_cache{$serial} = 1; # store the first number in the hash
      for (2..$length) {# start at 2 because we already have the first number
         my $num = int(rand(49))+1; # get a new random number
         redo if exists $local_cache{$num}; # redo the loop if the number already exists
         $local_cache{$num} = 1; # store the number in the hash
         $serial .= "-$num"; # append to the serialized string
      }
      rand_nums($length) if exists $cache{$serial}; # redo the function if the key already exists
      $cache{$serial}=1; # store the new key in the hash (%cache)
      return $serial;
   }
}
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 11