# Advent of Code 2020: Day 9 (Ruby solution)

Piotr Jurewicz

Published on Dec 9, 2020

Subscribe to my newsletter and never miss my upcoming articles

Today's puzzles are about debugging a stream of some fake protocol.

The first task is to find the first value that violates protocol rules. It means finding the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it.

Having this value found, you have to find a contiguous set of at least two numbers in the stream which sum to this value.

Here is my Ruby code:

``````def find_invalid_number numbers, preamble
numbers.drop(preamble).each_with_index do |number, index|
valid = numbers[index...index + preamble].combination(2).any? do |combination|
combination.sum == number
end
return number unless valid
end
end

def find_contiguous_range_of_sum numbers, value
numbers.each_with_index do |number, index|
sum = number
i = 0
while sum < value
sum += numbers[index + (i += 1)]
end
return numbers[index...index + i] if sum == value
end
end