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