Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re^2: grouping numbers

by ag4ve (Monk)
on Jul 11, 2013 at 13:03 UTC ( #1043718=note: print w/replies, xml ) Need Help??

in reply to Re: grouping numbers
in thread grouping numbers

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....?

Replies are listed 'Best First'.
Re^3: grouping numbers
by mtmcc (Hermit) on Jul 11, 2013 at 13:30 UTC

    What is significant about those groups of numbers?

    Perl can't mind read.

      Oh, they're 'close' together.
        Compared to -5000 and +5000, they're all 'close' together.

        I think you first need to think about how you would like to define 'close together' and 'far apart' in practical terms, and when you've worked that out, write some code.

        I'm happy to be corrected if I'm missing something...

        Good luck!
Re^3: grouping numbers
by poj (Monsignor) on Jul 11, 2013 at 15:11 UTC

    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"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1043718]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2018-06-18 06:48 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (109 votes). Check out past polls.