-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
113 lines (89 loc) · 2.12 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
package main
import (
"container/ring"
"flag"
"image"
"log"
"strconv"
"strings"
"github.com/afarbos/aoc/pkg/point"
"github.com/afarbos/aoc/pkg/read"
"github.com/afarbos/aoc/pkg/utils"
)
const separator = ", "
var flagInput string
func init() {
utils.Init(&flagInput)
}
type person struct {
firstCross, position image.Point
direction *ring.Ring
visited map[image.Point]struct{}
}
func newPerson(sequences []string) *person {
var (
p = new(person)
northRing, eastRing, southRing, westRing = ring.New(1), ring.New(1), ring.New(1), ring.New(1)
)
northRing.Value = image.Point{1, 0}
eastRing.Value = image.Point{0, 1}
southRing.Value = image.Point{-1, 0}
westRing.Value = image.Point{0, -1}
southRing.Link(westRing)
eastRing.Link(southRing)
northRing.Link(eastRing)
p.direction = northRing
p.visited = make(map[image.Point]struct{}, len(sequences)*2)
p.walkBlocks(sequences)
return p
}
func (p *person) walk(newDirection byte, blockCount int) {
const (
right = "R"
left = "L"
)
switch newDirection {
case right[0]:
p.direction = p.direction.Next()
case left[0]:
p.direction = p.direction.Prev()
default:
log.Fatal(newDirection)
}
var (
direction = p.direction.Value.(image.Point)
nextPosition = p.position.Add(direction.Mul(blockCount))
)
zp := image.Point{}
if p.firstCross == zp {
for pt := p.position; pt != nextPosition; pt = pt.Add(direction) {
if _, ok := p.visited[pt]; ok {
p.firstCross = pt
}
p.visited[pt] = struct{}{}
}
}
p.position = nextPosition
}
func (p *person) walkBlocks(sequences []string) {
for i := range sequences {
blockCount, err := strconv.Atoi(strings.TrimSuffix(sequences[i][1:], read.Eol))
if err != nil {
log.Fatal(err)
}
p.walk(sequences[i][0], blockCount)
}
}
func main() {
const (
resTotalBlocks = 298
resFirstCross = 158
)
flag.Parse()
var (
sequences = read.Strings(flagInput, separator)
p = newPerson(sequences)
)
utils.AssertEqual(point.Distance(p.position), resTotalBlocks)
utils.AssertEqual(point.Distance(p.firstCross), resFirstCross)
}