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

Show parent comment

1

u/knallisworld Dec 05 '18

This year also my AoC Go one.

As the input contains only characters of the ASCII table, I have chosen modulo for the comparison. I guess that's faster than .toLower/.toUpper calls. Part2 solved in 5s.

func reducePolymerUnits(s string) string {
	return string(reducePolymerUnits2([]rune(s)))
}

func reducePolymerUnits2(runes []rune) []rune {
	for {
		changed := false
		for i := 0; i < len(runes); i++ {
			if i+1 >= len(runes) {
				break // EOL
			}
			r := runes[i]
			s := runes[i+1]

			if r != s && r%32 == s%32 { // mod 32 for matching a=A, b=B, ... (polarity non-matches)
				runes = append(runes[0:i], runes[i+2:]...) // remove reacting part
				changed = true
				break
			}
		}
		if !changed {
			break
		}
	}
	return runes
}

func findShortestReactedPolymer(s string) (int, int32) {
	defer dayless.TimeTrack(time.Now(), "findShortestReactedPolymer")
	var minLength = len(s)
	var minLengthChar = 'a' - 1
	for i := 'a'; i <= 'z'; i++ {
		m := i % 32
		s2 := strings.Map(func(r rune) rune {
			if r%32 == m { // mod 32 for matching a&A, b&B, ...
				return -1
			}
			return r
		}, s)
		length := len(reducePolymerUnits2([]rune(s2)))
		if minLength > length {
			minLength = length
			minLengthChar = i
		}
	}
	return minLength, minLengthChar
}

Completed ones available at GitHub