You're correct. I didn't test the code well, and seem to have gotten several things backward or out of whack. Here's properly tested code (I hope):
#!/your/perl/here use strict; use warnings; my $str="17:43:33:21:23:19:27:6"; my %hash=split/:/,$str; my $count; my %ad_lookup; foreach my $k(keys %hash) { $count += $k; $ad_lookup{$count} = $hash{$k}; } my @ad_lookup_sorted_keys = sort {$b <=> $a} keys %ad_lookup; my %seen; for my $rand ( 1..$count ) { # my $rand = rand($count); my $adid; foreach my $key ( @ad_lookup_sorted_keys ) { if ( $rand <= $key ) { $adid = $ad_lookup{$key}; } else { last; } } # print "$adid\n"; $seen{$adid}++; } foreach my $k ( sort {$a <=> $b} keys %seen ) { print "\$seen{$k}: $seen{$k}\n"; }
Which outputs:
$seen{6}: 27 $seen{19}: 23 $seen{21}: 33 $seen{43}: 17
[There would be a slight shift going back to rand, because of the 0..99 and 1..100 difference. I believe you just need to change:
$ad_lookup{$count} = $hash{$k};
to:
$ad_lookup{$count-1} = $hash{$k};
]

I should note there are several ways to do this and get it right, and this is but one. Also, the key sort is only done once. A binary search on the keyspace would be faster, if there are many keys, but I'd estimate you would need a hundred keys or so to make it worth while. [Feel free to test that if you like]

-QM
--
Quantum Mechanics: The dreams stuff is made of


In reply to Re^3: $str to %hash to @ary by QM
in thread $str to %hash to @ary by abaxaba

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.