-
Notifications
You must be signed in to change notification settings - Fork 0
/
day02.go
115 lines (100 loc) · 1.69 KB
/
day02.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
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
func main() {
log.SetFlags(0)
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
f, err := os.Open("input.txt")
if err != nil {
return err
}
defer f.Close()
prog, err := Parse(f)
if err != nil {
return err
}
fmt.Printf("Final position, part 1: %+v\n", Run1(prog))
fmt.Printf("Final position, part 2: %+v\n", Run2(prog))
return nil
}
func Run1(prog []Command) Pos {
var p Pos
for _, c := range prog {
switch c.Op {
case OpForward:
p.Horizontal += c.Count
case OpDown:
p.Depth += c.Count
case OpUp:
p.Depth -= c.Count
}
}
return p
}
func Run2(prog []Command) Pos {
var p Pos
for _, c := range prog {
switch c.Op {
case OpForward:
p.Horizontal += c.Count
p.Depth += c.Count * p.Aim
case OpDown:
p.Aim += c.Count
case OpUp:
p.Aim -= c.Count
}
}
return p
}
type Pos struct {
Horizontal int
Depth int
Aim int
}
type Command struct {
Op Op
Count int
}
type Op int
const (
OpForward Op = iota
OpUp
OpDown
)
func Parse(r io.Reader) ([]Command, error) {
var out []Command
s := bufio.NewScanner(r)
for s.Scan() {
l := s.Text()
i := strings.Index(l, " ")
if i < 0 {
return nil, fmt.Errorf("invalid input line %q", l)
}
c, err := strconv.Atoi(l[i+1:])
if err != nil {
return nil, fmt.Errorf("invalid input line %q: %v", l, err)
}
switch op := l[:i]; op {
case "forward":
out = append(out, Command{OpForward, c})
case "up":
out = append(out, Command{OpUp, c})
case "down":
out = append(out, Command{OpDown, c})
default:
return nil, fmt.Errorf("invalid operation %q", op)
}
}
return out, nil
}