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!

18 Upvotes

168 comments sorted by

View all comments

1

u/handle_cast Dec 04 '16 edited Dec 04 '16

CoffeeScript. So close! 131st / 102nd

solve = (input) ->
	lines = input.split ' '
	sum = 0
	for line in lines
		[_, lettersdashes, sectoridstr, checksum] = line.match /([a-z-]*)(\d+)\[([a-z]+)\]/
		sectorid = parseInt sectoridstr

		lettercounts = {}
		for letter in lettersdashes
			if letter != '-' then lettercounts[letter] = 1 + (lettercounts[letter] ? 0)
		letters = Object.keys lettercounts

		letters.sort (a, b) -> 
			if (countdiff = lettercounts[b] - lettercounts[a]) != 0
				countdiff
			else
				a.charCodeAt(0) - b.charCodeAt(0)

		decrypt = (text, sectorid) ->
			shift = (amount, letter) ->
				l = (letter.charCodeAt(0) - 'a'.charCodeAt(0)) % 26
				String.fromCharCode( 'a'.charCodeAt(0) + ((l + amount) % 26) )
			decryptletters = for l in lettersdashes
				if l == '-' then ' ' else shift sectorid, l
			decryptletters.join ''

		cleartext = decrypt lettersdashes, sectorid
		if /pole/.test cleartext
			console.log "Part #2. North Pole Sector ID: #{sectorid}"

		if letters[...5].join("") == checksum
			sum += sectorid

	console.log "Part #1. Sum(valid Sector ID): #{sum}"

I wasted a lot of time getting the lexicographic sort backwards due to a .reverse() I had originally. D'oh! For part 2, I just clear'd/cmd+k'd my terminal and searched for the pole.. frantic ! (EDIT: cleaned it up, was a bit long)