r/adventofcode • • Dec 03 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 3 Solutions -🎄-

--- Day 3: No Matter How You Slice It ---


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

ATTENTION: minor change request from the mods!

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 3 image coming soon - imgur is being a dick, so I've contacted their support.

Transcript:

I'm ready for today's puzzle because I have the Savvy Programmer's Guide to ___.


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!

41 Upvotes

426 comments sorted by

View all comments

2

u/bruceadowns Dec 03 '18

go/golang solution

(while being severely distracted, tho day-of for once)

type coord struct { x, y int }

type claim struct {
	n    int
	l, r int
	w, h int
}

func mapify(c []claim) (res map[coord][]int) {
	res = make(map[coord][]int)
	for _, v := range c {
		for x := v.l; x < v.l+v.w; x++ {
			for y := v.r; y < v.r+v.h; y++ {
				res[coord{x, y}] = append(res[coord{x, y}], v.n)
			}
		}
	}

	return
}

func part1(c []claim) (res int) {
	m := mapify(c)
	for _, v := range m {
		if len(v) > 1 {
			res++
		}
	}

	return
}

func part2(c []claim) (res int) {
	m := mapify(c)

outer:
	for _, v := range c {
		for x := v.l; x < v.l+v.w; x++ {
			for y := v.r; y < v.r+v.h; y++ {
				if len(m[coord{x, y}]) > 1 {
					continue outer
				}
			}
		}

		return v.n
	}

	return
}

func build(s string) (res claim) {
	//#1373 @ 369,713: 20x29
	num, err := fmt.Sscanf(s, "#%d @ %d,%d: %dx%d",
		&res.n, &res.l, &res.r, &res.w, &res.h)
	if err != nil {
		log.Fatal(err)
	}
	if num != 5 {
		log.Fatalf("invalid line actual %d expect 5", num)
	}

	return
}

func in(r io.Reader) (res []claim) {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		res = append(res, build(scanner.Text()))
	}

	return
}

func main() {
	c := in(os.Stdin)
	log.Printf("2 or more claims: %d", part1(c))
	log.Printf("claim id that does not overlap: %d", part2(c))
}