Skip to main content

Command Palette

Search for a command to run...

Advent of Code 2020: Day 5 (Ruby solution)

Published
1 min read

Here is my solution for puzzles of the 5th day of the Advent of Code 2020 event. The crucial thing is to notice that entries in the input file are just binary numbers where F and L stand for 0, B and R stand for 1.

After converting them to decimal numbers it is trivial to pick the maximum value. The first task is completed.

In the second puzzle, you are asked to find a missing entry among the file. There are few ways of doing that. I managed to find it by comparing following values with the loop index.

file = File.read('inputs/day5.txt')
entries = file.lines.map do |line|
  line.gsub(/[FBLR]/, 'F' => 0, 'B' => 1, 'L' => 0, 'R' => 1).to_i(2)
end
entries.sort!
puts "First task answer: #{entries.last}"

entries.each_with_index do |entry, index|
  if index + entries.first != entry
    puts "Second task answer: #{index + entries.first}"
    return
  end
end

More from this blog

R

Ruby Wizards blog

26 posts

I am a full-stack business developer from Poland with a strong interest in DDD. My leading technology is Ruby on Rails.

Contact me at: piotr.jurewicz(you-know-what)rubywizards.com

Advent of Code 2020: Day 5 (Ruby solution)