Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 235c028

Browse files
committed
1041 wrong answer
1 parent 81f751d commit 235c028

File tree

1 file changed

+55
-11
lines changed

1 file changed

+55
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,60 @@
11
package problem1041
22

33
func isRobotBounded(instructions string) bool {
4-
g, l, r := 0, 0, 0
5-
for _, b := range instructions {
6-
switch b {
7-
case 'G':
8-
g++
9-
case 'L':
10-
l++
11-
case 'R':
12-
r++
13-
}
4+
r := newRobot()
5+
for _, i := range instructions {
6+
r.receive(i)
147
}
15-
return g == 0 || (l-r)%4 != 0
8+
return (r.x == 0 && r.y == 0) ||
9+
(r.d != north)
10+
}
11+
12+
type direction int
13+
14+
const (
15+
north direction = iota
16+
east
17+
south
18+
west
19+
)
20+
21+
type robot struct {
22+
d direction
23+
x, y int
24+
}
25+
26+
func newRobot() *robot {
27+
return &robot{
28+
d: north,
29+
}
30+
}
31+
32+
func (r *robot) receive(instruction rune) {
33+
if instruction == 'G' {
34+
r.move()
35+
} else {
36+
r.turn(instruction)
37+
}
38+
}
39+
40+
func (r *robot) move() {
41+
switch r.d {
42+
case north:
43+
r.y++
44+
case east:
45+
r.x++
46+
case south:
47+
r.y--
48+
case west:
49+
r.x--
50+
}
51+
}
52+
53+
func (r *robot) turn(instruction rune) {
54+
if instruction == 'R' {
55+
r.d++
56+
} else {
57+
r.d--
58+
}
59+
r.d = r.d % 4
1660
}

0 commit comments

Comments
 (0)