aboutsummaryrefslogtreecommitdiff
path: root/2018/lib/Utils.pm6
blob: 5b955d3aa3c93413d6236078beb42f164b8ed8be (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
use v6;

grammar Day3 is export {
    token TOP { <id> " @ " <position> ": " <size> }
    token id { "#" \d+ }
    token position { $<left> = [\d+]","$<top>=[\d+] }
    token size { $<width>=[\d+]"x"$<height>=[\d+] }
}

sub parse-input(--> List) is export { $*IN.lines.List }

sub to-int(Str @input --> List) is export { @input.map: *.Int }

sub dd-matrix(@m) {
    for ^@m.shape[0] -> \i {
        my $s = "";
        for ^@m.shape[1] -> \j {
            $s~=@m[i;j];
        }
        say "[" ~ $s.comb.join(", ") ~ "]";
    }
}

sub levenshtein($s, $t) is export {
    my $m = $s.chars;
    my $n = $t.chars;
    my int32 @d[$m+1;$n+1] = (0 xx $n+1) xx $m+1;

    for 1..$m { @d[$_;0] = $_ };
    for 1..$n { @d[0;$_] = $_ };

    for 1..$n -> \j {
        for 1..$m -> \i {
            my $sub-cost = 0;
            if $s.comb[i-1] ne $t.comb[j-1] {
                $sub-cost = 1;
            }
            @d[i;j] = (@d[i-1;j] + 1,
                       @d[i;j-1] + 1,
                       @d[i-1;j-1] + $sub-cost).min;
        }
    }

    return @d[$m;$n];
}