diff options
| author | Gustavo L. de M. Chaves <gustavo@cpqd.com.br> | 2021-01-25 22:00:47 -0300 |
|---|---|---|
| committer | Gustavo L. de M. Chaves <gustavo@cpqd.com.br> | 2021-01-25 22:00:47 -0300 |
| commit | d795df786aac20eb8dbb2eef3aac670b0c407bf1 (patch) | |
| tree | 0102f4aec1f2d5186ed71dfadeb80b14ace94c5b | |
| parent | 3d3900a2f0f69c54a34683e4e1b5da007b4af9d9 (diff) | |
| download | perlweeklychallenge-club-d795df786aac20eb8dbb2eef3aac670b0c407bf1.tar.gz perlweeklychallenge-club-d795df786aac20eb8dbb2eef3aac670b0c407bf1.tar.bz2 perlweeklychallenge-club-d795df786aac20eb8dbb2eef3aac670b0c407bf1.zip | |
Add Gustavo Chaves's solutions to challenge 097
| -rwxr-xr-x | challenge-097/gustavo-chaves/perl/ch-1.pl | 21 | ||||
| -rwxr-xr-x | challenge-097/gustavo-chaves/perl/ch-2.pl | 36 |
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)"; |
