-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchallenge.go
More file actions
98 lines (78 loc) · 1.79 KB
/
challenge.go
File metadata and controls
98 lines (78 loc) · 1.79 KB
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
package challenge
import (
"fmt"
"strconv"
"strings"
"github.com/codemicro/adventOfCode/lib/aocgo"
)
const (
FORWARD = "forward"
DOWN = "down"
UP = "up"
)
type instruction struct {
Direction string
Magnitude int
}
func parse(instr string) ([]*instruction, error) {
var o []*instruction
for _, line := range strings.Split(strings.TrimSpace(instr), "\n") {
splitLine := strings.Split(line, " ")
if len(splitLine) != 2 {
return nil, fmt.Errorf("malformed instruction %#v", line)
}
magnitudeInt, err := strconv.Atoi(splitLine[1])
if err != nil {
return nil, err
}
o = append(o, &instruction{
Direction: splitLine[0],
Magnitude: magnitudeInt,
})
}
return o, nil
}
type Challenge struct {
aocgo.BaseChallenge
}
func (c Challenge) One(instr string) (interface{}, error) {
var depth, horizontal int
instructions, err := parse(instr)
if err != nil {
return nil, err
}
for _, instruction := range instructions {
switch instruction.Direction {
case FORWARD:
horizontal += instruction.Magnitude
case UP:
depth -= instruction.Magnitude
case DOWN:
depth += instruction.Magnitude
default:
return nil, fmt.Errorf("unknown direction %#v", instruction.Direction)
}
}
return depth * horizontal, nil
}
func (c Challenge) Two(instr string) (interface{}, error) {
var depth, horizontal, aim int
instructions, err := parse(instr)
if err != nil {
return nil, err
}
for _, instruction := range instructions {
switch instruction.Direction {
case FORWARD:
horizontal += instruction.Magnitude
depth += instruction.Magnitude * aim
case UP:
aim -= instruction.Magnitude
case DOWN:
aim += instruction.Magnitude
default:
return nil, fmt.Errorf("unknown direction %#v", instruction.Direction)
}
}
return depth * horizontal, nil
}