aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAbigail <abigail@abigail.be>2021-01-27 17:06:46 +0100
committerAbigail <abigail@abigail.be>2021-01-27 17:06:46 +0100
commit87492b8eeeb02a6325f056662b07cf9e773930a2 (patch)
treefbe3cc31c014bf4c30aa709aa72be2a5893a1a35
parent98186989bc5539fabdbaf4936b2dda608d833d0d (diff)
downloadperlweeklychallenge-club-87492b8eeeb02a6325f056662b07cf9e773930a2.tar.gz
perlweeklychallenge-club-87492b8eeeb02a6325f056662b07cf9e773930a2.tar.bz2
perlweeklychallenge-club-87492b8eeeb02a6325f056662b07cf9e773930a2.zip
Use the same algorithm for the perl solution as for other languages.
-rw-r--r--challenge-097/abigail/perl/ch-2.pl32
1 files changed, 24 insertions, 8 deletions
diff --git a/challenge-097/abigail/perl/ch-2.pl b/challenge-097/abigail/perl/ch-2.pl
index b0d145069e..179745252b 100644
--- a/challenge-097/abigail/perl/ch-2.pl
+++ b/challenge-097/abigail/perl/ch-2.pl
@@ -25,18 +25,34 @@ GetOptions 's=i' => \my $sections;
die "-s option required" unless defined $sections && $sections > 0;
#
-# To get the minimum number of flips, for each position take the
-# minimum of the number of 0s and the number of 1s, and sum over
-# all the positions
+# There is no need to split the input string into chunks,
+# we can leave it as is. The $i-th character of the $j-th section
+# is as position $j * $s_len + $i, where $s_len is the length
+# of a section.
+#
+# To calculate the minimum number of flips, for each position $i, we
+# calculate the number of 0s there are on the $i-th positions of
+# each section. Given the number of 0s, we can calculate the number
+# of 1s. The minimum number of flips required to get all the bits
+# on position equal is the minimum of the number of 0s and the number
+# of 1s.
+#
+# So, to calculate the minimum number of flips, for each postion,
+# we sum the minimum of the number of 0s and the number of 1s.
#
while (<>) {
- my $sum = 0;
chomp;
- my @chunks = /.{$sections}/g;
- for (my $i = 0; $i < length $chunks [0]; $i ++) {
- my $zeros = grep {substr ($_, $i, 1) eq "0"} @chunks;
- $sum += min $zeros, @chunks - $zeros;
+ my $s_len = length () / $sections;
+ my $sum = 0;
+ for my $i (0 .. $s_len - 1) {
+ my $zeros = 0;
+ for my $j (0 .. $sections - 1) {
+ my $index = $j * $s_len + $i;
+ $zeros ++ if substr ($_, $index, 1) eq "0";
+ }
+ my $ones = $sections - $zeros;
+ $sum += min ($zeros, $ones);
}
say $sum;
}