The hard bit about this appears to be filling in the "gaps" in the histogram. If the histogram was huge, then I suppose that a hash table would be best, filling in the "gaps" on the output. But in this case an array representation appears to be quite good. To find the maximum "peg" value, a numeric sort of the values and taking the last one in that list appears to me to be a good way to go. I think that
jwkrahn was very close. Update: Well I suppose it is also possible that I've made the problem more complex than it needed to be!
#!/usr/bin/perl -w
use strict;
my %hash = qw (
a 2
b 4
c 2
d 1
e 1
f 2
g 4
h 3
i 8
j 10
k 10
);
my @values = sort{$a<=>$b}values(%hash);
my $max = (@values)[-1];
my @pegs = (0) x ($max);
for my $value ( @values )
{
$pegs[ $value ]++;
}
for my $peg_num (0..@pegs-1)
{
print "$peg_num \t=> $pegs[$peg_num]\n";
}
__END__
Prints:
0 => 0
1 => 2
2 => 3
3 => 1
4 => 2
5 => 0
6 => 0
7 => 0
8 => 1
9 => 0
10 => 2
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.