Skip to main content

Command Palette

Search for a command to run...

Advent of Code 2020: Day 1 (Ruby solution)

Published
1 min read

Have you heard about Advent of Code? It is an annual event with daily tasks to solve for programmers.

This year, the first two tasks are to find numbers from 200 lines text file which in sum give 2020. In fact, you are asked for the result of their multiplication. Firstly you are supposed to find a pair of such numbers. Next, you are asked to find a trio. I have managed to solve both tasks using one recursive function. Here is the code:

def search_for_entries entries, sum, number_of_entries, depth = 1
  entries.each do |e|
    if number_of_entries > depth
      res = search_for_entries(entries - [e], sum - e, number_of_entries, depth + 1)
      return [e] + res if res
    else
      return [e] if e == sum
    end
  end
  nil
end

file = File.read('inputs/day1.txt')
entries = file.lines.map(&:to_i)

task_1 = search_for_entries(entries, 2020, 2)
puts "First task result: #{task_1&.inject(:*)}"

task_2 = search_for_entries(entries, 2020, 3)
puts "Second task result: #{task_2&.inject(:*)}"

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