-- 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 total = 0 local left_list = {} local right_list = {} -- https://www.lua.org/manual/5.4/manual.html#pdf-ipairs -- print all line numbers and their contents for _, v in ipairs(lines) do for n1, n2 in string.gmatch(v, "(%d+)%s+(%d+)") do -- [](https://stackoverflow.com/a/27434198) -- [Lua Length Operator](https://www.lua.org/manual/5.2/manual.html#3.4.6) left_list[#left_list + 1] = n1 right_list[#right_list + 1] = n2 end end -- https://www.lua.org/manual/5.2/manual.html#pdf-table.sort table.sort(left_list) table.sort(right_list) for i, v in ipairs(left_list) do total = total + math.abs(v - right_list[i]) end io.output():write(total)