-- Using Autorun now print("Starting Day 5...") local input_file = "Day5/full" local DEBUG = false local Freshness = { Range = {}, } function debug(msg) if DEBUG then print(msg) end end function Freshness.add(R) local S, E = string.match(R, "(%d+)-(%d+)") local Set = { tonumber(S), tonumber(E) } table.insert(Freshness.Range, Set) end function Freshness.show() for k, v in pairs(Freshness.Range) do print(string.format("%d-%d", v[1], v[2])) end end function Freshness.check(value) cv = tonumber(value) for k, v in pairs(Freshness.Range) do if cv >= v[1] and cv <= v[2] then return true end end return false end function Freshness.CalculateIDs() -- Copy and Sort table.sort(Freshness.Range, function(a, b) return a[1] < b[1] end) local IDTable = {} local count = 0 for kadd, vadd in pairs(Freshness.Range) do local merged = false debug("Checking " .. vadd[1] .. "-" .. vadd[2]) for kcheck, vcheck in pairs(IDTable) do -- Check Lower debug(" Compare " .. vcheck[1] .. "-" .. vcheck[2]) if vadd[1] >= vcheck[1] and vadd[1] <= vcheck[2] then if vadd[2] > vcheck[2] then debug(" Lower number inside range and higher number higher") IDTable[kcheck][2] = vadd[2] end merged = true end -- Check higher if vadd[2] >= vcheck[1] and vadd[2] <= vcheck[2] then if vadd[1] < vcheck[1] then debug(" Higher number inside range and lower number lower") IDTable[kcheck][1] = vadd[1] end merged = true end end if not merged then table.insert(IDTable, vadd) end end local countIDs = 0 for k, v in pairs(IDTable) do countIDs = countIDs + (v[2] - v[1]) + 1 print(string.format("Range %d-%d = %d Total %d", v[1], v[2], (v[2] - v[1] + 1), countIDs)) end return countIDs end local InputMode = true local FreshCounter = 0 for line in io.lines(input_file) do if line == "" then InputMode = false elseif InputMode then Freshness.add(line) else if Freshness.check(line) then FreshCounter = FreshCounter + 1 end end end print("Found Fresh Ingredients " .. FreshCounter) print(string.format("Found IDs %18.0f", Freshness.CalculateIDs()))