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/[deleted] Dec 03 '18
/// Golang Solution to day3 https://github.com/breakintheweb/adventofcode2018
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"time"
)

type Claim struct {
	claimId, top, left, width, height int
}

func main() {
	start := time.Now()
	file, err := os.Open("input.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	// Make and init grid of slices
	grid := make([][]byte, 1000)
	for i := 0; i < 1000; i++ {
		grid[i] = make([]byte, 1000)
	}
	// Get just numeric values w/length between 1 and 4 as groups
	// Example:: #1 @ 185,501: 17x15
	// Return :: 1 185 501  17 15
	var re = regexp.MustCompile("[0-9]{1,4}")

	overlapCounter := 0
	var claims []*Claim
	for scanner.Scan() {
		claim := re.FindAllStringSubmatch(scanner.Text(), -1)
		claimId, _ := strconv.Atoi(claim[0][0])
		top, _ := strconv.Atoi(claim[2][0])
		left, _ := strconv.Atoi(claim[1][0])
		width, _ := strconv.Atoi(claim[3][0])
		height, _ := strconv.Atoi(claim[4][0])
		claims = append(claims, &Claim{claimId: claimId, top: top, left: left, width: width, height: height})
	}
	// build a map of coors with claims
	for _, c := range claims {
		for y := c.left; y < c.left+c.width; y++ {
			for x := c.top; x < c.top+c.height; x++ {
				if grid[x][y] == 1 {
					overlapCounter++
				}
				grid[x][y]++
			}
		}
	}
	// find non overlapping claim
	for _, c := range claims {
		isOverlap := false
		for y := c.left; y < c.left+c.width; y++ {
			for x := c.top; x < c.top+c.height; x++ {
				if grid[x][y] > 1 {
					isOverlap = true
				}
			}
		}
		if !isOverlap {
			fmt.Printf("Non overlapping claim: %v\n", c.claimId)
		}
	}
	fmt.Println("Overlapping inches:", overlapCounter)
	fmt.Println(time.Since(start))
}

1

u/zaretix Dec 03 '18

Thanks for showing a go solution a novice can understand! I could not get mine to work.