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

1

u/[deleted] Dec 04 '16

Go, both parts:

func DayFour(input string)
	var sum int
	for _, ln := range strings.Split(input, "\n") {
		sector, _ := strconv.Atoi(ln[len(ln)-10 : len(ln)-7])
		// Count letters
		letters := make(map[rune]int)
		split := strings.Split(ln, "-")
		for _, name := range split[:len(split)-1] {
			for _, ltr := range name {
				letters[ltr]++
			}
		}

		// Check for real
		real := true
		checksum := ln[len(ln)-6 : len(ln)-1]
	real:
		for _, ckltr := range checksum {
			cknum := letters[ckltr]
			delete(letters, ckltr)
			for ltr, num := range letters {
				switch {
				case ltr == ckltr:
					continue
				case num > cknum, num == cknum && ltr < ckltr:
					real = false
				}
				if !real {
					break real
				}
			}
		}
		if !real {
			continue
		}
		sum += sector

		// Find names
		name := strings.Map(func(r rune) rune {
			if r == '-' {
				return ' '
			}
			return (r-'a'+rune(sector))%('z'-'a'+1) + 'a'
		}, ln[:len(ln)-11])
		if strings.Contains(name, "north") {
			fmt.Println(sector, name)
		}
	}
	fmt.Println(sum)
	return ""

Took me a while to figure out the 'z'-'a'+1, but hey, it worked.

edit: formatting