day 3 part 2

This commit is contained in:
Felix Van der Jeugt 2021-12-03 09:38:00 +01:00
parent 6527698b9c
commit c14f89bf6f
No known key found for this signature in database
GPG Key ID: 58B209295023754D

View File

@ -1,33 +1,55 @@
local ZERO = string.byte("0", 1) local ZERO = string.byte("0", 1)
local ONE = string.byte("1", 1) local ONE = string.byte("1", 1)
local total = 0 local lines = {}
local counts = {}
for line in io.lines(arg[3]) do for line in io.lines(arg[3]) do
local ones = {}
for char = 1, #line do for char = 1, #line do
if line:byte(char) == ONE then table.insert(ones, line:byte(char) == ONE)
counts[char] = (counts[char] or 0) + 1
end
end end
total = total + 1 table.insert(lines, ones)
end end
local least, most, lmax, mmax = nil, nil, 0, 0 function reduce(left, keep)
for line in io.lines(arg[3]) do local char = 1
local lcur, mcur, lin, min = 0, 0, true, true while #left > 1 and char <= #lines[1] do
for char = 1, #line do local ones = 0
if line:byte(char) == ONE then for k, line in pairs(left) do
if counts[char] >= total / 2 then if lines[line][char] then
if min then mcur = mcur + 1 end ones = ones + 1
else
min = false
end
else
if counts[char] < total / 2 then
if min then mcur = mcur + 1 end
else
min = false
end end
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 end
print(line, mcur) return left[1]
end 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]))