Interview Question
Software Engineer / DevelopersCountry: United States
every time you need to update the precol and prevrow in the end of the for loop. (Sorry dismiss this message. I dismiss that you ++percol in the while loop)
This is a highschool question.
Scan the array to find next position (x,y).
Compare with previous one (xp, yp).
Keep going like that.
O(N^2 * stringlength).
public class OnScreenKeyboard {
public static void main(String[] a) {
OnScreenKeyboard onScreenKeyboard = new OnScreenKeyboard();
onScreenKeyboard.findLocation("dacixdsadsrascv", 5);
}
private void findLocation(String string, int length) {
int currentRow = 1, currentCol = 1, row = 0, col = 0, ascii = 0;
char array[] = string.toCharArray();
StringBuilder sb = new StringBuilder();
for (char element : array) {
ascii = ((int) element) - 96;
row = (ascii / length) + 1;
col = ascii % length;
for (int i = Math.abs(row - currentRow); i > 0; i--) {
sb.append((currentRow < row) ? "d" : "u");
}
for (int i = Math.abs(col - currentCol); i > 0; i--) {
sb.append((currentCol < col) ? "r" : "l");
}
sb.append("!");
currentRow = row;
currentCol = col;
}
System.out.print(sb.toString());
}
}
for(int i=0; i<s.length(); i++)
{
col = ( s[i]-'a' ) % ROW_LEN;
row = ( s[i]-'a' ) / ROW_LEN;
while(col>prevcol) { putchar('r'); col--; }
while(col<prevcol) { putchar('l'); col++; }
while(row>prevrow) { putchar('d'); col--; }
while(row<prevrow) { putchar('u'); col++; }
putchar('!');
}
for(int i=0; i<s.length(); i++)
{
col = ( s[i]-'a' ) % ROW_LEN;
row = ( s[i]-'a' ) / ROW_LEN;
while(col>prevcol) { putchar('r'); col--; }
while(col<prevcol) { putchar('l'); col++; }
while(row>prevrow) { putchar('d'); row--; }
while(row<prevrow) { putchar('u'); row++; }
putchar('!');
}
- S O U N D W A V E March 20, 2014