Created
February 14, 2013 23:55
-
-
Save andrewberls/4957505 to your computer and use it in GitHub Desktop.
Save the princess! https://www.hackerrank.com/challenges/saveprincess
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
# Test cases used | |
# | |
# DOWN LEFT | |
# 3 | |
# --- | |
# -m- | |
# p-- | |
# UP RIGHT | |
# 3 | |
# --p | |
# -m- | |
# --- | |
# Read input | |
grid = [] | |
gets.to_i.times do | |
buf = gets.scan /./ | |
grid << buf | |
buf = [] | |
end | |
# Find coordinates | |
player = {} | |
princess = {} | |
grid.each_with_index do |row, rowIdx| | |
playerColIdx = row.find_index("m") || -1 | |
prinColIdx = row.find_index("p") || -1 | |
player = { row: rowIdx, col: playerColIdx } if playerColIdx >= 0 | |
princess = { row: rowIdx, col: prinColIdx} if prinColIdx >= 0 | |
end | |
# Calculate moves | |
until player[:row] == princess[:row] | |
prinAbove = player[:row] > princess[:row] | |
puts (prinAbove) ? 'UP' : 'DOWN' | |
player[:row] += prinAbove ? -1 : 1 | |
end | |
until player[:col] == princess[:col] | |
prinLeft = player[:col] > princess[:col] | |
puts (prinLeft) ? 'LEFT' : 'RIGHT' | |
player[:col] += prinLeft ? -1 : 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment