in reply to Re: Perl - Unique Numbers
in thread Perl - Unique Numbers

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

Replies are listed 'Best First'.
Re^3: Perl - Unique Numbers
by flexvault (Monsignor) on Oct 18, 2015 at 02:12 UTC

    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.

        deelinux,

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

        No, his code prints 10 numbers. Where do you see that he saves anything?

        His loop handling is definitely non-Perl. He could just have done:
        for ( 1..10 )
        For such a trivial problem, if he had one previous response, I wouldn't have commented at all. When I posted, I was the 3rd comment, so I added the 'another way of doing' phrase.

        Regards...Ed

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