Skip to main content

Command Palette

Search for a command to run...

Advent of Code 2020: Day 6 (Ruby solution)

Published
1 min read

This time input file contains many groups of entries. Entries are separated with a single newline character while groups are separated with two of them.

Your job in the first puzzle is to find how many unique letters occur in each group and count them together.

In the second task, you are supposed to check how many unique letters occur across all entries of each group and to count them together.

So basically, solutions of those 2 tasks differ in one operator. In the first task, it is a union (| operator) and in the second one, it is an intersection (& operator).

def count_letters file, operator
  letters_count = 0
  file.each_line("\n\n") do |group|
    letters_count += group.strip.lines.map { |line| line.strip.chars }.inject(operator).size
  end
  letters_count
end

file = File.read('inputs/day6.txt')
puts "First task answer: #{count_letters(file, :|)}"
puts "Second task answer: #{count_letters(file, :&)}"

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