Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Perl - Unique Numbers

by flexvault (Monsignor)
on Oct 17, 2015 at 19:27 UTC ( #1145218=note: print w/replies, xml ) Need Help??


in reply to Perl - Unique Numbers

Welcome deelinux

And another way of doing what you need:

use strict; use warnings; my $x = 1; my $y = 20; my $looptimes = 10; my %NoDups = (); while( 1 ) { my $num = int( 1 + rand( 19 ) ); if ( exists $NoDups{ $num } ) { next; } $NoDups{ $num } = 1; if ( keys %NoDups >= $looptimes ) { last; } } foreach my $no ( sort {$a<=>$b} keys %NoDups ) { print "$no\n"; }

Good Luck...Ed

"Well done is better than well said." - Benjamin Franklin

Replies are listed 'Best First'.
Re^2: Perl - Unique Numbers
by johngg (Canon) on Oct 17, 2015 at 23:08 UTC

    I don't think it really matters if the value for a particular number is more than one so the exists test is perhaps overkill. The keys count is what matters.

    $ perl -Mstrict -Mwarnings -E ' my %numbers; $numbers{ int( rand 20 ) + 1 } ++ while keys %numbers < 10; say for sort { $a <=> $b } keys %numbers;' 4 7 8 9 11 13 14 15 17 18 $

    I hope this is of interest.

    Cheers,

    JohnGG

      The OP stated:

        "...but every now and then I get duplicates in the list. I would like to remove the duplicates or not get one in the first place."

      How do you define 'duplicates'?

      Regards...Ed

      "Well done is better than well said." - Benjamin Franklin

        Take a closer look at how his code works. It keeps generating numbers until it has 10 unique numbers, then prints out a list of those 10 unique numbers. Even if a number has been chosen several times, it still counts as only one unique number and will only be printed once. Thus, no duplicates will appear in the output.

        The main difference between his code and yours is that, if a number is selected three times, yours will have a value of 1 in the hash for that key, while his will have a value of 3. But, since the values are never used for anything (you just output the keys and ignore the values), it doesn't matter either way.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1145218]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2020-09-19 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (114 votes). Check out past polls.

    Notices?