Last active
July 28, 2019 04:27
-
-
Save manojnaidu619/7bbf6aa475d38a72f96b7b914fea6363 to your computer and use it in GitHub Desktop.
Leetcode Solution for "Alphabet Board Path" in Ruby
This file contains hidden or 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
def alphabet_board_path(target) | |
board = [ | |
['a','b','c','d','e'], | |
['f','g','h','i','j'], | |
['k','l','m','n','o'], | |
['p','q','r','s','t'], | |
['u','v','w','x','y'], | |
['z'] | |
] | |
answer = [] | |
beg = [0,0] | |
c=0 | |
target.each_char do |i| | |
row = board.detect{|aa| aa.include?(i)} | |
loc = [board.index(row), row.index(i)] | |
x = beg[0]-loc[0] | |
y = beg[1]-loc[1] | |
if(loc == [x,y]) | |
answer.push("!") | |
c+=1 | |
beg = loc | |
end | |
x.abs.times {answer.push('D')} if x<0 | |
x.abs.times {answer.push('U')} if x>0 | |
y.abs.times {answer.push('R')} if y<0 | |
y.abs.times {answer.push('L')} if y>0 | |
beg = loc | |
answer.push("!") if c<1 | |
c=0 | |
end | |
p answer.join('') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment