1 Replies - 1640 Views - Last Post: 13 January 2009 - 12:55 PM

#1 KevinADC   User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 401
  • Joined: 23-January 07

Random Numbers Generator

Posted 23 January 2007 - 07:30 PM

Description: Will generate a list of random numbers using a hash to insure unique numbers in the final list. After looking over born2c0de's random number generator snippet I thought it could be done a different way using a hash so I whipped this up loosely based on his code.
#!/usr/bin/perl

use strict;
use warnings;

# This is the range of numbers to
# use to generate random sequences from.
my @numbers = (1..49);

# This is how many numbers to generate.
# This number must be lower than the 
# total amount of numbers in the above list
# otherwise the script will go into an
# infinite loop.
my $limit = 11;

# A hash used to make sure we have
# all unique numbers in the final list. 
my %list = ();

# Here we generate the list of random 
# unique numbers. The hash continues to
# build until there are $limit number
# of keys. Since hash keys must be unique
# we are left with all unique numbers 
# without having to check anything except the
# total number of keys.
while (keys %list < $limit) {
   $list{$numbers[rand @numbers]}=1;
} 

# print unsorted list of numbers
print join(' ',keys %list);
print "n------------------------------n";
# print sorted (ascending) list of numbers
print join(' ', sort {$a <=> $b} keys %list);


Is This A Good Question/Topic? 0
  • +

Replies To: Random Numbers Generator

#2 souri_sen   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 21-December 08

Re: Random Numbers Generator

Posted 13 January 2009 - 12:55 PM

good code
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1