Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
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
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
Node Status?
node history
Node Type: note [id://1043750]
help
Chatterbox?
[Happy-the-monk]: Discipulus: most other Europeans must wait until 8 May for that day.

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-04-25 09:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?