aboutsummaryrefslogtreecommitdiff
path: root/challenge-046/dave-jacoby/perl/ch-1.pl
blob: 51625098edb162f4e35b6e690d9a8b5c12eb7683 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw{ postderef say signatures state switch };
no warnings
  qw{ experimental::postderef experimental::smartmatch experimental::signatures };

my $str1 = q{
H x l 4 !
c e - l o
z e 6 l g
H W l v R
q 9 m # o
};

my $str2 = q{
P + 2 l ! a t o
1 e 8 0 R $ 4 u
5 - r ] + a > /
P x w l b 3 k \
2 e 3 5 R 8 y u
< ! r ^ ( ) k 0
};

for my $ctext ( $str1, $str2 ) {
    my $ptext = decypher($ctext);
    say $ptext;
}

sub decypher ( $ctext ) {
    # ctext = cyphertext, ptext = plaintext. common terms in cryptography.

    # this breaks the message into a two-dimensional array
    my @ctext = map { [ split /\s+/, $_ ] } grep { /\S/ } split m{\n}, $ctext;
    my @ptext;

    # for each row, we get every entry, and then use a hash to count
    # the times that each show up
    # then we pull the key with the max usage, push it into the
    #   plaintext array and join it and return it.
    for my $i ( 0 .. scalar $ctext[0]->@* - 1 ) {
        my %col;
        map { $col{ $_->[$i] }++ } @ctext;
        my ($k) = sort { $col{$b} <=> $col{$a} } keys %col;
        push @ptext, $k;
    }
    return join '', @ptext;
}