From e6637c1fa40ab6bba1cfa7d7faf46481b6b65643 Mon Sep 17 00:00:00 2001 From: Stephen Lynn Date: Sun, 6 Aug 2023 22:24:19 +0800 Subject: pwc 228 --- challenge-228/steve-g-lynn/blog.txt | 1 + challenge-228/steve-g-lynn/perl/ch-1.pl | 30 ++++++++++++++++++++++++++++++ challenge-228/steve-g-lynn/perl/ch-2.pl | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 challenge-228/steve-g-lynn/blog.txt create mode 100755 challenge-228/steve-g-lynn/perl/ch-1.pl create mode 100755 challenge-228/steve-g-lynn/perl/ch-2.pl diff --git a/challenge-228/steve-g-lynn/blog.txt b/challenge-228/steve-g-lynn/blog.txt new file mode 100644 index 0000000000..3c6d6118e4 --- /dev/null +++ b/challenge-228/steve-g-lynn/blog.txt @@ -0,0 +1 @@ +https://thiujiac.blogspot.com/2023/08/pwc-228.html diff --git a/challenge-228/steve-g-lynn/perl/ch-1.pl b/challenge-228/steve-g-lynn/perl/ch-1.pl new file mode 100755 index 0000000000..e387a8010b --- /dev/null +++ b/challenge-228/steve-g-lynn/perl/ch-1.pl @@ -0,0 +1,30 @@ +#!/usr/bin/env -S perl -wl + + +print &unique_sum(2,1,3,2); #4 +print &unique_sum(1,1,1,1); #0 +print &unique_sum(2,1,3,4); #10 + +sub unique_sum { + my @int = @_; + + #-- %int : hash to count frequency of each element of @int, + #-- $retval : return value + my (%int, $retval); + + #initialize %int values, $retval, to zero + $retval=0; + map {$int{$_}=0} @int; + + #-- loop thru' @int counting frequencies and updating $retval + map { + $int{$_}++; + + ($int{$_} > 1) ? + ( ($int{$_} == 2) ? ($retval -= $_) : 1 ) + : ($retval += $_); + } @int; + $retval; +} + + diff --git a/challenge-228/steve-g-lynn/perl/ch-2.pl b/challenge-228/steve-g-lynn/perl/ch-2.pl new file mode 100755 index 0000000000..10d42856a4 --- /dev/null +++ b/challenge-228/steve-g-lynn/perl/ch-2.pl @@ -0,0 +1,32 @@ +#!/usr/bin/env -S perl -wl + +print &empty_array(3,4,2); #5 +print &empty_array(1,2,3); #3 + +sub empty_array { + my @int=@_; + my $retval=0; #-- return value + + #-- assuming unique ints + #-- skipping input validation chores + + my %indx; + #-- %indx: index of each element + + my @int_sorted = sort {$a <=> $b} @int; + + while (scalar @int) { + map { + $indx{$int[$_]} = $_; + } 0 .. $#int; + + $retval += $indx{$int_sorted[0]} + 1; + + splice(@int,$indx{$int_sorted[0]},1); + shift(@int_sorted); + } + + $retval; +} + + -- cgit