aboutsummaryrefslogtreecommitdiff
path: root/challenge-059/mohammad-anwar/perl
diff options
context:
space:
mode:
authorMohammad S Anwar <mohammad.anwar@yahoo.com>2020-05-06 14:51:19 +0100
committerMohammad S Anwar <mohammad.anwar@yahoo.com>2020-05-06 14:51:19 +0100
commit1f2dcb66b72603a6c730235fc9813105fb80d3e6 (patch)
tree66529802d76f2976f2c342808df1f66ba053b81e /challenge-059/mohammad-anwar/perl
parent0d01f67611f47df33dced823eb50a8a5e231dc8f (diff)
downloadperlweeklychallenge-club-1f2dcb66b72603a6c730235fc9813105fb80d3e6.tar.gz
perlweeklychallenge-club-1f2dcb66b72603a6c730235fc9813105fb80d3e6.tar.bz2
perlweeklychallenge-club-1f2dcb66b72603a6c730235fc9813105fb80d3e6.zip
- Added Perl solutions to the "Bit Sum" task.
Diffstat (limited to 'challenge-059/mohammad-anwar/perl')
-rw-r--r--challenge-059/mohammad-anwar/perl/ch-2.pl38
-rw-r--r--challenge-059/mohammad-anwar/perl/ch-2a.pl46
2 files changed, 84 insertions, 0 deletions
diff --git a/challenge-059/mohammad-anwar/perl/ch-2.pl b/challenge-059/mohammad-anwar/perl/ch-2.pl
new file mode 100644
index 0000000000..534646d355
--- /dev/null
+++ b/challenge-059/mohammad-anwar/perl/ch-2.pl
@@ -0,0 +1,38 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Algorithm::Combinatorics qw(combinations);
+
+print &s([2, 3, 4]);
+
+sub s {
+ my ($A) = @_;
+
+ my $sum = 0;
+ foreach my $pair (combinations($A, 2)) {
+ $sum += f(@$pair);
+ }
+
+ return $sum;
+}
+
+sub f {
+ my ($a, $b) = @_;
+
+ $a = sprintf("%b", $a);
+ $b = sprintf("%b", $b);
+
+ my $m = length($a) > length($b) ? length($a) : length($b);
+ my $f = '%0'.$m.'d';
+ my @a = split //, sprintf $f, $a;
+ my @b = split //, sprintf $f, $b;
+
+ my $bits = 0;
+ foreach (0..$m-1) {
+ $bits += 1 if ($a[$_] != $b[$_]);
+ }
+
+ return $bits;
+}
diff --git a/challenge-059/mohammad-anwar/perl/ch-2a.pl b/challenge-059/mohammad-anwar/perl/ch-2a.pl
new file mode 100644
index 0000000000..bed6b32f44
--- /dev/null
+++ b/challenge-059/mohammad-anwar/perl/ch-2a.pl
@@ -0,0 +1,46 @@
+#!/usr/bin/perl
+
+use Test::More;
+
+use Algorithm::Combinatorics qw(combinations);
+
+my $unit_tests = [
+ { in => [1, 2, 3], out => 4 },
+ { in => [2, 3, 4], out => 6 },
+];
+
+foreach my $unit_test (@$unit_tests) {
+ is (&s($unit_test->{in}), $unit_test->{out});
+}
+
+done_testing;
+
+sub s {
+ my ($A) = @_;
+
+ my $sum = 0;
+ foreach my $pair (combinations($A, 2)) {
+ $sum += f(@$pair);
+ }
+
+ return $sum;
+}
+
+sub f {
+ my ($a, $b) = @_;
+
+ $a = sprintf("%b", $a);
+ $b = sprintf("%b", $b);
+
+ my $m = length($a) > length($b) ? length($a) : length($b);
+ my $f = '%0'.$m.'d';
+ my @a = split //, sprintf $f, $a;
+ my @b = split //, sprintf $f, $b;
+
+ my $bits = 0;
+ foreach (0..$m-1) {
+ $bits += 1 if ($a[$_] != $b[$_]);
+ }
+
+ return $bits;
+}