Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package.path = package.path .. ";../lib/?.lua"
- local helper = require("helper")
- helper.load_lib("../lib/libaoc.so")
- local function apply_op(arr, op)
- local ret
- if op == "*" then
- ret = 1
- for _, n in ipairs(arr) do
- ret = ret * n
- end
- else
- ret = 0
- for _, n in ipairs(arr) do
- ret = ret + n
- end
- end
- return ret
- end
- local function part1(input)
- local ret = 0
- local input_lines = helper.line_iter(input)
- local ops = {}
- for line in input_lines do
- local num_got = false
- local i = 1 -- the index of the list in ops
- local init = (#ops == 0)
- for val in line:gmatch("%d+") do
- num_got = true
- if init then -- first line of numbers
- local add = { tonumber(val) }
- table.insert(ops, add)
- else -- just appending
- table.insert(ops[i], tonumber(val))
- i = i + 1
- end
- end
- if not num_got then -- regex missed so these are the operators
- for op in line:gmatch("%S+") do
- ret = ret + apply_op(ops[i], op)
- i = i + 1
- end
- end
- end
- return ret
- end
- local function part2(input)
- local ret = 0
- local split_input = {}
- local max_len = 0
- for line in helper.line_iter(input) do
- local split_line = {}
- for c in line:gmatch(".") do
- table.insert(split_line, c)
- end
- if #split_line > max_len then
- max_len = #split_line
- end
- table.insert(split_input, split_line)
- end
- local nums = {}
- local op = ""
- for char_index = 1, max_len do
- local all_empty = true
- local curr_num = ""
- for _, arr in ipairs(split_input) do
- local c = arr[char_index]
- if c == " " or c == nil then
- goto continue
- end
- if c == "+" or c == "*" then
- op = c
- else -- c is a number
- curr_num = curr_num .. c
- all_empty = false
- end
- ::continue::
- end
- if all_empty then
- for i, _ in ipairs(nums) do
- nums[i] = tonumber(nums[i])
- end
- ret = ret + apply_op(nums, op)
- nums = {}
- op = ""
- else
- table.insert(nums, curr_num)
- end
- end
- return ret + apply_op(nums, op)
- end
- local sample = helper.get_sample("sample.txt")
- local input = helper.get_input(6, 2025)
- print(part1(sample))
- print(part2(input))
Advertisement
Add Comment
Please, Sign In to add comment