Advent of Code 2020 Day 5/25 in the Raku programming language

On Day 5, they gave a task to find a seat number in a place. We have a list of occupied seats in a special form. Long story short, the rows and the seats within the row are encoded binary, but instead of 0 and 1, letters are used: F and B for rows and L and R for the seat:

  • BFFFBBFRRR: row 70, column 7, seat ID 567.
  • FFFBBBFRRR: row 14, column 7, seat ID 119.
  • BBFFBBFRLL: row 102, column 4, seat ID 820.

The seat number is determined by the row and the column by a simple formula $row * 8 + $col. You should read the original description to get the task more clearly.

If the task is clear, here is my solution for the first part. In the first part, you need to tell the maximum seat number.

my @passes = 'input.txt'.IO.lines.map: *.trans( < F B L R > => < 0 1 0 1 > );

my $max = @passes.max;

my ($row, $col) = $max.substr(0, 7), $max.substr(7);
$row = "0b$row".Int;
$col = "0b$col".Int;

my $seat = $row * 8 + $col;
say $seat;

First of all, I transform the coding to a proper binary form, and then extract the row and column parts of it using a couple of substrs. The clever thing about the solution is that you can sort the values immediately after you convert them to a binary form. Actually, you even don’t have to replace L and R as these letters are already sorted unlike F and B (but you still will need to convert it later when determining $row and $col.

In the second part, you have to find the only missing seat. You should also take into account that the seat numbers do not start with 1. But the seat that we are looking for is neither the first nor the last, so it is definitely surrounded by the neighbours.

my @seats = 'input.txt'.IO.lines.map: *.trans( < F B L R > => < 0 1 0 1 > );

@seats.=map({"0b$_".Int});
@seats.=sort;

say 1 + @seats[(^@seats.end).first({@seats[$_] + 1 != @seats[$_ + 1]})];

I am using the first method to find the value, for which there is no next adjusting number that is bigger by 1.

* * *

→ Browse the code on GitHub
→ See all blog posts on Advent of Code 2020

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code