aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2022-11-26 12:49:33 +0000
committerGitHub <noreply@github.com>2022-11-26 12:49:33 +0000
commit9fb08c5841b630c28e5e9c846f6b8c10922dcabb (patch)
tree9f6765d3822a46ccbb0edc53dc04d125e91dea64
parent03c344e83446eef897827cb4a6bf11f92e7d4923 (diff)
parent4cfd8a9c7cea395bc193516a6c33572c5797dbfc (diff)
downloadperlweeklychallenge-club-9fb08c5841b630c28e5e9c846f6b8c10922dcabb.tar.gz
perlweeklychallenge-club-9fb08c5841b630c28e5e9c846f6b8c10922dcabb.tar.bz2
perlweeklychallenge-club-9fb08c5841b630c28e5e9c846f6b8c10922dcabb.zip
Merge pull request #7155 from tcheukueppo/pwc-192
Pwc 192
-rw-r--r--challenge-192/kueppo-wesley/Perl/ch-1.pl15
-rw-r--r--challenge-192/kueppo-wesley/Perl/ch-2.pl59
2 files changed, 74 insertions, 0 deletions
diff --git a/challenge-192/kueppo-wesley/Perl/ch-1.pl b/challenge-192/kueppo-wesley/Perl/ch-1.pl
new file mode 100644
index 0000000000..ad3725237b
--- /dev/null
+++ b/challenge-192/kueppo-wesley/Perl/ch-1.pl
@@ -0,0 +1,15 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+use Test::More;
+
+sub flip {
+ my $bin = "0b" . ( sprintf "%b", shift ) =~ tr[01][10]r;
+ return oct $bin;
+}
+
+is_deeply( [ map { flip($_) } qw/ 5 4 6 / ], [ 2, 3, 1 ], "well fliped?" );
+
+done_testing(1);
diff --git a/challenge-192/kueppo-wesley/Perl/ch-2.pl b/challenge-192/kueppo-wesley/Perl/ch-2.pl
new file mode 100644
index 0000000000..c2c4f1573a
--- /dev/null
+++ b/challenge-192/kueppo-wesley/Perl/ch-2.pl
@@ -0,0 +1,59 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+
+use Test::More;
+
+use List::Util qw/ sum /;
+
+sub equalize {
+ my @list = @_;
+ my $sum = sum @list;
+
+ # Cannot equally distribute without using floating points, so return.
+ return -1 if $sum % @list != 0;
+
+ my $move = 0;
+ my $target = $sum / @list;
+
+ while ( my ( $i, $v ) = each @list ) {
+
+ # Well, get this: no matter what, in the last iteration we are
+ # pretty pretty sure that `$v' is gonna be `$target'
+ next if $v == $target;
+
+ if ( $v < $target ) {
+ foreach my $j ( $i + 1 .. $#list ) {
+ if ( $list[$j] > $target ) {
+ my $strip = $target - $v;
+
+ $list[$j] -= $strip;
+ $move += ( $j - $i ) * $strip;
+ last;
+ }
+ }
+ }
+ else {
+ my $step = $v - $target;
+
+ $move += $step;
+
+ # and as a result we are never gonna overflow.
+ $list[ $i + 1 ] += $step;
+ }
+
+ $list[$i] = $target;
+ }
+
+ return $move;
+}
+
+my %test_data = (
+ expected => [ 4, -1, 2, 21 ],
+ samples => [ [ 1, 0, 5 ], [ 0, 2, 0 ], [ 0, 3, 0 ], [ 9, 9, 2, 4, 1 ] ],
+);
+
+is_deeply( [ map { equalize(@$_) } $test_data{samples}->@* ], $test_data{expected}, "Equalized?" );
+
+done_testing(1);