Skip to content

Instantly share code, notes, and snippets.

@kamiccolo
Created December 10, 2020 20:51

Revisions

  1. kamiccolo created this gist Dec 10, 2020.
    68 changes: 68 additions & 0 deletions AoC2020_10.lua
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    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")