Interview Question
Country: United States
void main()
{
char* input = "if man was meant to stay on the ground god would have given us roots";
char* spaceless = new char[strlen(input)];
for (int i = 0, j = 0; !i || input[i-1]; i++)
if (input[i] != ' ')
spaceless[j++] = input[i];
int numRow = (int)sqrt((float)strlen(spaceless));
int lastRow = strlen(spaceless) - numRow*numRow + 1;
int numCol = numRow + (lastRow != 0);
for (int i = 0; i < numCol; i++, printf(" "))
for (int j = 0; j < numRow; j++)
if ((j < numRow - 1) || (i < lastRow))
printf("%c", spaceless[j*numCol + i]);
getch();
};
output:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
}
StringBuilder resultString = new StringBuilder();
String[] words = sentence.split("\\s+");
StringBuilder allWords = new StringBuilder(sentence.length());
for (String word : words){
allWords.append(word.toLowerCase());
}
int counter = 0 , allWordsLength = allWords.length();
while (counter < allWordsLength){
int upper = counter + 8;
if (upper < allWordsLength){
resultString.append(allWords.substring(counter, upper)+" ");
}else{
resultString.append(allWords.substring(counter));
}
counter += 8;
}
return resultString.toString();
One classic method for composing secret messages is called a square code. The spaces are removed from the English text and the characters are written into a square (or rectangle). For example, the sentence "If man was meant to stay on the ground god would have given us roots" is 54 characters long, so it is written into a rectangle with 7 rows and 8 columns.
ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as:
the idea for this one is binary search to find low bound (row) and upper bound (col) for the
2-d array
- Scott March 04, 2015