adventofcode-2021/day03/part2.lua

58 lines
1.1 KiB
Lua
Executable File

#!/usr/bin/env luajit
local ZERO = string.byte("0", 1)
local ONE = string.byte("1", 1)
local lines = {}
for line in io.lines(arg[3]) do
local ones = {}
for char = 1, #line do
table.insert(ones, line:byte(char) == ONE)
end
table.insert(lines, ones)
end
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
end
end
local nleft = {}
for k, line in pairs(left) do
if keep(lines[line][char], ones, #left) then
table.insert(nleft, line)
end
end
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
end
return v
end
local indices = {}
for line = 1, #lines do
table.insert(indices, line)
end
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]))