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 part1(ranges, ids)
- local fresh = 0
- local counted = {}
- for _, id in ipairs(ids) do
- for _, range in ipairs(ranges) do
- if id >= range[1] and id <= range[2] and counted[id] == nil then
- fresh = fresh + 1
- counted[id] = true
- end
- end
- end
- return fresh
- end
- local function merge_ranges(r1, r2)
- local do_overlap = r1[1] <= r2[2] and r1[2] >= r2[1]
- if do_overlap then
- return true, {
- math.min(r1[1], r2[1]),
- math.max(r1[2], r2[2])
- }
- else
- return false, nil
- end
- end
- local function part2(ranges)
- table.sort(ranges, function(l, r)
- if l[1] == r[1] then
- return l[2] < r[2]
- else
- return l[1] < r[1]
- end
- end)
- local total = 0
- local final_ranges = {}
- for _, r1 in ipairs(ranges) do
- if #final_ranges == 0 then
- table.insert(final_ranges, r1)
- else
- local did_merge, merged = merge_ranges(r1, final_ranges[#final_ranges])
- if did_merge then
- final_ranges[#final_ranges] = merged
- else
- table.insert(final_ranges, r1)
- end
- end
- end
- for _, range in ipairs(final_ranges) do
- total = total + (range[2] - range[1] + 1)
- end
- return total
- end
- ---@param input string
- local function parse_input(input)
- local ranges = {}
- local ids = {}
- local lines = helper.line_iter(input)
- for line in lines do
- if not line:match("-") then
- table.insert(ids, tonumber(line))
- else
- local num_iter = line:gmatch("%d+")
- table.insert(ranges, { tonumber(num_iter()), tonumber(num_iter()) })
- end
- end
- return ranges, ids
- end
- local input = helper.get_input(5, 2025)
- local sample = helper.get_sample("sample.txt")
- local ranges, ids = parse_input(input)
- print(part1(ranges, ids))
- print(string.format("%.f", part2(ranges)))
Advertisement
Add Comment
Please, Sign In to add comment