forked from hacktoberfest17/programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrobot_simulator.rb
More file actions
77 lines (61 loc) · 1.17 KB
/
robot_simulator.rb
File metadata and controls
77 lines (61 loc) · 1.17 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
class Robot
attr_accessor :x, :y, :bearing
def at(x, y)
self.x = x
self.y = y
end
def coordinates
[x, y]
end
def orient(direction)
fail ArgumentError unless cardinal_directions.include?(direction)
self.bearing = direction
end
def turn_right
turn(:+)
end
def turn_left
turn(:-)
end
def advance
if bearing == :north
self.y += 1
elsif bearing == :south
self.y -= 1
elsif bearing == :west
self.x -= 1
else
self.x += 1
end
end
private
def turn(sign)
i = cardinal_directions.index(bearing)
self.bearing = cardinal_directions[i.send(sign, 1) % 4]
end
def cardinal_directions
[:north, :east, :south, :west]
end
end
class Simulator
def instructions(text)
text.split('').map { |char| command(char) }
end
def place(robot, position)
robot.at(position[:x], position[:y])
robot.orient(position[:direction])
end
def evaluate(robot, text)
instructions(text).each do |command|
robot.send(command)
end
end
private
def command(char)
{
'R' => :turn_right,
'L' => :turn_left,
'A' => :advance
}[char]
end
end