aboutsummaryrefslogtreecommitdiff
path: root/2020/day5.raku
blob: 98151ef64435ec628b2eb8af055b07f97a943cca (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
sub binary-partition(@code, $from is copy, $to is copy, $lower, $upper --> Int) {
    for @code[0..*-1]  {
        when $lower { $to = ($from + $to) div 2 }
        when $upper { $from = (($from + $to) div 2) + 1 }
    }
    return @code[*-1] eq $lower ?? $from !! $to;
}

sub row(@code) {
    binary-partition(@code, 0, 127, 'F', 'B')
}

sub column(@code --> Int) {
    binary-partition(@code, 0, 7, 'L', 'R')
}

sub get-id($input) {
    my $row = row($input.comb[0..^7]);
    my $column = column($input.comb[7..^10]);
    ($row * 8) + $column
}

multi sub MAIN('part1', $file) {
    say $file.IO.lines.map(*.&get-id).max;
}

multi sub MAIN('part2', $file) {
    my $gap = $file.IO.lines.map(*.&get-id).sort.rotor(2=>-1).grep(
        -> ($a, $b) {
            $a+1 != $b
        }
    ).head;

    say $gap.head + 1;
}

multi sub MAIN('test') {
    use Test;
    is row(<F B F B B F F>), 44, 'row';
    is column(<R L R>), 5, 'column';

    is get-id('BFFFBBFRRR'), 567, 'example 1';
    is get-id('FFFBBBFRRR'), 119, 'example 2';
    is get-id('BBFFBBFRLL'), 820, 'example 3';
}