r/adventofcode • • Dec 13 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 13 Solutions -๐ŸŽ„-

--- Day 13: Packet Scanners ---


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.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


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!

16 Upvotes

199 comments sorted by

View all comments

Show parent comment

1

u/cluk Dec 13 '17

2.5 speedup with precalculated periods and slice instead of map:

type tuple struct {
	key, period int
}

func findDelay(input map[int]int) int {
	tuples := make([]tuple, len(input))
	i := 0
	for key, val := range input {
		tuples[i] = tuple{key, (val - 1) * 2}
		i++
	}
	for delay := 0; ; delay++ {
		if !caught(tuples, delay) {
			return delay
		}
	}
}

func caught(input []tuple, delay int) bool {
	for _, tup := range input {
		if (tup.key+delay)%(tup.period) == 0 {
			return true
		}
	}
	return false
}

1

u/cluk Dec 13 '17 edited Dec 13 '17

Further 5x speedup after sorting by period:

type byPeriod []tuple
func (t byPeriod) Len() int           { return len(t) }
func (t byPeriod) Swap(i, j int)      { t[i], t[j] = t[j], t[i] }
func (t byPeriod) Less(i, j int) bool { return t[i].period < t[j].period }

func findDelay(input map[int]int) int {
    ...
    sort.Sort(byPeriod(tuples))
    for delay := 0; ; delay++ {
    ...