aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorE. Choroba <choroba@matfyz.cz>2022-11-21 23:44:10 +0100
committerE. Choroba <choroba@matfyz.cz>2022-11-21 23:44:10 +0100
commit4e71199de32ec8a67f5adea04368747ec8e09e11 (patch)
tree44d064c6a91cd198c38d67e6b855d36efb374119
parent62cd59ab1bc620f0a9a621801645f61b2afba4fe (diff)
downloadperlweeklychallenge-club-4e71199de32ec8a67f5adea04368747ec8e09e11.tar.gz
perlweeklychallenge-club-4e71199de32ec8a67f5adea04368747ec8e09e11.tar.bz2
perlweeklychallenge-club-4e71199de32ec8a67f5adea04368747ec8e09e11.zip
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';