Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^6: Perl - Unique Numbers

by dsheroh (Monsignor)
on Oct 19, 2015 at 12:06 UTC ( [id://1145318]=note: print w/replies, xml ) Need Help??


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

Again, take a closer look at his code.

His loop is not equivalent to for (1 .. 10). Rewriting his loop in a more "conventional" way, it's equivalent to:

while (keys %numbers < 10) { my $num = int( rand 20 ) + 1; $numbers{$num}++; }
It will loop until there are 10 keys in %numbers, which means that 10 distinct numbers have been chosen, since hashes can't have duplicate keys.

Where do you see that he saves anything?

Because the value associated with the key is incremented each time that value is chosen, the keys will "save" the list of distinct numbers chosen, while the values will "save" the number of times each one came up.

His loop handling is definitely non-Perl.

I think we'll just have to disagree on that one. I find

$numbers{int(rand(20))+1}++ while keys %numbers < 10;
to be far more idiomatically Perlish than the "conventional" equivalent I provided above.

P.S. You seem to have gotten your attributions crossed. I'm not deelinux.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-26 06:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found