1
0
Fork 0

2020 day 9

This commit is contained in:
Lucidiot 2020-12-09 06:32:14 +01:00
parent dc3289d8af
commit c84c313362
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
2 changed files with 68 additions and 1 deletions

67
2020/9/day9.lua Normal file
View File

@ -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)))

View File

@ -19,7 +19,7 @@ is acceptable; anything goes as long as I solve it myself!
6 ██ ██ ██
7 ██ ██ ██
8 ██ ██ ██
9 ██
9 ██ ██
10 ██ ██
11 ██ ██
12 ██ ██