DEV Community

Brandon Weaver
Brandon Weaver

Posted on • Updated on

Advent of Ruby 3.0 - Day 05 - Binary Boarding

Ruby 3.0 was just released, so it's that merry time of year where we take time to experiment and see what all fun new features are out there.

This series of posts will take a look into several Ruby 2.7 and 3.0 features and how one might use them to solve Advent of Code problems. The solutions themselves are not meant to be the most efficient as much as to demonstrate novel uses of features.

I'll be breaking these up by individual days as each of these posts will get progressively longer and more involved, and I'm not keen on giving 10+ minute posts very often.

With that said, let's get into it!

<< Previous | Next >>

Day 05 - Part 01 - Binary Boarding

Today chose an interesting title. Binary boarding. We should probably pay attention to that, and also the fact that there are 128, or 2**7, rows of seats.

Wait wait, they also want to use the first 7 characters of the boarding pass to determine which row we're in? Can't be a coincidence.

It'd be even more of a coincidence if the last three, 2^3, somehow came up to 8. Too bad we can't combine them or...

Every seat also has a unique seat ID: multiply the row by 8, then add the column. In this example, the seat has ID 44 * 8 + 5 = 357.
Enter fullscreen mode Exit fullscreen mode

Well what do you know, it is a front for a binary string!

Let's start with the solution:

FRONT = 'F'.freeze
BACK  = 'B'.freeze
LEFT  = 'L'.freeze
RIGHT = 'R'.freeze

def find_position(pass) = pass.gsub(/./, {
  FRONT => 0,
  LEFT  => 0,
  BACK  => 1,
  RIGHT => 1
}).to_i(2)

def positions(passes) = passes.map { find_position(_1) }
def max_position(...) = positions(...).max

File.readlines(ARGV[0]).then { puts max_position(_1) }