105 lines
2.0 KiB
Lua
105 lines
2.0 KiB
Lua
io.input("input")
|
|
|
|
symbols = "[%*%$%+%#%/%&%=%@%-%%]"
|
|
ast = "%*"
|
|
|
|
function coord(r,c) return r..","..c end
|
|
function add_pot_gear(coor, num)
|
|
if not pot_gears[coor] then
|
|
pot_gears[coor] = {}
|
|
end
|
|
table.insert(pot_gears[coor],num)
|
|
end
|
|
|
|
lines = {}
|
|
for line in io.lines() do
|
|
table.insert(lines, line)
|
|
end
|
|
|
|
pot_gears = {}
|
|
|
|
sum1 = 0
|
|
sum2 = 0
|
|
for i,line in ipairs(lines) do
|
|
-- print(i, line)
|
|
init = 1
|
|
repeat -- find all numbers in each line
|
|
o,f = line:find("%d+", init)
|
|
is_part = false
|
|
if o then
|
|
num = tonumber(line:sub(o,f))
|
|
-- right
|
|
if f<#line then
|
|
right = line:sub(f+1,f+1)
|
|
is_part = is_part or right:find(symbols)
|
|
|
|
if right:find(ast) then
|
|
coor = coord(i, f+1)
|
|
add_pot_gear(coor,num)
|
|
end
|
|
end
|
|
-- left
|
|
if o>1 then
|
|
left = line:sub(o-1,o-1)
|
|
is_part = is_part or left:find(symbols)
|
|
|
|
if left:find(ast) then
|
|
coor = coord(i, o-1)
|
|
add_pot_gear(coor,num)
|
|
end
|
|
end
|
|
-- top
|
|
if i>1 then
|
|
prev_line = lines[i-1]
|
|
colo = (o>1) and (o-1) or 1
|
|
colf = (f<#line) and (f+1) or f
|
|
top = prev_line:sub(colo,colf)
|
|
is_part = is_part or top:find(symbols)
|
|
|
|
ainit = 1
|
|
repeat
|
|
ao, af = top:find(ast, ainit)
|
|
if ao then
|
|
coor = coord(i-1, colo-1+ao)
|
|
add_pot_gear(coor,num)
|
|
ainit = af+1
|
|
end
|
|
until not ao
|
|
|
|
end
|
|
-- bottom
|
|
if i<#lines then
|
|
next_line = lines[i+1]
|
|
colo = (o>1) and (o-1) or 1
|
|
colf = (f<#line) and (f+1) or f
|
|
bottom = next_line:sub(colo,colf)
|
|
is_part = is_part or bottom:find(symbols)
|
|
|
|
ainit = 1
|
|
repeat
|
|
ao, af = bottom:find(ast, ainit)
|
|
if ao then
|
|
coor = coord(i+1,colo-1+ao)
|
|
add_pot_gear(coor,num)
|
|
ainit = af+1
|
|
end
|
|
until not ao
|
|
end
|
|
if is_part then sum1 = sum1 + num end
|
|
-- print(num,o,f,is_part)
|
|
init = f+1
|
|
end
|
|
until not o
|
|
end
|
|
|
|
print("part 1", sum1)
|
|
|
|
for coor,nums in pairs(pot_gears) do
|
|
if #nums==2 then
|
|
ratio = nums[1] * nums[2]
|
|
sum2 = sum2 + ratio
|
|
end
|
|
end
|
|
|
|
print("part 2", sum2)
|