re: AoC Day 3: No Matter How You Slice It VIEW POST

FULL DISCUSSION
 

Puh, that was a tough one for me today. I started out by counting the number of claims for each square on the "canvas" which gave me a correct aswer. However, I later misunderstand part 2 thinking I should find completely unclaimed squares that could be filled out by one claim...

After cheating a little and getting inspirations for solutions I have implemented a Golang solution for today. At least I am happy that I could implement it in Golang without any prior experience using Golang:

Part 1 and 2 together:

package main

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

type coord struct {
    l int
    t int
}

// readLines reads a whole file into memory
// and returns a slice of its lines.
func readLines(path string) ([]string, error) {
    file, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    var lines []string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }
    return lines, scanner.Err()
}

func mapClaims(data []string) (map[coord][]int, map[int][]int) {
    m := make(map[coord][]int)
    claims := make([][]int, len(data))
    overlaps := make(map[int][]int)
    r, _ := regexp.Compile("-?[0-9]+")
    for i, d := range data {
        claimsVal := r.FindAllString(d, -1)
        for _, valStr := range claimsVal {
            val, _ := strconv.Atoi(valStr)
            claims[i] = append(claims[i], val)
        }
        id := claims[i][0]
        startX := claims[i][1]
        startY := claims[i][2]
        width := claims[i][3]
        height := claims[i][4]
        overlaps[id] = []int{}
        for l := startX; l < startX+width; l++ {
            for t := startY; t < startY+height; t++ {
                claimSet := m[coord{l, t}]
                for _, number := range claimSet {
                    overlaps[number] = append(overlaps[number], id)
                    overlaps[id] = append(overlaps[id], number)
                }
                claimSet = append(claimSet, id)
                m[coord{l, t}] = claimSet
            }
        }

    }
    return m, overlaps
}

func main() {
    start := time.Now()
    data, err := readLines("input")
    if err != nil {
        panic(err)
    }

    m, overlaps := mapClaims(data)

    partA := 0
    for _, v := range m {
        if len(v) >= 2 {
            partA++
        }
    }
    fmt.Println(partA)

    partB := []int{}
    for k, v := range overlaps {
        if len(v) == 0 {
            partB = append(partB, k)
        }
    }
    fmt.Println(partB[0])
    elapsed := time.Since(start)
}
code of conduct - report abuse