in reply to Summing up duplicate lines
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]
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Summing up duplicate lines
by oko1 (Deacon) on May 08, 2024 at 20:07 UTC |