Quick Search:
 
 Perl Code: Generate unique strings of random numbers Jump to:  
Category: >> Perl Code >> Generate unique strings of random numbers  

<< 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)

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;
   }
}


 
   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org