@@ 99,8 99,86 @@ func partA(fn string) {
log.Printf("%s: %v", fn, a)
}
+type XY struct {
+ x, y int
+}
+
+func adjacentGears(ls []string, x, y int) []XY {
+ X := len(ls[0])
+ Y := len(ls)
+
+ var xy []XY
+
+ if y > 0 {
+ if x > 0 && ls[y-1][x-1] == '*' {
+ xy = append(xy, XY { x-1, y-1 })
+ }
+
+ if ls[y-1][x] == '*' {
+ xy = append(xy, XY { x, y-1 })
+ }
+
+ if x+1 < X && ls[y-1][x+1] == '*' {
+ xy = append(xy, XY { x+1, y-1 })
+ }
+ }
+
+ if x > 0 && ls[y][x-1] == '*' {
+ xy = append(xy, XY { x-1, y })
+ }
+
+ if x+1 < X && ls[y][x+1] == '*' {
+ xy = append(xy, XY { x+1, y })
+ }
+
+ if y+1 < Y {
+ if x > 0 && ls[y+1][x-1] == '*' {
+ xy = append(xy, XY { x-1, y+1 })
+ }
+
+ if ls[y+1][x] == '*' {
+ xy = append(xy, XY { x, y+1 })
+ }
+
+ if x+1 < X && ls[y+1][x+1] == '*' {
+ xy = append(xy, XY { x+1, y+1 })
+ }
+ }
+
+ return xy
+}
+
func partB(fn string) {
- var b int
+ ls := getLines(fn)
+ Y := len(ls)
+ X := len(ls[0])
+
+ Gs := make(map[XY][]int)
+ for y := 0; y < Y; y++ {
+ for x := 0; x < X; x++ {
+ if isDigit(ls[y][x]) {
+ gs := make(map[XY]bool)
+ //x0 := x
+ sum := 0
+ for ; x < X && isDigit(ls[y][x]); x++ {
+ for _, g := range adjacentGears(ls, x, y) {
+ gs[g] = true
+ }
+ sum = 10*sum + int(ls[y][x]-'0')
+ }
+ //log.Printf("(%d,%d) %v %v", x0, y, sum, gs)
+ for g, _ := range gs {
+ Gs[g] = append(Gs[g], sum)
+ }
+ }
+ }
+ }
+ b := 0
+ for _, ns := range Gs {
+ if len(ns) == 2 {
+ b += ns[0]*ns[1]
+ }
+ }
log.Printf("%s: %v", fn, b)
}
@@ 108,6 186,6 @@ func main() {
partA("03.example") // 4361
partA("03.input") // 551094
- //partB("03.example")
- //partB("03.input")
+ partB("03.example") // 467835
+ partB("03.input") // 80179647
}