aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2022-11-22 13:51:20 +0000
committerGitHub <noreply@github.com>2022-11-22 13:51:20 +0000
commit24493701dab7b14b718b622b889db571f2c2d4e0 (patch)
treed85e24485109b28c110d7979e63db6c662a1644a
parent5367d3436b633906fca7984ffb19362976ae0df2 (diff)
parent4e71199de32ec8a67f5adea04368747ec8e09e11 (diff)
downloadperlweeklychallenge-club-24493701dab7b14b718b622b889db571f2c2d4e0.tar.gz
perlweeklychallenge-club-24493701dab7b14b718b622b889db571f2c2d4e0.tar.bz2
perlweeklychallenge-club-24493701dab7b14b718b622b889db571f2c2d4e0.zip
Merge pull request #7137 from choroba/ech192
Add solutions to 192: Binary Flip & Equal Distribution by E. Choroba
-rwxr-xr-xchallenge-192/e-choroba/perl/ch-1.pl15
-rwxr-xr-xchallenge-192/e-choroba/perl/ch-2.pl33
2 files changed, 48 insertions, 0 deletions
diff --git a/challenge-192/e-choroba/perl/ch-1.pl b/challenge-192/e-choroba/perl/ch-1.pl
new file mode 100755
index 0000000000..e78a408479
--- /dev/null
+++ b/challenge-192/e-choroba/perl/ch-1.pl
@@ -0,0 +1,15 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental 'signatures';
+
+sub binary_flip ($n) { ~ $n & (2 ** (log ($n) / log 2) - 1) }
+
+use Test::More tests => 3 + 2;
+
+is binary_flip(5), 2, 'Example 1';
+is binary_flip(4), 3, 'Example 2';
+is binary_flip(6), 1, 'Example 3';
+
+is binary_flip(255), 0, '1x8';
+is binary_flip(256), 255, '1 . 0x8';
diff --git a/challenge-192/e-choroba/perl/ch-2.pl b/challenge-192/e-choroba/perl/ch-2.pl
new file mode 100755
index 0000000000..27bc4304fa
--- /dev/null
+++ b/challenge-192/e-choroba/perl/ch-2.pl
@@ -0,0 +1,33 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use experimental 'signatures';
+
+use List::Util qw{ sum };
+
+sub equal_distribution ($list) {
+ my $sum = sum(@$list);
+ if (0 == $sum % @$list) {
+ my $avg = $sum / @$list;
+ my $moves = 0;
+ my $sum_part = 0;
+ for my $i (0 .. $#$list) {
+ $sum_part += $list->[$i];
+ $moves += abs($sum_part - ($avg * ($i + 1)));
+ }
+ return $moves
+ } else {
+ return -1
+ }
+}
+
+use Test::More tests => 3 + 4;
+
+is equal_distribution([1, 0, 5]), 4, 'Example 1';
+is equal_distribution([0, 2, 0]), -1, 'Example 2';
+is equal_distribution([0, 3, 0]), 2, 'Example 3';
+
+is equal_distribution([1, 5, 0]), 3, '1-5-0';
+is equal_distribution([5, 1, 0]), 5, '5-1-0';
+is equal_distribution([3, 3, 0]), 3, '3-3-0';
+is equal_distribution([1, 0, 6, 2, 4, 7, 1]), 16, 'long';