2020 day 9
This commit is contained in:
parent
dc3289d8af
commit
c84c313362
|
@ -0,0 +1,67 @@
|
|||
local function sum(items)
|
||||
local total = 0
|
||||
for _, value in ipairs(items) do
|
||||
total = total + value
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
local function min(items)
|
||||
local smol
|
||||
for _, value in ipairs(items) do
|
||||
if not smol or smol > value then
|
||||
smol = value
|
||||
end
|
||||
end
|
||||
return smol
|
||||
end
|
||||
|
||||
local function max(items)
|
||||
local lorge
|
||||
for _, value in ipairs(items) do
|
||||
if not lorge or lorge < value then
|
||||
lorge = value
|
||||
end
|
||||
end
|
||||
return lorge
|
||||
end
|
||||
|
||||
PREAMBLE_SIZE = 25
|
||||
local numbers = {}
|
||||
|
||||
for line in io.lines() do
|
||||
table.insert(numbers, tonumber(line))
|
||||
end
|
||||
|
||||
local function has_sum(preamble, number)
|
||||
for _, i in pairs(preamble) do
|
||||
for _, j in pairs(preamble) do
|
||||
if i ~= j and i + j == number then
|
||||
return true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function find_invalid_number()
|
||||
for i = PREAMBLE_SIZE + 1, #numbers do
|
||||
if not has_sum(table.pack(table.unpack(numbers, i-PREAMBLE_SIZE, i-1)), numbers[i]) then
|
||||
return numbers[i]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local function find_weakness(number)
|
||||
for size = 2, #numbers do
|
||||
for i = size, #numbers do
|
||||
local range = table.pack(table.unpack(numbers, i-size+1, i))
|
||||
if sum(range) == number then
|
||||
return min(range) + max(range)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local part1 = assert(find_invalid_number())
|
||||
print(part1)
|
||||
print(assert(find_weakness(part1)))
|
Loading…
Reference in New Issue