diff options
Diffstat (limited to '2020/day5.raku')
-rw-r--r-- | 2020/day5.raku | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/2020/day5.raku b/2020/day5.raku new file mode 100644 index 0000000..98151ef --- /dev/null +++ b/2020/day5.raku @@ -0,0 +1,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'; +} |