summary refs log tree commit diff stats
path: root/2020/day-09/day-09.raku
blob: e9b6683df4b67556bfed3754576b7a2015559208 (plain) (blame)
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
#!/usr/bin/env raku

sub MAIN (
    Int $part where * == 1|2 = 1 #= part to run (1 or 2)
) {
    my @numbers = "input".IO.lines>>.Int;
    my Int $solution;

    my Int $preamble_length = 25;
    my Int %invalid;

    MAIN: for @numbers.kv -> $idx, $num {
        next if $idx < $preamble_length;

        my @preamble = @numbers[$idx - $preamble_length..$idx - 1].sort;

        my Bool $valid;
        while pop @preamble -> $num_1 {
            my $diff = $num - $num_1;
            for @preamble -> $num_2 {
                if $num_2 == $diff {
                    $valid = True;
                    next MAIN;
                }
            }
        }

        unless $valid {
            %invalid<num> = $num;
            %invalid<idx> = $idx;
            $solution = %invalid<num> if $part == 1;
            last MAIN;
        }
    }

    if $part == 2 {
        my @set = @numbers[0..%invalid<idx> - $preamble_length - 1];

        PART2: for @set.elems - 1 ... 0 -> $idx_1 {
            for @set.elems - 1 ... 0 -> $idx_2 {
                my $sum = [+] @set[$idx_1..$idx_2];
                if $sum == %invalid<num> {
                    my @tmp = @set[$idx_1..$idx_2].sort;
                    $solution = @tmp[0] + @tmp[*-1];
                    last PART2;
                }
            }
        }
    }

    say "Part $part: ", $solution;
}