Skip to content

Instantly share code, notes, and snippets.

@kamiccolo
Created December 10, 2020 20:51
Show Gist options
  • Save kamiccolo/a97d0b30eb440ff3188570d145b9dc4e to your computer and use it in GitHub Desktop.
Save kamiccolo/a97d0b30eb440ff3188570d145b9dc4e to your computer and use it in GitHub Desktop.
local joules = {0}
for line in io.lines("input.txt") do
table.insert(joules, tonumber(line))
end
table.sort(joules)
table.insert(joules, joules[#joules] + 3)
local diff_counts = {}
local diffs = {}
for i = 1, #joules - 1 do
local d = joules[i + 1] - joules[i]
diff_counts[d] = (diff_counts[d] or 0) + 1
table.insert(diffs, d)
end
print(diff_counts[1]*diff_counts[3])
-- Stuff for pt.2:
-- Yeah yeah, recursion stuff, but it won't go deep
-- just adding up possible combinations of chargers
-- till it reaches the limit (actually, the end of group)
function rec(t, i, limit)
local v = 0
if i == limit then
return 1
elseif i > limit then
return 0
else
for j = 1, 3 do
if t[i + j] and t[i + j] - t[i] <= 3 then
v = v + rec(t, i + j, limit)
end
end
end
return v
end
local diff_pairs = {}
local start = nil
local finish = nil
-- group sequences of chargers with diff < 3
-- i.e. {1,2,3,6,9,11} ---> {{1,3}, {4, 4}, {5, 6}}
-- beware, those are indices!
for i, diff in ipairs(diffs) do
start = start or i
if diff == 3 then
finish = i
table.insert(diff_pairs, {start or i, finish})
start, finish = nil, nil
end
end
-- find the solution for smaller groups
local result = {}
for i, p in ipairs(diff_pairs) do
table.insert(result, rec(joules, p[1], p[2]))
end
-- grrrr, the number does not fit, feed multiplication to bc
os.execute("echo \"" .. table.concat(result, '*') .. "\" | bc")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment