我正在为我的计算机科学类(class)开发一个密码项目,我们应该将一个字符串放入一个方形的二维数组中,用星号填充剩余的空间,然后通过对角遍历数组来打印出编码的消息。
例如,对于消息“testcipher”,数组将是
[t、e、s、t]
[c、i、p、h]
[e、r、*、*]
[*、*、*、*]
该数组将被处理为“t i * * e p * * s h e * t c r *”
我真的需要一些帮助来解决这个问题。提前致谢!
最佳答案
让我们一步一步来:
1) 我们需要找到二维数组的维数。由于必须对其进行平方,因此我们必须找到第一个大于或等于字符串长度的平方数。
小编辑:我假设密码是一个字符串。
int arrayDimension = 0;
while (arrayDimension * arrayDimension < cipher.length())
{
arrayDimension++;
}
2) 现在我们将密码逐字符放入数组中。
int currentCharacterIndex = 0;
for (int i = 0; i < arrayDimension; i++)
{
for (int j = 0; j < arrayDimension; j++)
{
if (currentCharacterIndex < cipher.length())
array[i][j] = cipher.charAt(currentCharacterIndex++);
else
array[i][j] = '*';
}
}
我想这可以简化,但是这段代码的目的是让您理解这个想法并希望编写一个更好的版本。
3) 我们已经有了数组,所以最简单的方法是将所有行(第一行除外)向左移动 rowIndex 次。
所以基本上对于一行 c i p h
我们最终会得到 i p h c
。因此,我们现在必须打印每一列,我们的工作就完成了。
代码应如下所示(非常简单,所以我将其留给您):
//Shift each row
char firstColumnChar;
for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
{
//We shift rowIndex times
for (int timesToShift = rowIndex; timesToShift > 0; timesToShift--)
{
firstColumnChar = array[rowIndex][0]; //We keep the first char in some variable
//We shift all elements to the left - except for the first one
for (int i = 0; i < rowIndex - 1; i++)
array[rowIndex][i] = array[rowIndex][i+1];
//We now shift the first character to the last column
array[rowIndex][arrayDimension - 1] = firstColumnChar;
}
}
//Print columns
for (int columnIndex = 0; columnIndex < arrayDimension; columnIndex++)
{
for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
System.out.print(array[rowIndex][columnIndex] + " ");
//You can print a '\n' here if you want to
}
关于java - 对角处理二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079512/