adventofcode-2021/day03/part2.lua

56 lines
1.1 KiB
Lua
Raw Normal View History

2021-12-03 08:54:29 +01:00
local ZERO = string.byte("0", 1)
local ONE = string.byte("1", 1)
2021-12-03 09:38:00 +01:00
local lines = {}
2021-12-03 08:54:29 +01:00
for line in io.lines(arg[3]) do
2021-12-03 09:38:00 +01:00
local ones = {}
2021-12-03 08:54:29 +01:00
for char = 1, #line do
2021-12-03 09:38:00 +01:00
table.insert(ones, line:byte(char) == ONE)
2021-12-03 08:54:29 +01:00
end
2021-12-03 09:38:00 +01:00
table.insert(lines, ones)
2021-12-03 08:54:29 +01:00
end
2021-12-03 09:38:00 +01:00
function reduce(left, keep)
local char = 1
while #left > 1 and char <= #lines[1] do
local ones = 0
for k, line in pairs(left) do
if lines[line][char] then
ones = ones + 1
2021-12-03 08:54:29 +01:00
end
2021-12-03 09:38:00 +01:00
end
local nleft = {}
for k, line in pairs(left) do
if keep(lines[line][char], ones, #left) then
table.insert(nleft, line)
2021-12-03 08:54:29 +01:00
end
end
2021-12-03 09:38:00 +01:00
left = nleft
char = char + 1
end
return left[1]
end
function bin2dec(t)
local v = 0
for i = 1, #t do
v = v * 2
if t[i] then v = v + 1 end
2021-12-03 08:54:29 +01:00
end
2021-12-03 09:38:00 +01:00
return v
end
local indices = {}
for line = 1, #lines do
table.insert(indices, line)
2021-12-03 08:54:29 +01:00
end
2021-12-03 09:38:00 +01:00
local oxygen = reduce(indices, function (bit, ones, total)
return (not bit or ones >= total/2) and (bit or ones < total/2)
end)
local co2 = reduce(indices, function (bit, ones, total)
return (not bit or ones < total/2) and (bit or ones >= total/2)
end)
print(bin2dec(lines[oxygen]) * bin2dec(lines[co2]))