Problems? Is your data what you think it is? PerlMonks

### Re: grouping numbers

by ww (Archbishop)
 on Jul 11, 2013 at 12:44 UTC ( #1043713=note: print w/replies, xml ) Need Help??

Serious Error: "can't even get this to work" is not recognized as a valid error description.

Seriously, you'll need to tell us more about what you expected or want; why the output deviates from your heart's desire; and -- tho none appear when I test or execute your code -- error messages or warnings received from code you haven't shown.

If I've misconstrued your question or the logic needed to answer it, I offer my apologies to all those electrons which were inconvenienced by the creation of this post.

Replies are listed 'Best First'.
Re^2: grouping numbers
by ag4ve (Monk) on Jul 11, 2013 at 13:03 UTC

Seriously? The code runs fine for me.

The expected output of the code or what I'd like. Since I'm not sure if I'm on the right track with the code, what I'd like are three sets with 5,7,10,10, 50, and 70,72,75,79,80.

I'm not sure how else to explain this - between the code I'm stuck on, the use case, and abstract....?

What is significant about those groups of numbers?

Michael
Oh, they're 'close' together.

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://1043713]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (5)
As of 2018-04-20 07:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (75 votes). Check out past polls.

Notices?