aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xchallenge-209/wlmb/perl/ch-2.pl27
1 files changed, 11 insertions, 16 deletions
diff --git a/challenge-209/wlmb/perl/ch-2.pl b/challenge-209/wlmb/perl/ch-2.pl
index e11b229f2c..46ad3198c8 100755
--- a/challenge-209/wlmb/perl/ch-2.pl
+++ b/challenge-209/wlmb/perl/ch-2.pl
@@ -5,25 +5,20 @@
# See https://wlmb.github.io/2023/03/20/PWC209/#task-2-merge-account
use v5.36;
use English;
-my %merge_to;
my %line_of;
my @names;
while(<>){
chomp;
my ($name, @addresses)=split / /;
- $names[$INPUT_LINE_NUMBER] = $name;
- $merge_to{$INPUT_LINE_NUMBER}=$INPUT_LINE_NUMBER; # merge to itself
- for(@addresses){
- my $l=$line_of{$_};
- $line_of{$_}=$INPUT_LINE_NUMBER;
- # merge overlapping accounts with current one
- $merge_to{$l}=$merge_to{$merge_to{$l}}=$INPUT_LINE_NUMBER if defined $l;
- }
+ next unless $name; # skip empty lines
+ $names[$INPUT_LINE_NUMBER]=$name;
+ my ($merged)=grep {defined $_} map {$line_of{$_}} @addresses;
+ $merged//=$INPUT_LINE_NUMBER; # current line by default
+ @line_of{@addresses}=($merged) x @addresses;
}
-my @addresses = keys %line_of; # distinct addresses
-my %merged; # merged accounts
-push @{$merged{$merge_to{$line_of{$_}}}}, $_ # add addresses to merged accounts
- for @addresses;
-# output account name, (one of its) line number(s), addresses
-say join " ", $names[$_], "($_):", sort {$a cmp $b} @{$merged{$_}}
- for sort {$names[$a] cmp $names[$b] || $a <=> $b} keys %merged;
+my %accounts;
+push @{$accounts{$line_of{$_}}}, $_ for(keys %line_of);
+# Sort output by account name and line number, and sort addresses
+say "$names[$_] ($_): ", join " ",
+ sort {$a cmp $b} @{$accounts{$_}}
+ for sort {$names[$a] cmp $names[$b] || $a <=>$b} keys %accounts;