Skip to content

Instantly share code, notes, and snippets.

@oafridi
Created June 14, 2019 20:47
Show Gist options
  • Save oafridi/523d2c92a63d97366ee3b84396f2493c to your computer and use it in GitHub Desktop.
Save oafridi/523d2c92a63d97366ee3b84396f2493c to your computer and use it in GitHub Desktop.
AOC Day One
# O(n)
def resulting_freq(collection, initial_value = 0)
collection.inject(initial_value) do |final_value, line|
final_value += line.to_i
end
end
p resulting_freq([+1, +1, +1]) == 3
p resulting_freq([+1, +1, -2]) == 0
p resulting_freq([-1, -2, -3]) == -6
# collection = File.foreach('frequencies.txt')
# p resulting_freq(collection) == 518
def first_dup_freq(collection)
cur = 0
seen = { 0 => true }
loop do
collection.each do |line|
cur += line.to_i
return cur if seen[cur]
seen[cur] = true
end
end
cur
end
p first_dup_freq([+1, -1]) == 0
p first_dup_freq([+3, +3, +4, -2, -4]) == 10
p first_dup_freq([-6, +3, +8, +5, -6]) == 5
p first_dup_freq([+7, +7, -2, -7, -4]) == 14
# collection = File.foreach('frequencies.txt')
# p first_dup_freq(collection) == 72889
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment