Given the English alphabet, 'a' through 'z' (lowercase), and an imaginary onscreen keyboard
with the letters laid out in 6 rows and 5 columns:
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
Using a remote control - (up - 'u', down 'd', left 'l', right 'r' and enter '!'), write a
function that given a word will produce the sequence of key presses required to type out
the word on the onscreen keyboard. The function should return the sequence string.
例如"hello",就输出 d r r ! u r r ! d d l l l ! ! r r r !
with the letters laid out in 6 rows and 5 columns:
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
Using a remote control - (up - 'u', down 'd', left 'l', right 'r' and enter '!'), write a
function that given a word will produce the sequence of key presses required to type out
the word on the onscreen keyboard. The function should return the sequence string.
例如"hello",就输出 d r r ! u r r ! d d l l l ! ! r r r !
分析:
If we observe the 2D matrix[6][5], we have integer values as (intVal) :
a -> 0
b -> 1
e -> 4
f -> 5
.
.
.
z -> 25
=====================
Map these 1D values to 2D index values.
Let [ _i ] [ _j ] be current position of cursor on matrix.
Let i be a row_no and j be col_no.
ROW = 6;
COL = 5;
for any alphabet 'input', find [i][j] like this
i = intVal(input) / COL;
j = intVal(input) % COL;
now first move (i - _i) horizontal steps, then move (j - _j) vertical steps. This can be printed also.
After reaching to [i][j], print '!' (OK button), then update values of [ _i ] [ _j ] equal to [i][j].
#include <cstdio>
void PrintKeySequence(const char* word, char* sequence)
{
int row = 0;
int col = 0;
int ch,dst_row,dst_col,row_diff,col_diff,i,j,k;
for(i = 0,j = 0; word[i]; i++)
{
ch = word[i] - 'a';
dst_row = ch / 5;
dst_col = ch % 5;
row_diff = row - dst_row;
col_diff = col - dst_col;
if (row_diff > 0)
for(k = 0; k < row_diff; k++)
sequence[j++] = 'u';
else
for(k = 0; k < (0 - row_diff); k++)
sequence[j++] = 'd';
if (col_diff > 0)
for(k = 0; k < col_diff; k++)
sequence[j++] = 'l';
else
for(k = 0; k < (0 - col_diff); k++)
sequence[j++] = 'r';
sequence[j++] = '!';
row = dst_row;
col = dst_col;
}
sequence[j] = '\0';
}
int main()
{
char word[] = "hello";
char* seq = new char[100];
PrintKeySequence(word, seq);
for(int i = 0; seq[i]; i++)
{
printf("%c ", seq[i]);
}
printf("\n");
return 0;
}