AdventOfCode-2018/day14.cr

49 lines
1.1 KiB
Crystal

require "./common.cr"
LINE_COUNT = 637061
recipes = Deque(Int32).new
recipes << 3
recipes << 7
elves = [0, 1]
def add_recipes(recipes, elves)
new_num = elves.map { |it| recipes[it] }.sum
new_num.to_s.chars.map(&.to_i32).each do |n|
recipes << n
end
elves.each_with_index do |elf, index|
elves[index] = (elf + recipes[elf] + 1) % recipes.size
end
end
def index?(recipes, sequence, start_at = 0)
return nil if recipes.size < sequence.size
(recipes.size-sequence.size+1-start_at).times do |offset|
correct = true
sequence.each_with_index do |s, i|
correct &= (recipes[start_at + offset + i] == s)
break unless correct
end
return start_at + offset if correct
end
return nil
end
# Part 1
while recipes.size < LINE_COUNT + 10
add_recipes(recipes, elves)
end
puts recipes.to_a[-10..-1].map(&.to_s).join
# Part 2
digits = LINE_COUNT.to_s.chars.map(&.to_i32)
index = nil
old_size = 0
until (index = index?(recipes, digits, Math.max(old_size - 10, 0)))
old_size = recipes.size
add_recipes(recipes, elves)
end
puts index