Advent of Code 2020: Day 1 (Ruby solution)

Subscribe to my newsletter and never miss my upcoming articles

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
      return [e] if e == sum

file ='inputs/day1.txt')
entries =

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(:*)}"

No Comments Yet