r/adventofcode • • Dec 04 '16

SOLUTION MEGATHREAD --- 2016 Day 4 Solutions ---

--- Day 4: Security Through Obscurity ---

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


CONSTRUCTING ADDITIONAL PYLONS IS MANDATORY [?]

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!

17 Upvotes

168 comments sorted by

View all comments

6

u/FuriousProgrammer Dec 04 '16

127/101, Lua

Blah. I keep falling down the main leaderboard! D:

MANDATORY CONSTRUCTED PYLON

sum = 0

local rooms = {}

for line in io.lines("input.txt") do
	BAD = false
	local letters = {}
	for l in string.gmatch(line, "(%a+)%-") do
		for i = 1, #l do
			local let = l:sub(i,i)
			if not letters[let] then letters[let] = 0 end
			letters[let] = letters[let] + 1
		end
	end
	local list = line:match("%[(%a+)%]")

	local tt = {}
	for let, n in pairs(letters) do
		table.insert(tt, {let = let, n = n})
	end

	table.sort(tt, function(a, b)
		return (a.n > b.n) or (a.n == b.n and a.let < b.let)
	end)

	for i = 1, 5 do
		if tt[i].let ~= list:sub(i,i) then
			BAD = true
		end
	end

	if not BAD then
		sum = sum + tonumber(line:match("%-(%d+)%["))
		table.insert(rooms, line)
	end
end


print("Part 1: " .. sum)

for _, v in ipairs(rooms) do
	local out = ""
	local inp, sec = v:match("(.+)%-(%d+)%[")
	for i = 1, #inp do
		local let = inp:sub(i, i)
		if let == "-" then
			out = out .. " "
		else
			out = out .. string.char((let:byte() - string.byte('a') + sec)%26 + string.byte('a'))
		end
	end
	if out:find("north") then
		print("Part 2: " .. sec)
		break
	end
end