def chronal_calib_part1
  sum = 0

  File.open('advent_of_code/day1.txt', 'r') do |f|
    f.each_line do |line|
      sum += line.to_i
    end
  end  
  sum
end

Logic for part 2:

  • Iterate over eac line in file
  • Store the sum as an index in a hash.
  • If index already exists. Break the loop.
  • Return the hash key

Storing the summed frequencies as a hash as hash key lookup is faster than instead of doing an array.include? each time to check if sum already repeated.
Have to benchmark and test if this is true.

def chronal_calib_part2
  sum = 0
  frequency = {}
  found_frequency = false
  while found_frequency == false
    File.open('advent_of_code/day1.txt', 'r') do |f|
      f.each_line do |line|
        sum += line.to_i
        if frequency[sum] == true
          frequency[sum] = false
          found_frequency = true 
          break
        else
          frequency[sum] = true 
        end
      end
    end 
  end 
  puts frequency.key(false)
end

Time is O[n] as has to go thru each line in file multiple times.
Space is O[m] - m is sums.

Classic DEV Post from Nov 18 '18

Why is your preferred programming language your go-to?

A quick write up on why I love Python and you love your go-to language!

I’m a software developer primarily building web apps using Ruby on Rails.