aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2022-05-04 23:13:54 +0200
committerE. Choroba <choroba@matfyz.cz>2022-05-04 23:13:54 +0200
commit2773576ffe70e8cedc3b088352b604262f64b837 (patch)
tree92833b4bfbe93d04ab9406b94836418c337e2a13
parent00424daeddd40cc9d98cd1e4111541ddccd0f235 (diff)
downloadperlweeklychallenge-club-2773576ffe70e8cedc3b088352b604262f64b837.tar.gz
perlweeklychallenge-club-2773576ffe70e8cedc3b088352b604262f64b837.tar.bz2
perlweeklychallenge-club-2773576ffe70e8cedc3b088352b604262f64b837.zip
Solve 163: Sum Bitwise Operator & Summations by E. Choroba
-rwxr-xr-xchallenge-163/e-choroba/perl/ch-1.pl22
-rwxr-xr-xchallenge-163/e-choroba/perl/ch-2.pl25
2 files changed, 47 insertions, 0 deletions
diff --git a/challenge-163/e-choroba/perl/ch-1.pl b/challenge-163/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..cb637b4450
--- /dev/null
+++ b/challenge-163/e-choroba/perl/ch-1.pl
@@ -0,0 +1,22 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+sub sum_bitwise_operator {
+ my $sum = 0;
+ my %seen;
+ for my $i (1 .. $#_) {
+ for my $j (0 .. $i - 1) {
+ my @pair = sort { $a <=> $b } @_[$i, $j];
+ $sum += $pair[0] & $pair[1] unless $seen{"@pair"}++;
+ }
+ }
+ return $sum
+}
+
+use Test::More tests => 3;
+
+is sum_bitwise_operator(1, 2, 3), 3, 'Example 1';
+is sum_bitwise_operator(2, 3, 4), 2, 'Example 2';
+
+is sum_bitwise_operator(2, 2, 3, 3, 3), 7, 'Unique pairs with duplicates';
diff --git a/challenge-163/e-choroba/perl/ch-2.pl b/challenge-163/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..38d124f84d
--- /dev/null
+++ b/challenge-163/e-choroba/perl/ch-2.pl
@@ -0,0 +1,25 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+
+use List::Util qw{ sum };
+
+sub summations {
+ my @list = @_;
+ while (@list > 1) {
+ my @new_list;
+ my $s = 0;
+ for my $i (1 .. $#list) {
+ push @new_list, $s += $list[$i];
+ }
+ @list = @new_list;
+ }
+ return $list[0]
+}
+
+use Test::More tests => 3;
+
+is summations(1, 2, 3, 4, 5), 42, 'Example 1';
+is summations(1, 3, 5, 7, 9), 70, 'Example 2';
+
+is summations(1 .. 20), 6564120420, 'Large input';