Write better code: Day 5 - Chronal Calibration

・1 min read

I'm late to the Advent of code questions... But starting anyway.

I'm going to spend 1-2 hours/day solving different algorithms.

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

My answers are in the comments.

Did you find this post useful? Show some love!
DISCUSSION (1)
 
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 19 '18

The node_modules problem

Why node_modules is so heavy and can be done to solve it?

Arjun Rajkumar
I’m a software developer primarily building web apps using Ruby on Rails. Working on a personal project + freelancing. I'm looking for additional freelance work so hit me up if you need help!

Thanks for visiting dev.to

A Beginner's Guide to dev.to