aboutsummaryrefslogtreecommitdiff
path: root/challenge-097
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2021-01-26 15:01:05 +0000
committerGitHub <noreply@github.com>2021-01-26 15:01:05 +0000
commit20fcc2945bf76d5afe47d5274793edb9541aa20f (patch)
treedc55af238dffd98b0b14e56e9bc6220870655290 /challenge-097
parent3a1e6cf53bd1d9baf4ef67cb561055ec7bf14e50 (diff)
parentd795df786aac20eb8dbb2eef3aac670b0c407bf1 (diff)
downloadperlweeklychallenge-club-20fcc2945bf76d5afe47d5274793edb9541aa20f.tar.gz
perlweeklychallenge-club-20fcc2945bf76d5afe47d5274793edb9541aa20f.tar.bz2
perlweeklychallenge-club-20fcc2945bf76d5afe47d5274793edb9541aa20f.zip
Merge pull request #3387 from gnustavo/097
Add Gustavo Chaves's solutions to challenge 097
Diffstat (limited to 'challenge-097')
-rwxr-xr-xchallenge-097/gustavo-chaves/perl/ch-1.pl21
-rwxr-xr-xchallenge-097/gustavo-chaves/perl/ch-2.pl36
2 files changed, 57 insertions, 0 deletions
diff --git a/challenge-097/gustavo-chaves/perl/ch-1.pl b/challenge-097/gustavo-chaves/perl/ch-1.pl
new file mode 100755
index 0000000000..11a2d2f608
--- /dev/null
+++ b/challenge-097/gustavo-chaves/perl/ch-1.pl
@@ -0,0 +1,21 @@
+#!/usr/bin/env perl
+
+# https://perlweeklychallenge.org/blog/perl-weekly-challenge-097/
+# TASK #1 › Caesar Cipher
+
+use 5.030;
+use warnings;
+
+my ($N, $S) = @ARGV;
+
+# ($N, $S) = (3, "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG");
+
+my $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+my $caesar = substr($alphabet, -$N) . substr($alphabet, 0, length($alphabet) - $N);
+
+$alphabet .= lc $alphabet;
+$caesar .= lc $caesar;
+
+for ($S) {
+ say eval "tr/$alphabet/$caesar/r";
+}
diff --git a/challenge-097/gustavo-chaves/perl/ch-2.pl b/challenge-097/gustavo-chaves/perl/ch-2.pl
new file mode 100755
index 0000000000..bad7ffa917
--- /dev/null
+++ b/challenge-097/gustavo-chaves/perl/ch-2.pl
@@ -0,0 +1,36 @@
+#!/usr/bin/env perl
+
+# https://perlweeklychallenge.org/blog/perl-weekly-challenge-097/
+# TASK #2 › Binary Substrings
+
+use 5.030;
+use warnings;
+use List::AllUtils qw(sum0 pairwise reduce);
+
+my ($B, $S) = @ARGV;
+
+# ($B, $S) = qw(101100101 3);
+# ($B, $S) = qw(10110111 4);
+
+length($B) % $S == 0
+ or die "The length of the string '$B' must be a multiple of $S\n";
+
+my @substrings = $B =~ /(.{$S})/g;
+
+my (@distance, @flips);
+
+# Calculate the distances between each pair of substrings and the total number
+# of flips to change all of them to be equal to each one.
+for my $i (0 .. $#substrings) {
+ my @from = split //, $substrings[$i];
+ for my $j (0 .. $#substrings) {
+ my @to = split //, $substrings[$j];
+ $distance[$i][$j] = sum0 pairwise {$a != $b} @from, @to;
+ }
+ $flips[$i] = sum0 @{$distance[$i]};
+}
+
+# Find the index of the substring which requires the minimum number of flips.
+my $i = reduce {$flips[$a] < $flips[$b] ? $a : $b} 0 .. $#flips;
+
+say "$flips[$i] to make all substrings equal to '$substrings[$i]' ($i)";