-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhackerrank_bot_saves_princess_1.rb
More file actions
84 lines (69 loc) · 1.85 KB
/
hackerrank_bot_saves_princess_1.rb
File metadata and controls
84 lines (69 loc) · 1.85 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
# frozen_string_literal: true
# HackerRank submission for 'Bot Saves Princess' with heavy OOP/Rubyism focus.
# Removed all custom error handling, user input validation, builder classes and helpers that exist in bot_saves_princess_1 directory.
class Position
attr_reader :row, :column
def initialize(row, column)
@row = row
@column = column
end
def same_position?(other)
row == other.row && column == other.column
end
end
class Grid
attr_reader :n, :rows
def initialize(n, rows)
@n = n
@rows = rows
end
def character_at(row, column)
rows[row][column]
end
def find_character(character)
rows.each_with_index.map do |line, row|
col = line.index(character)
Position.new(row, col) if col
end.compact.first
end
end
class Bot
attr_reader :position
def initialize(position)
@position = position
end
def step_toward(target)
if position.row > target.row
@position = Position.new(position.row - 1, position.column)
'UP'
elsif position.row < target.row
@position = Position.new(position.row + 1, position.column)
'DOWN'
elsif position.column > target.column
@position = Position.new(position.row, position.column - 1)
'LEFT'
elsif position.column < target.column
@position = Position.new(position.row, position.column + 1)
'RIGHT'
end
end
def path_to(target)
moves = []
moves << step_toward(target) until position.same_position?(target)
moves
end
end
def displayPathtoPrincess(n, rows)
grid = Grid.new(n, rows)
bot_position = grid.find_character('m')
princess_position = grid.find_character('p')
bot = Bot.new(bot_position)
bot.path_to(princess_position).each do |move|
puts move
end
end
if __FILE__ == $PROGRAM_NAME
n = gets.to_i
grid = Array.new(n) { gets.chomp }
displayPathtoPrincess(n, grid)
end