-
Notifications
You must be signed in to change notification settings - Fork 0
/
day14.go
116 lines (104 loc) · 1.92 KB
/
day14.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"strconv"
"strings"
)
type Point struct {
x, y int
}
func calcSandAtRest(lines []string, floor bool) int {
cave, maxDepth := createCave(lines, floor)
landed := putSand(&cave, maxDepth)
return landed
}
func putSand(cave *[200][700]int, maxDepth int) int {
landed := 0
nextSand:
for {
sand := Point{500, 0}
for {
if sand.y >= maxDepth {
return landed
}
switch cave[sand.y+1][sand.x] {
case 0:
sand.y++
default:
if cave[sand.y+1][sand.x-1] != 0 {
if cave[sand.y+1][sand.x+1] != 0 {
cave[sand.y][sand.x] = 2
landed++
if sand.y == 0 && sand.x == 500 {
return landed
}
continue nextSand
} else {
sand.x++
continue
}
} else {
sand.x--
continue
}
}
}
}
}
func createCave(lines []string, floor bool) ([200][700]int, int) {
cave := [200][700]int{}
maxDepth := 0
for _, v := range lines {
parts := strings.Split(v, " -> ")
points := extractPoints(parts)
for i := 0; i < len(points); i++ {
if points[i].y > maxDepth {
maxDepth = points[i].y
}
if i == len(points)-1 {
break
}
fillStones(&cave, points[i], points[i+1])
}
}
if floor {
for x := 0; x < len(cave[maxDepth+2]); x++ {
cave[maxDepth+2][x] = 1
}
maxDepth += 2
}
return cave, maxDepth
}
func fillStones(cave *[200][700]int, from, to Point) {
xDiff := from.x - to.x
yDiff := from.y - to.y
if xDiff != 0 {
for x := from.x; x != to.x; {
cave[from.y][x] = 1
if xDiff > 0 {
x--
} else {
x++
}
}
} else if yDiff != 0 {
for y := from.y; y != to.y; {
cave[y][from.x] = 1
if yDiff > 0 {
y--
} else {
y++
}
}
}
cave[to.y][to.x] = 1
}
func extractPoints(parts []string) []Point {
var points []Point
for _, v := range parts {
xy := strings.Split(v, ",")
x, _ := strconv.Atoi(xy[0])
y, _ := strconv.Atoi(xy[1])
points = append(points, Point{x, y})
}
return points
}