in reply to Summing up duplicate lines

Your description leaves too much room for interpretation.

I assume you just want to "collapse" consecutive lines and you don't care about "repetitions" which are separated.

Hence no %seen hash is needed, just remember the $last line aka array and compare it to the $current one.

If the $current one fits your criteria add it to $last, if it doesn't print $last and make $last=$current for the next iteration.

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Summing up duplicate lines
by LanX (Saint) on May 09, 2024 at 12:52 UTC
    Here we go, implementing it revealed more ambiguities

    use v5.12; use warnings; use Data::Dump; my @in = do { local $/; eval <DATA> }; sub DBG { ddx @_ if 0 } # debug DBG "INPUT"=> @in; my @out; my $similarity = 3; # number equal elements my $last = shift @in; my $sum = [ @$last ]; # init while ( my $cur = shift @in ) { my @zeros = grep { $cur->[$_] == 0 } 0..1; my @same = grep { $cur->[$_] == $last->[$_] } 0..$similarity-1; if ( @zeros and @same == $similarity ) { my $non_zero = 1 - $zeros[0]; DBG "SUM" => $last, $cur, \@zeros, $non_zero ; $sum->[$non_zero] += $cur->[$non_zero]; } else { DBG "OUT" => $last, $cur, \@zeros; push @out, $sum; $last = $cur; $sum = [ @$last ]; # init } } push @out, $sum; dd @out; __DATA__ [ -1, 5, 1 ], [ 0, 5, 1 ], [ 0, 5, 1 ], [ 1, 5, 1 ], # separated repetitions # [ 0, 5, 1 ], # [ 0, 5, 1 ], [ 3, 4, 1 ], [ 5, 1, 1 ], # Testcases for ambiguities #[ 1000,0,1], #[ 5, 0, 1000 ], [ 5, 0, 1 ], [ 5, 0, 1 ], [ 5, 0, 1 ], [ 5, 0, 1 ], [ 5, 0, 1 ], [ 5, 0, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ 0, -5, 1 ], [ -23, -64, 0 ], [ -5, 0, 1 ], [ -5, 1, 1 ],

    ( [-1, 5, 1], [0, 10, 1], [1, 5, 1], [3, 4, 1], [5, 1, 1], [30, 0, 1], [0, -45, 1], [-23, -64, 0], [-5, 0, 1], [-5, 1, 1], )

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

    update

    fixed final push @out, $sum;

Re^2: Summing up duplicate lines
by oko1 (Deacon) on May 09, 2024 at 22:06 UTC

    Heh, perhaps that's something else that was under-specified in my question. :) I understand the idea behind it - it's not a complex one - but my brain was just refusing to produce the code to match it. It was just a weird day when I was unable to focus (for Various But Definite Reasons); any programmer who's been around a while has seen this pattern many times.
    I certainly appreciate the help you folks provided, though!

    -- 
    I hate storms, but calms undermine my spirits.
     -- Bernard Moitessier, "The Long Way"
      Actually, this collapsing/ folding was harder to implement than I thought. Too many off-by-one edge cases.

      Still looking into simplifying the code.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery