in reply to Summing up duplicate lines

The specification is still vague. What should the third value be if it's not the same, e.g. [0, 5, 1] and [0, 5, 2]? Also, in what order should the triplets be printed?

The following code uses the order of the first appearance of the first two columns, and uses the third value from the first occurrence.

Update: The %seen hash contains the index into the @out array, i.e. the index of the first occurrence of the two values.

#!/usr/bin/perl use strict; use feature qw{ say }; use warnings; my %seen; my @out; while (<DATA>) { my @n = /-?[0-9]+/g; if ($n[0] == 0 || $n[1] == 0) { if (exists $seen{"@n[0, 1]"}) { $out[ $seen{"@n[0, 1]"} ][$_] += $n[$_] for 0, 1; } else { push @out, \@n; $seen{"@n[0, 1]"} = $#out; } } else { push @out, \@n; } } say "[@$_]" for @out; __DATA__ [ -1, 5, 1 ], [ 0, 5, 1 ], [ 0, 5, 1 ], [ 1, 5, 1 ], [ 3, 4, 1 ], [ 5, 1, 1 ], [ 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 ],

Output:

[-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]

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Summing up duplicate lines
by oko1 (Deacon) on May 08, 2024 at 20:07 UTC

    You're right - I didn't even think to specify this. There's no case in which the third value can be different among repeats, so it's not an issue. As to the order of the triplets, it would be the original one except for the "collapsed" ones.

    Your solution looks great - thank you, much appreciated!

    -- 
    I hate storms, but calms undermine my spirits.
     -- Bernard Moitessier, "The Long Way"