Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^3: grouping numbers

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


in reply to Re^2: grouping numbers
in thread 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1043750]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-20 00:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found