Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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 (Prior) 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]
[LanX]: hmm could be a myth since the root of throne is Greek
[LanX]: erix : the one armed who spent his last years in Dorn castle was a prince of Oranie ;)
[erix]: why does that tell against the Kaiser-story?
[erix]: ah, of course, makes sense
[erix]: mafia are family based, of course

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2017-12-15 16:28 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (439 votes). Check out past polls.