From e37883ea3a8afa9322f14c12d0ed16dfa714e0a7 Mon Sep 17 00:00:00 2001 From: Zynh Ludwig Date: Tue, 3 Dec 2024 13:35:34 -0800 Subject: [PATCH] day 3 part 2 --- day3/part2.lua | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 day3/part2.lua diff --git a/day3/part2.lua b/day3/part2.lua new file mode 100644 index 0000000..52bfee3 --- /dev/null +++ b/day3/part2.lua @@ -0,0 +1,67 @@ +-- see if the file exists +local function file_exists(file) + local f = io.open(file, "rb") + if f then + f:close() + end + return f ~= nil +end + +-- get all lines from a file, returns an empty +-- list/table if the file does not exist +local function lines_from(file) + if not file_exists(file) then + return {} + end + local lines = {} + for line in io.lines(file) do + lines[#lines + 1] = line + end + return lines +end + +-- tests the functions above +local file = "input" +local lines = lines_from(file) + +local input = "" +for _, line in pairs(lines) do + input = input .. line +end + +local instructions = {} +-- print all line numbers and their contents +for pos, a, b in string.gmatch(input, "()mul%((%d+),(%d+)%)") do + ---@diagnostic disable-next-line: redefined-local + local a, b = tonumber(a), tonumber(b) + local product = a * b + + instructions[#instructions + 1] = { + pos = pos, + product = product, + } +end + +for pos in string.gmatch(input, "()do%(%)") do + instructions[#instructions + 1] = { pos = pos, enable = true } +end + +for pos in string.gmatch(input, "()don't%(%)") do + instructions[#instructions + 1] = { pos = pos, enable = false } +end + +table.sort(instructions, function(a, b) + return a.pos < b.pos +end) + +local total = 0 +local enabled = true +for _, instruction in ipairs(instructions) do + if instruction.enable ~= nil then + enabled = instruction.enable + elseif enabled then + total = total + instruction.product + end +end + +io.output():write(total)