aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2019-07-07 19:21:44 +0100
committerGitHub <noreply@github.com>2019-07-07 19:21:44 +0100
commitd468219a2aed0a4971c0cfdd7ec98b295cf68522 (patch)
treed63a062fa12b315e6b80b421cac51c0d2a2ce68d
parent916f5b9f780eaaae1660f7b9e8da81b0bd6b0528 (diff)
parent136b6f74103473ddd5e2042f1fb148915cac4102 (diff)
downloadperlweeklychallenge-club-d468219a2aed0a4971c0cfdd7ec98b295cf68522.tar.gz
perlweeklychallenge-club-d468219a2aed0a4971c0cfdd7ec98b295cf68522.tar.bz2
perlweeklychallenge-club-d468219a2aed0a4971c0cfdd7ec98b295cf68522.zip
Merge pull request #345 from threadless-screw/threadless-screw-wk15ch2p6
Create ch-2.p6
-rw-r--r--challenge-015/ozzy/perl6/ch-2.p646
1 files changed, 46 insertions, 0 deletions
diff --git a/challenge-015/ozzy/perl6/ch-2.p6 b/challenge-015/ozzy/perl6/ch-2.p6
new file mode 100644
index 0000000000..d13136e24e
--- /dev/null
+++ b/challenge-015/ozzy/perl6/ch-2.p6
@@ -0,0 +1,46 @@
+#!/usr/bin/env perl6
+#
+# Vigenère-cipher encoder/decoder
+# Operates on capitalized input- and kextexts only
+#
+
+sub encode (Str $key where { 'A' le $key le 'Z' },
+ Str $plain where { 'A' le $plain le 'Z' })
+{
+ my $base = 'A'.ord; # unicode base point of alphabet
+ my $column_index = $plain.ord - $base; # calculate col.index of plaintext char on encoding row
+ my $alphab_index = (( $key.ord - $base ) + $column_index) % ('A'..'Z').elems; # calculate alphabet index of cipher character
+ my $cipher = ($base + $alphab_index).chr; # convert back to unicode code point
+ return $cipher;
+}
+
+
+
+sub decode (Str $key where { 'A' le $key le 'Z' },
+ Str $cipher where { 'A' le $cipher le 'Z' })
+{
+ my $base = $key.ord; # base/first letter of decoding row in Vignére table
+ my $column_index = $cipher.ord - $base; # column index of $cipher in Vignère table on decoding row
+ my $alphab_index = $column_index % ('A'..'Z').elems; # zero-based index of column index into alphabet
+ my $plain = ('A'.ord + $alphab_index).chr; # convert back to unicode code point
+ return $plain;
+}
+
+
+
+sub MAIN (Str $cmd, Str $inputtext, Str $keytext )
+{
+ my %commands = 'encode' => &encode,
+ 'decode' => &decode;
+
+ my &func = %commands{$cmd};
+ my @inputtext = $inputtext.uc.comb;
+ my @keytext = $keytext.uc.comb;
+ my $outputtext;
+
+ for 0..(@inputtext.elems - 1) -> $i {
+ my $keytext_index = $i % @keytext.elems;
+ $outputtext ~= &func(@keytext[$keytext_index], @inputtext[$i]);
+ }
+ say $outputtext;
+}