/
ch-2.p6
executable file
·96 lines (74 loc) · 2.25 KB
/
ch-2.p6
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!raku
sub build-grid( Str $passprhase ) {
my @grid;
my $counter = 0;
for $passprhase.comb {
# skip existing letters
next if @grid.grep( $_ );
next if $_ !~~ / <[ a .. z ]> /;
# insert this letter
@grid.push: $_;
@grid.push: '|' if ++$counter %% 5;
}
# add the other letters
unless ( @grid.grep( '|' ).elems == 5 ) {
for 'a' .. 'z' {
next if @grid.grep( $_ );
next if $_ ~~ / i /;
next if $_ ~~ / j /;
# insert this letter
@grid.push: $_;
@grid.push: '|' if ++$counter %% 5;
last if @grid.grep( '|' ).elems == 5;
}
}
# now split the array into a matrix
my @matrix;
for @grid.join.split( '|' ) {
next if ! $_;
@matrix.push: [ $_.comb ];
}
say @matrix;
return @matrix;
}
sub build-pairs( Str $needle ) {
my @mangled;
my @current;
for $needle.comb {
next if $_ ~~ / ' ' /;
@current.push: $_ if ! @mangled.grep( $_ );
@current.push: 'X' if @mangled.grep( $_ );
if @current.elems == 2 {
@mangled.push: [@current];
@current = ();
}
}
return @mangled;
}
sub MAIN() {
my @key-matrix = build-grid( 'playfair example' );
my @pairs = build-pairs( 'hide the gold in the tree stump' );
for @pairs -> @current-pair {
my @rectangle;
for 0 ..^ @current-pair {
my $current_letter = @current-pair[ $_ ];
my $found = False;
for 0 ..^ @key-matrix.elems -> $row {
for 0 ..^ 5 -> $column {
if @key-matrix[ $row ][ $column ] ~~ $current_letter {
# found!
@rectangle.push: ( row => $row, col => $column ).Hash;
$found = True;
}
last if $found;
}
last if $found;
}
}
say @current-pair.join;
say @rectangle;
say @rectangle[ 0 ].^name;
# my $is-rectangle = @rectangle[ 0 ]{ row } != @rectangle[ 1 ]{ row } && @rectangle[ 0 ]{ col } != @rectangle[ 1 ]{ col };
# say "rettangolo $is-rectangle";
}
}