r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


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

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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!

51 Upvotes

407 comments sorted by

View all comments

Show parent comment

1

u/frenetix Dec 03 '18
countLetters := func(s string) map[rune]int {
	out := make(map[rune]int)
	for _, b := range s {
		out[b] = out[b] + 1
	}
	return out
}
part1 := func(in io.Reader) string {
	twos := 0
	threes := 0
	for _, line := range lines(in) {
		alreadyCounted2 := false
		alreadyCounted3 := false
		for _, val := range countLetters(line) {
			if val == 2 && !alreadyCounted2 {
				alreadyCounted2 = true
				twos++
			}
			if val == 3 && !alreadyCounted3 {
				alreadyCounted3 = true
				threes++
			}
		}
	}
	return strconv.FormatInt(int64(twos*threes), 10)
}
part2 := func(in io.Reader) string {
	ls := lines(in)
	for i, line1 := range ls {
		for _, line2 := range ls[i+1:] {
			diffCount := 0
			diffIndex := 0
			for j := 0; j < len(line1); j++ {
				if line1[j] != line2[j] {
					diffCount++
					diffIndex = j
				}
			}
			if diffCount == 1 {
				return line1[:diffIndex] + line1[diffIndex+1:]
			}
		}
	}
	return ""
}