Created
April 16, 2014 15:11
-
-
Save adbatista/10891686 to your computer and use it in GitHub Desktop.
Challengers Hackerrank
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
Position = Struct.new(:x,:y) do | |
def ==(pos) | |
x == pos.x && y == pos.y | |
end | |
end | |
class Finder | |
def self.princess(grid) | |
edge = grid.length - 1 | |
[0,edge].each do |row| | |
[0,edge].each do |col| | |
return Position.new(col,row) if grid[row][col] == 'p' | |
end | |
end | |
end | |
def self.bot(grid) | |
x = y = grid.length / 2 | |
Position.new(x,y) | |
end | |
end | |
def displayPathtoPrincess(n,grid) | |
princess = Finder.princess(grid) | |
bot = Finder.bot(grid) | |
path = [] | |
while bot != princess | |
path << if bot.x < princess.x | |
bot.x += 1 | |
"RIGHT" | |
elsif bot.x > princess.x | |
bot.x -= 1 | |
"LEFT" | |
end | |
path << if bot.y < princess.y | |
bot.y += 1 | |
"DOWN" | |
elsif bot.y > princess.y | |
bot.y -= 1 | |
"UP" | |
end | |
end | |
path | |
end | |
m = gets.to_i | |
grid = Array.new(m) | |
(0...m).each do |i| | |
grid[i] = gets.strip | |
end | |
puts displayPathtoPrincess(m,grid) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/ruby | |
Position = Struct.new(:x,:y) | |
def find_princess(grid) | |
grid.each_with_index do |row, y| | |
row.each_char do |col| | |
return Position.new(row.index(col), y ) if col == 'p' | |
end | |
end | |
end | |
def nextMove(n,r,c,grid) | |
bot = Position.new c, r | |
princess = find_princess grid | |
delta = { | |
x: bot.x - princess.x, | |
y: bot.y - princess.y | |
} | |
far = delta.max_by {|_,value| value.abs} | |
case far[0] | |
when :x | |
far[1] < 0 ? "RIGHT" : "LEFT" | |
when :y | |
far[1] < 0 ? "DOWN" : "UP" | |
end | |
end | |
n = gets.to_i | |
r,c = gets.strip.split.map(&:to_i) | |
grid = Array.new(n) | |
(0...n).each do |i| | |
grid[i] = gets | |
end | |
puts nextMove(n,r,c,grid) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment