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

1

u/drakmaniso Dec 03 '18

Go (golang)

Part 1:

A brute force solution, not very elegant (or scalable)...

package main

import (
	"bufio"
	"fmt"
	"image"
	"os"
)

func main() {
	input := read()

	overlaps := map[[2]int]struct{}{}
	for i := 0; i < len(input); i++ {
		for j := i + 1; j < len(input); j++ {
			o := input[i].Intersect(input[j])
			if !o.Empty() {
				for x := o.Min.X; x < o.Max.X; x++ {
					for y := o.Min.Y; y < o.Max.Y; y++ {
						overlaps[[2]int{x, y}] = struct{}{}
					}
				}
			}
		}
	}

	fmt.Printf("Answer: %d\n", len(overlaps))
}

func read() (input []image.Rectangle) {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		var id, x, y, w, h int
		n, err := fmt.Sscanf(s.Text(), "#%d @ %d,%d: %dx%d", &id, &x, &y, &w, &h)
		if n < 5 {
			fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
			continue
		}
		input = append(input, image.Rectangle{
			Min: image.Point{x, y},
			Max: image.Point{x + w, y + h},
		})
	}
	return input
}

Part 2:

package main

import (
	"bufio"
	"fmt"
	"image"
	"os"
)

func main() {
	input, claims := read()

loop:
	for i := 0; i < len(input); i++ {
		for j := 0; j < len(input); j++ {
			if i != j && input[i].Overlaps(input[j]) {
				continue loop
			}
		}
		fmt.Printf("Answer: %d\n", claims[i])
		return
	}
}

func read() (input []image.Rectangle, claims []int) {
	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		var id, x, y, w, h int
		n, err := fmt.Sscanf(s.Text(), "#%d @ %d,%d: %dx%d", &id, &x, &y, &w, &h)
		if n < 5 {
			fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
			continue
		}
		input = append(input, image.Rectangle{
			Min: image.Point{x, y},
			Max: image.Point{x + w, y + h},
		})
		claims = append(claims, id)
	}
	return input, claims
}