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

No Comments Yet