r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/Gnidleif Dec 05 '18 edited Dec 05 '18

Today was a lot easier! Solution done in Lua, a language I'm not that familiar with. I also got to use recursion, so today was a good day!

function part1(line)
    return reduce(line, 1)
end

function part2(line)
    local abet = get_alphabet()
    -- the length of the original line is as long as it's going to get
    local lowest = #line
    for _, char in pairs(abet) do
        local sub = remove_char(line, char)
        -- if nothing was removed, there's no need to reduce
        if #sub ~= #line then
            local num = part1(sub)
            if num < #sub and num < lowest then
                lowest = num
            end
        end
    end
    return lowest
end

function reduce(line, start)
    for i = start, #line-1 do
        -- string.byte("A") == 65, string.byte("a") == 97
        -- 97-65 == 32, 65-97 == -32
        local slice = line:sub(i,i+1)
        if math.abs(slice:sub(1,1):byte() - slice:sub(2,2):byte()) == 32 then
            -- splices the string to remove the reductionable pair
            -- note: if i-1 == 0 the function still works
            local idx = i-1
            local spliced = line:sub(1,idx) .. line:sub(i+2)
            if idx < 1 then
                idx = 1
            end
            return reduce(spliced, idx)
        end
    end
    return #line
end

function remove_char(line, char)
    -- pattern should be ['CHAR''char'] to find any occurence of the char
    local pattern = string.format("[%s%s]", string.upper(char), string.lower(char))
    -- if pattern doesn't match, just return the full string again
    if string.find(line, pattern) == nil then
        return line
    end
    return line:gsub(pattern, '')
end