aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLuis Mochan <mochan@fis.unam.mx>2023-03-21 19:29:06 -0600
committerLuis Mochan <mochan@fis.unam.mx>2023-03-21 19:29:06 -0600
commit0f80fec7fbf53a1da397910e6c95da28ba79ef7b (patch)
tree8f8e20d236b06880d9b6550d460faa18e9801f3e
parentecdc3f8651ad777dfac7a10d4af0aee18ef4f772 (diff)
downloadperlweeklychallenge-club-0f80fec7fbf53a1da397910e6c95da28ba79ef7b.tar.gz
perlweeklychallenge-club-0f80fec7fbf53a1da397910e6c95da28ba79ef7b.tar.bz2
perlweeklychallenge-club-0f80fec7fbf53a1da397910e6c95da28ba79ef7b.zip
Changed strategy for task 2
-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;