diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2022-05-06 23:46:46 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-05-06 23:46:46 +0100 |
| commit | 848f9f1d7b9fdedab03803706867895821d02b8b (patch) | |
| tree | 49985dd0d3c97277bde56761fdbeabfd6e692323 | |
| parent | d6e29224059e3c12dca475e4aa5a6bfe20a1a4c4 (diff) | |
| parent | 2773576ffe70e8cedc3b088352b604262f64b837 (diff) | |
| download | perlweeklychallenge-club-848f9f1d7b9fdedab03803706867895821d02b8b.tar.gz perlweeklychallenge-club-848f9f1d7b9fdedab03803706867895821d02b8b.tar.bz2 perlweeklychallenge-club-848f9f1d7b9fdedab03803706867895821d02b8b.zip | |
Merge pull request #6058 from choroba/ech163
Solve 163: Sum Bitwise Operator & Summations by E. Choroba
| -rwxr-xr-x | challenge-163/e-choroba/perl/ch-1.pl | 22 | ||||
| -rwxr-xr-x | challenge-163/e-choroba/perl/ch-2.pl | 25 |
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'; |
