#include<iostream>
#include<conio.h>
#include<math.h>
#include<vector>
#include<iterator>
#include<string>
using namespace std;
int main() {
int k=0;
string s;
cout<<"string ";
getline(cin,s); //taking in a string from the user
float n=s.size(); //storing size of string
int f=floor((sqrt(n))); //floor of square root of input string
int c=ceil((sqrt(n))); //ceiling
int m=f*c; //storing product of f and c
vector< vector<string> > vec(n<=m?f:++f, vector<string>(c)); //makes a 2d vector
//depending on user's
//string length
for(int i=0;n<=m?i<f:i<++f;i++) //looping acc to user's input and assigning
{
for(int j=0;j<c;j++) //string to a matrix
{
if(k<s.size())
{
vec[i][j]=s[k];
k++;
}
}
}
for(int j=0;j<c;j++) //printing the vector
{
{
for(int i=0;n<=m?i<f:i<++f;i++)
cout<<vec[i][j];
}cout<<" ";
}
getch();
}
它不适用于 n>m,因为对于长度为 8 个字符的字符串,它会生成 2*3 的向量,因此无法将整个字符串包含在矩阵中,这就是为什么我使用三元来制作更大尺寸的向量当它遇到这样的情况时。.那么我做错了什么?
我只会写整个问题。
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). The width and height of the rectangle have the constraint,
floor(sqrt(word)) <= width, height <= ceil(sqrt(word))
The coded message is obtained by reading down the columns going left to right. For example, the message above is coded as:
imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
Sample Input:
chillout
Sample Output:
clu hlt io