HackerRank: Encryption
An English text needs to be encrypted. The encryption algorithm first removes the spaces from the text and then the characters are written into a rectangle (or a square), whose width and height have the following constraints:
floor(sqrt( len(word) )) <= width, height <= ceil(sqrt( len(word) ))
In case of a rectangle, the number of rows will always be smaller than the number of columns.
Also ensure, height * width >= len(word)
If multiple rectangles satisfy the above conditions, choose the one with the minimum area.
The encoded message is obtained by displaying the characters in a column, inserting a space, and then displaying the next column and inserting a space and so on.For example, the encoded message for the above rectangle is:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
You will be given a message in English with no spaces between the words.The maximum message length can be 81 characters. Print the encoded message.
An English text needs to be encrypted. The encryption algorithm first removes the spaces from the text and then the characters are written into a rectangle (or a square), whose width and height have the following constraints:
floor(sqrt( len(word) )) <= width, height <= ceil(sqrt( len(word) ))
In case of a rectangle, the number of rows will always be smaller than the number of columns.
Also ensure, height * width >= len(word)
If multiple rectangles satisfy the above conditions, choose the one with the minimum area.
The encoded message is obtained by displaying the characters in a column, inserting a space, and then displaying the next column and inserting a space and so on.For example, the encoded message for the above rectangle is:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
You will be given a message in English with no spaces between the words.The maximum message length can be 81 characters. Print the encoded message.
int main()
{
string str;
cin >> str;
int len = (int)str.size();
int lb = (int)sqrt(1.0*len);
int ub = (int)ceil(sqrt(1.0*len));
int ans = INT_MAX;
int r = 0, c = 0;
for (int row = lb; row <= ub; row++)
for (int col = row; col <= ub; col++)
if (row * col >= len && row * col < ans)
{
ans = row * col;
r = row;
c = col;
}
for (int i = 0; i < c; i++)
{
for (int j = 0; j < r; j++)
if (j*c + i < len)
cout << str[j*c + i];
cout << " ";
}
cout << endl;
return 0;
}