DEV Community

Arjun Rajkumar
Arjun Rajkumar

Posted on • Updated on

Write better code: Day 5 - Chronal Calibration

This post originally appeared on Arjun Rajkumar's blog. Arjun runs web development company based in Bangalore, India.

--

Day 5: Question 1 & Question 2 are from Advent of code:
https://adventofcode.com/2018/day/1/answer

My answers are in the comments.

Top comments (1)

Collapse
 
arjunrajkumar profile image
Arjun Rajkumar • Edited
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.