"be consistent" PerlMonks

### Re^3: grouping numbers

by poj (Monsignor)
 on Jul 11, 2013 at 15:11 UTC ( #1043750=note: print w/replies, xml ) Need Help??

in reply to Re^2: grouping numbers

Not sure if this is any use but is does give the expected output. It loops through the sorted list working out the effect of adding each to 'current group average'. If change is greater than the value 'diff' it starts a new group

```#!perl
use strict;

my @data = (10,7,5,10,50,70,75,72,79,80);
my @arr = sort {\$a<=>\$b} @data;
my \$diff = 2; # group closeness

my @avg; #[count,sum]
my @grp;
my \$g=0;

for my \$i (0..\$#arr){
my \$val = \$arr[\$i];
#print "value \$val\n";
if (\$i == 0){
push @{\$grp[\$g]},\$val;
\$avg[\$g] = [1,\$val];
} else {
#work out new average with this element
my (\$n,\$sum) = @{\$avg[\$g]};
#print "count \$n sum \$sum\n";
my \$avg = \$sum/\$n;
my \$new_avg = (\$sum+\$val)/(\$n+1);
if (abs(\$new_avg - \$avg) < \$diff){
# join group
push @{\$grp[\$g]},\$val;
\$avg[\$g] = [\$n+1,\$sum+\$val];
} else {
# start new group
++\$g;
push @{\$grp[\$g]},\$val;
\$avg[\$g] = [1,\$val];
}
}
}

for (@grp) {
print join ',',@\$_,"\n";
}
POJ

Create A New User
Node Status?
node history
Node Type: note [id://1043750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2018-10-20 02:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When I need money for a bigger acquisition, I usually ...

Results (111 votes). Check out past polls.

Notices?