G'day SaktiMonk,
Welcome to the monastery.
Update: My original solution (now within <spoiler> tags below) didn't take into account uneven sized ranges. I didn't notice that but ++Laurent_R did (see below). Here's a new version that still uses an array (@bins) for the range counts; caches the results of determining the range; and still only uses one iteration per range to output the bin counts.
$ perl -Mstrict -Mwarnings -e ' use List::Util qw{first}; my @input = qw{12 14 15 20 21}; my @range_ends = qw{19 29 39}; my (@bins, %range_index_cache); sub get_range_index { ( first { $_[0] <= $range_ends[$_] } 0 .. $#range_ends ) // @r +ange_ends; } for (@input) { ++$bins[$range_index_cache{$_} //= get_range_index($_)]; } for (0 .. $#range_ends) { printf "%d-%d %d\n" => $_ ? $range_ends[$_ - 1] + 1 : 1, $range_ends[$_], $bins[$ +_] // 0; } ' 1-19 3 20-29 2 30-39 0
Any datapoints beyond the ranges you specify are counted in the last element of @bins.
[Note: If you're using an old version of Perl that doesn't have the // (Logical Defined-Or) operator, you'll need to use the defined function.]
-- Ken
In reply to Re: Perl hit counter for multiple ranges, optimization or options in other languages?
by kcott
in thread Perl hit counter for multiple ranges, optimization or options in other languages?
by SaktiMonk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |