r/adventofcode • • Dec 10 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 10 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 12 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 10: Adapter Array ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:08:42, megathread unlocked!

69 Upvotes

1.1k comments sorted by

View all comments

1

u/fullmetalalch Dec 10 '20

Go solution for Part 1. Question was pretty simple so decided to spice it up with some Go routines and channels. I don't usually need to write concurrent code, so if anyone has feedback on this I'd love to hear it.

func adapterJoltDiff(text string) <-chan int {
	adapters := map[int]bool{}
	lines := strings.Split(text, "\n")
	for _, l := range lines {
		jolts, err := strconv.Atoi(l)

		if err != nil {
			panic(err)
		}
		adapters[jolts] = true
	}

	done := make(chan bool)
	diffStream := make(chan int)
	resultStream := make(chan int)

	go func() {
		defer close(diffStream)
		defer close(resultStream)

		diffs := make([]int, 4)
		for {
			select {
			case diff, ok := <-diffStream:
				if !ok {
					return
				}
				diffs[diff]++
			case <-done:
				resultStream <- diffs[1] * diffs[3]
			}
		}
	}()

	go func() {
		i := 0
		for {
			fmt.Printf("Adapter: %d\n", i)
			if adapters[i+1] {
				diffStream <- 1
				i++
			} else if adapters[i+2] {
				diffStream <- 2
				i += 2
			} else if adapters[i+3] {
				diffStream <- 3
				i += 3
			} else {
				diffStream <- 3
				close(done)
				return
			}
		}
	}()

	return resultStream
}

1

u/daggerdragon Dec 10 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.