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(), 44, 'row'; is column(), 5, 'column'; is get-id('BFFFBBFRRR'), 567, 'example 1'; is get-id('FFFBBBFRRR'), 119, 'example 2'; is get-id('BBFFBBFRLL'), 820, 'example 3'; }