DEV Community

Arjun Rajkumar
Arjun Rajkumar

Posted on • Edited on

Write better code: Day 5 - Chronal Calibration

Recent posts:


--

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.

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay