You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.5 KiB
68 lines
1.5 KiB
width = tonumber(arg[2])
|
|
height = tonumber(arg[3])
|
|
|
|
layers = {}
|
|
layer = {}
|
|
row = {}
|
|
for x in io.open(arg[1]):read("a"):gmatch("%d") do
|
|
table.insert(row, tonumber(x))
|
|
if #row >= width then
|
|
table.insert(layer, row)
|
|
row = {}
|
|
if #layer >= height then
|
|
table.insert(layers, layer)
|
|
layer = {}
|
|
end
|
|
end
|
|
end
|
|
layer = nil
|
|
row = nil
|
|
|
|
fewest = nil
|
|
for layer_index, layer in ipairs(layers) do
|
|
count = 0
|
|
for _, row in ipairs(layer) do
|
|
for _, pixel in ipairs(row) do
|
|
if pixel == 0 then
|
|
count = count + 1
|
|
end
|
|
end
|
|
end
|
|
|
|
if not fewest or count < fewest[1] then
|
|
fewest = {count, layer_index}
|
|
end
|
|
end
|
|
|
|
result_p1 = {0, 0}
|
|
for _, row in ipairs(layers[fewest[2]]) do
|
|
for _, pixel in ipairs(row) do
|
|
if not result_p1[pixel] then
|
|
result_p1[pixel] = 0
|
|
end
|
|
result_p1[pixel] = result_p1[pixel] + 1
|
|
end
|
|
end
|
|
|
|
print("Part 1:", result_p1[1] * result_p1[2])
|
|
|
|
if not arg[4] then
|
|
os.exit(true)
|
|
end
|
|
|
|
output = io.open(arg[4], "w")
|
|
output:write(string.format("P1\n%d %d\n", #layers[1][1], #layers[1]))
|
|
for row_index, row in ipairs(layers[1]) do
|
|
for pixel_index, pixel in ipairs(row) do
|
|
if pixel == 2 then
|
|
for x = 2, #layers do
|
|
pixel = layers[x][row_index][pixel_index]
|
|
if pixel ~= 2 then
|
|
break
|
|
end
|
|
end
|
|
end
|
|
output:write(pixel)
|
|
output:write(" ")
|
|
end
|
|
end
|
|
|