aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLubos Kolouch <lubos@kolouch.net>2021-01-30 11:25:30 +0100
committerLubos Kolouch <lubos@kolouch.net>2021-01-30 12:43:43 +0100
commitd48082057e95d265cb72f38fc4cf3c91ffa12cc1 (patch)
tree0b0d89e1952ad55270e2439e68693284c5425713
parente9c74676c298b1c5ae8245a2b143528dd1a10026 (diff)
downloadperlweeklychallenge-club-d48082057e95d265cb72f38fc4cf3c91ffa12cc1.tar.gz
perlweeklychallenge-club-d48082057e95d265cb72f38fc4cf3c91ffa12cc1.tar.bz2
perlweeklychallenge-club-d48082057e95d265cb72f38fc4cf3c91ffa12cc1.zip
Task 2 Challenge 097 LK Perl
-rw-r--r--challenge-097/lubos-kolouch/perl/ch-2.pl54
1 files changed, 54 insertions, 0 deletions
diff --git a/challenge-097/lubos-kolouch/perl/ch-2.pl b/challenge-097/lubos-kolouch/perl/ch-2.pl
new file mode 100644
index 0000000000..9294a08f79
--- /dev/null
+++ b/challenge-097/lubos-kolouch/perl/ch-2.pl
@@ -0,0 +1,54 @@
+#!/usr/bin/perl
+#===============================================================================
+#
+# FILE: ch-2.pl
+#
+# USAGE: ./ch-2.pl
+#
+# DESCRIPTION: Perl Weekly Challenge 097
+# Task 2
+# Binary Substrings
+#
+# AUTHOR: Lubos Kolouch
+# CREATED: 01/30/2021 10:11:26 AM
+#===============================================================================
+
+use strict;
+use warnings;
+use feature qw/say/;
+use Data::Dumper;
+use List::Util qw/min/;
+
+sub binary_substrings {
+ my $what = shift;
+
+ my $inp_bin = $what->[0];
+ my $split_nr = $what->[1];
+
+
+ # count 0s and 1s at each position
+
+ my %counts;
+
+ my $pos = 0;
+ for (split '', $inp_bin) {
+ $counts{$pos}{$_}++;
+ $pos++;
+ $pos = $pos % $split_nr;
+ }
+
+ # if both positions exist, count the smaller one
+ my $flips = 0;
+
+ for my $key (keys %counts) {
+ $flips += min(values %{$counts{$key}}) if (defined $counts{$key}{'0'}) and (defined $counts{$key}{'1'});
+ }
+
+ return $flips;
+}
+
+use Test::More;
+
+is(binary_substrings(['101100101', 3]), 1);
+is(binary_substrings(['10110111', 4]), 2);
+done_testing;