-
-
Save rayjcwu/11198633 to your computer and use it in GitHub Desktop.
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
Given an input string, return the commands need to input the string in a dvr. Commands are “l”, “r”, “u”, “d”, and “*”. | |
input was "bad" -> "r*l*rrr*" | |
[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 | |
// | |
public String move(String word) { | |
int[] prev = new int[2]; // init as (0, 0) = a | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < word.length(); ++i) { | |
int[] cur = charToCoord(word.charAt(i)); | |
sb.append(charMove(prev, cur)); | |
sb.append('*'); | |
prev = cur; | |
} | |
return sb.toString(); | |
} | |
public int[] charToCoord(char c) { | |
int[] coord = new int[2]; // (y, x) | |
int idx = c - 'a'; | |
coord[0] = idx / 5; | |
coord[0] = idx % 5; | |
return coord; | |
} | |
public String charMove(int[] start, int[] end) { | |
String result = ""; | |
final int dy = end[0] - start[0]; | |
final int dx = end[1] - start[1]; | |
if (dy == 0) { | |
// start.y == end.y | |
result = dxMove(dx); | |
} else if (dy < 0) { | |
// start.y > end.y, first go up, then go left/right | |
result = dyMove(dy) + dxMove(dx); | |
} else /* dy > 0 */ { | |
// start.y < end.y, first go left/right, then go down | |
result = dxMove(dx) + dyMove(dy); | |
} | |
return result; | |
} | |
public String dyMove(int dy) { | |
if (dy > 0) { | |
return repeat('d', dy); | |
} else if (dy < 0) { | |
return repeat('u', -dy); | |
} else { | |
return ""; | |
} | |
} | |
public String dxMove(int dx) { | |
if (dx > 0) { | |
return repeat('r', dx); | |
} else if (dx < 0) { | |
return repeat('l', -dx); | |
} else { | |
return ""; | |
} | |
} | |
public String repeat(char c, int times) { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < times; ++i) { | |
sb.append(c); | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment