Skip to content

Commit 9e5d79e

Browse files
authored
Merge pull request #599 from bu7ch/branch-bu7ch
-PR-#597
2 parents a0e5456 + e844a0b commit 9e5d79e

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed

robot_simulator/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Robot Simulator
2+
3+
Write a robot simulator.
4+
5+
A robot factory's test facility needs a program to verify robot movements.
6+
7+
The robots have three possible movements:
8+
9+
- turn right
10+
- turn left
11+
- advance
12+
13+
Robots are placed on a hypothetical infinite grid, facing a particular
14+
direction (north, east, south, or west) at a set of {x,y} coordinates,
15+
e.g., {3,8}, with coordinates increasing to the north and east.
16+
17+
The robot then receives a number of instructions, at which point the
18+
testing facility verifies the robot's new position, and in which
19+
direction it is pointing.
20+
21+
- The letter-string "RAALAL" means:
22+
- Turn right
23+
- Advance twice
24+
- Turn left
25+
- Advance once
26+
- Turn left yet again
27+
- Say a robot starts at {7, 3} facing north. Then running this stream
28+
of instructions should leave it at {9, 4} facing west.
29+
30+
* * * *
31+

robot_simulator/robot_simulator.rb

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
class Robot
2+
attr_accessor :x, :y, :bearing
3+
4+
def at(x, y)
5+
self.x = x
6+
self.y = y
7+
end
8+
9+
def coordinates
10+
[x, y]
11+
end
12+
13+
14+
def orient(direction)
15+
fail ArgumentError unless cardinal_directions.include?(direction)
16+
self.bearing = direction
17+
end
18+
19+
def turn_right
20+
turn(:+)
21+
end
22+
23+
def turn_left
24+
turn(:-)
25+
end
26+
27+
def advance
28+
if bearing == :north
29+
self.y += 1
30+
elsif bearing == :south
31+
self.y -= 1
32+
elsif bearing == :west
33+
self.x -= 1
34+
else
35+
self.x += 1
36+
end
37+
end
38+
39+
private
40+
41+
def turn(sign)
42+
i = cardinal_directions.index(bearing)
43+
self.bearing = cardinal_directions[i.send(sign, 1) % 4]
44+
end
45+
46+
def cardinal_directions
47+
[:north, :east, :south, :west]
48+
end
49+
end
50+
51+
class Simulator
52+
def instructions(text)
53+
text.split('').map { |char| command(char) }
54+
end
55+
56+
def place(robot, position)
57+
robot.at(position[:x], position[:y])
58+
robot.orient(position[:direction])
59+
end
60+
61+
def evaluate(robot, text)
62+
instructions(text).each do |command|
63+
robot.send(command)
64+
end
65+
end
66+
67+
private
68+
69+
def command(char)
70+
{
71+
'R' => :turn_right,
72+
'L' => :turn_left,
73+
'A' => :advance
74+
}[char]
75+
end
76+
77+
end

0 commit comments

Comments
 (0)