aboutsummaryrefslogtreecommitdiff
path: root/challenge-088/pjdurai/raku/ch-2.p6
blob: a2fe17c22e882a18db0053b3b29a2bbb46bee24b (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
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
use Test;
# Solution algoritm.
# We peel layers (like a cake) from the top, then right, then bottom and left until nothing is left.
# String them together for solution.

# Solution walk through
# Input:
#    1 2 3
#    4 5 6
#    7 8 9
#
#    After taking the top layer, it becomes
#    4 5 6
#    7 8 9
#
#    Take the right layer off.
#    4 5
#    7 8
#
#    Take the bootom layer off
#
#    4 5
#
#    Take left layer off.
#    5
#
#    Finally tope layer again
#
#    []
#
#    Collect the removed items in a result list

sub solve(@M) {

    my @directions = |<top right bottom left> xx *;

    my $num-rows = @M.elems;
    my $num-cols = @M[0].elems;

    my @result = reduce sub (@acc, $direction){
        given $direction {
            when 'top' {
                @acc.append(@(@M.shift));
            }
            when 'right' {
                my @right-col = do for @M -> $r {
                    $r.pop;
                }
                @acc.append(@right-col);
            }
            when 'bottom' {
                @acc.append(@M.pop.reverse);
            }
            when 'left' {
                my @left-col = do for @M -> $c {
                    $c.shift;
                }
                @acc.append(@left-col.reverse);
            }
        }
        @acc;
    }, [], |@directions[0..^($num-rows + $num-cols -1)];
}

sub MAIN(){
    my @M = [[  1,  2,  3,  4 ],
             [  5,  6,  7,  8 ],
             [  9, 10, 11, 12 ],
             [ 13, 14, 15, 16 ]];
    say "Problem: ", @M;
    say "Solution: ", solve (@M);

    say "";

    my @M1 = [[ 1, 2, 3 ],
             [ 4, 5, 6 ],
             [ 7, 8, 9 ]];

    say "Problem: ", @M1;
    say "Solution: ", solve (@M1);
}