-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolve.rb
executable file
·123 lines (97 loc) · 2.44 KB
/
solve.rb
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
116
117
118
119
120
121
122
123
#!/usr/bin/env ruby
class Point
attr_reader :x
attr_reader :y
def initialize(x, y)
@x = x
@y = y
end
def rotate(angle)
case angle % 360
when 90 then @x, @y = @y, -@x
when 180 then @x, @y = -@x, -@y
when 270 then @x, @y = -@y, @x
end
end
def move(dx, dy)
@x += dx
@y += dy
end
def move_towards(waypoint, distance)
dx = distance * waypoint.x
dy = distance * waypoint.y
@x += dx
@y += dy
end
def move_to_angle(angle, distance)
dx = 0
dy = 0
case angle % 360
when 0 then dx = distance
when 90 then dy = distance
when 180 then dx = -distance
when 270 then dy = -distance
end
move(dx, dy)
end
def distance
@x.abs + @y.abs
end
def to_s
"(#{@x}, #{y})"
end
end
class SimpleShip
def initialize()
@loc = Point.new(0, 0)
@angle = 0
end
def rotate(angle)
@angle = (@angle + angle) % 360
end
def command(name, arg)
case name
when 'F' then @loc.move_to_angle(@angle, arg)
when 'B' then @loc.move_to_angle(@angle, -arg)
when 'N' then @loc.move(0, -arg)
when 'S' then @loc.move(0, arg)
when 'W' then @loc.move(-arg, 0)
when 'E' then @loc.move(arg, 0)
when 'R' then rotate(arg)
when 'L' then rotate(-arg)
end
end
def distance
@loc.distance
end
end
class ShipWithWaypoint
def initialize()
@loc = Point.new(0, 0)
@waypoint = Point.new(-1, 10)
end
def command(name, arg)
case name
when 'F' then @loc.move_towards(@waypoint, arg)
when 'B' then @loc.move_towards(@waypoint, arg)
when 'N' then @waypoint.move(-arg, 0)
when 'S' then @waypoint.move(arg, 0)
when 'W' then @waypoint.move(0, -arg)
when 'E' then @waypoint.move(0, arg)
when 'R' then @waypoint.rotate(arg)
when 'L' then @waypoint.rotate(-arg)
end
end
def distance
@loc.distance
end
end
ship1 = SimpleShip.new
ship2 = ShipWithWaypoint.new
ARGF.each_line do |line|
cmd = line[0]
arg = line[1...].to_i
ship1.command(cmd, arg)
ship2.command(cmd, arg)
end
puts "#{ship1.distance} #{ship2.distance}"