-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
134 lines (116 loc) · 2.5 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"io"
aoc "github.com/teivah/advent-of-code"
)
type squareType int
const (
empty squareType = iota
rock
)
func fs1(input io.Reader, iterations int) int {
var start aoc.Position
board := aoc.ParseBoard(aoc.ReaderToStrings(input), func(r rune, pos aoc.Position) squareType {
switch r {
case '.':
return empty
case '#':
return rock
case 'S':
start = pos
return empty
default:
panic(r)
}
})
q := []aoc.Position{start}
for it := 0; it < iterations; it++ {
length := len(q)
positions := make(map[aoc.Position]struct{})
for i := 0; i < length; i++ {
p := q[0]
q = q[1:]
moves := []aoc.Direction{aoc.Up, aoc.Down, aoc.Left, aoc.Right}
for _, move := range moves {
t := p.Move(move, 1)
if board.Contains(t) && board.Get(t) != rock {
if _, exists := positions[t]; exists {
continue
}
positions[t] = struct{}{}
q = append(q, t)
}
}
}
}
return len(q)
}
func fs2(input io.Reader, iterations int) int {
var start aoc.Position
board := aoc.ParseBoard(aoc.ReaderToStrings(input), func(r rune, pos aoc.Position) squareType {
switch r {
case '.':
return empty
case '#':
return rock
case 'S':
start = pos
return empty
default:
panic(r)
}
})
type position struct {
boardRow int
boardCol int
position aoc.Position
}
q := []position{
{position: start},
}
var stats []int
for it := 0; it < 64+board.MaxCols*2+1; it++ {
length := len(q)
positions := make(map[position]struct{})
for i := 0; i < length; i++ {
p := q[0]
q = q[1:]
moves := []aoc.Direction{aoc.Up, aoc.Down, aoc.Left, aoc.Right}
for _, move := range moves {
p := p
t := p.position.Move(move, 1)
if t.Row < 0 {
p.boardRow--
t.Row = board.MaxRows - 1
} else if t.Row == board.MaxRows {
p.boardRow++
t.Row = 0
} else if t.Col < 0 {
p.boardCol--
t.Col = board.MaxCols - 1
} else if t.Col == board.MaxCols {
p.boardCol++
t.Col = 0
}
p.position = t
if board.Get(t) == rock {
continue
}
if _, exists := positions[p]; exists {
continue
}
positions[p] = struct{}{}
q = append(q, p)
}
}
stats = append(stats, len(q))
}
remaining := iterations % board.MaxCols
return polynomial(iterations/board.MaxCols, stats[remaining-1], stats[remaining-1+board.MaxCols], stats[remaining-1+board.MaxCols*2])
}
func polynomial(a, x, y, z int) int {
b0 := x
b1 := y - x
b2 := z - y
return b0 + (b1 * a) + (a*(a-1)/2)*(b2-b1)
}