From 87492b8eeeb02a6325f056662b07cf9e773930a2 Mon Sep 17 00:00:00 2001 From: Abigail Date: Wed, 27 Jan 2021 17:06:46 +0100 Subject: Use the same algorithm for the perl solution as for other languages. --- challenge-097/abigail/perl/ch-2.pl | 32 ++++++++++++++++++++++++-------- 1 file 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; } -- cgit