File tree Expand file tree Collapse file tree 1 file changed +88
-0
lines changed Expand file tree Collapse file tree 1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "flag"
5
+ "fmt"
6
+ "io/ioutil"
7
+ "strings"
8
+ )
9
+
10
+ var inputFile = flag .String ("inputFile" , "inputs/day03.input" , "Relative file path to use as input." )
11
+
12
+ type Coord struct {
13
+ X , Y int
14
+ }
15
+
16
+ func main () {
17
+ flag .Parse ()
18
+ bytes , err := ioutil .ReadFile (* inputFile )
19
+ if err != nil {
20
+ return
21
+ }
22
+ contents := string (bytes )
23
+ split := strings .Split (contents , "\n " )
24
+
25
+ sum := 0
26
+ grid := make (map [Coord ]rune )
27
+ gears := make (map [Coord ][]int )
28
+ var maxX , maxY int
29
+ for y , row := range split [:len (split )- 1 ] {
30
+ for x , c := range row {
31
+ grid [Coord {x , y }] = c
32
+ if x > maxX {
33
+ maxX = x
34
+ }
35
+ }
36
+ if y > maxY {
37
+ maxY = y
38
+ }
39
+ }
40
+ for y := 0 ; y <= maxY ; y ++ {
41
+ for x := 0 ; x <= maxX ; {
42
+ c := grid [Coord {x , y }]
43
+ if c < '0' || c > '9' {
44
+ x ++
45
+ continue
46
+ }
47
+ // We've found a number. Keep reading to the right.
48
+ num := int (c - '0' )
49
+ length := 1
50
+ for i := 1 ; ; i ++ {
51
+ n := grid [Coord {x + i , y }]
52
+ if n < '0' || n > '9' {
53
+ break
54
+ }
55
+ num = 10 * num + int (n - '0' )
56
+ length ++
57
+ }
58
+ outer:
59
+ for j := y - 1 ; j <= y + 1 ; j ++ {
60
+ for i := x - 1 ; i <= x + length ; i ++ {
61
+ nCoord := Coord {i , j }
62
+ neigh := grid [nCoord ]
63
+ if neigh == 0 || neigh == '.' {
64
+ continue
65
+ }
66
+ if neigh >= '0' && neigh <= '9' {
67
+ continue
68
+ }
69
+ sum += num
70
+ if neigh == '*' {
71
+ gears [nCoord ] = append (gears [nCoord ], num )
72
+ }
73
+ break outer
74
+ }
75
+ }
76
+ x = x + length
77
+ }
78
+ }
79
+ fmt .Println (sum )
80
+
81
+ ratio := 0
82
+ for _ , v := range gears {
83
+ if len (v ) == 2 {
84
+ ratio += v [0 ] * v [1 ]
85
+ }
86
+ }
87
+ fmt .Println (ratio )
88
+ }
You can’t perform that action at this time.
0 commit comments