aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKUEPPO <tcheukueppo@tutanota.com>2022-11-26 13:27:58 +0100
committerGitHub <noreply@github.com>2022-11-26 13:27:58 +0100
commitfca8a2f283e4bcc5102a01446383978257bc6937 (patch)
tree788d54f31592ddc14a92f77366ae172bf03f3dbd
parentaa28bdcd814412b91226d2cb59b820538c03dc3c (diff)
downloadperlweeklychallenge-club-fca8a2f283e4bcc5102a01446383978257bc6937.tar.gz
perlweeklychallenge-club-fca8a2f283e4bcc5102a01446383978257bc6937.tar.bz2
perlweeklychallenge-club-fca8a2f283e4bcc5102a01446383978257bc6937.zip
ch-2.pl
-rw-r--r--challenge-192/kueppo-wesley/Perl/ch-2.pl59
1 files changed, 59 insertions, 0 deletions
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);