一种简单的换位密码



我需要编写一个简单的列换位密码程序。

到目前为止,我拥有的是:

public static String transpositionCipher(String text, int N) {
String output = "";
char[][] split = new char[N][text.length()];
for (int i = 0; i <= N; i++) {
for (int j = 0; j < text.length(); j++) {
split[i][j] = text.charAt(i * text.length() + j);
System.out.println(split[i][j]);
}
System.out.println("");
}
}

Bellow是我的程序的输入和预期输出:

输入#1

text = "New atak", N = 3

换位矩阵:

N e w
_ a t
a k _

OUPUT#1

"N aeakwt"

输入#2

text = "NOS ATACAN CON CARBUNCO", N = 5

换位矩阵:

N O S _ A
T A C A N
_ C O N _
C A R B U
N C O _ _

OUPUT#2

"NT CNOACACSCORO ANB AN U"

请参阅下面代码中方法cifradoTransjavadoc注释。请注意,为了更好地可视化,我将空格替换为下划线。

public class CipherSq {
/**
* Places characters of <var>cadena</var> in a matrix with <var>numberOfColumnsInMatrix</var>
* columns and as many rows as required in order to hold all characters of <var>cadena</var>.
* Stores the characters in rows, i.e. first character in <var>cadena</var> is in first row,
* first column of matrix. Second character of <var>cadena</var> is in first row, second column
* of matrix, and so on. Then a string is created by traversing the matrix column by column and
* concatenating the matrix elements, i.e. first character of returned string is character in
* first row, first column of matrix. Second character in string is second row, first column of
* matrix and so on.
* 
* @param cadena                  - string to manipulate.
* @param numberOfColumnsInMatrix - number of columns in matrix.
* 
* @return Manipulated string.
*/
public static String cifradoTrans(String cadena, int numberOfColumnsInMatrix) {
cadena = cadena.replace(' ', '_');
char[] characters = cadena.toCharArray();
int len = cadena.length();
int rows = (int) Math.ceil((double) len / numberOfColumnsInMatrix);
char[][] matrix = new char[rows][numberOfColumnsInMatrix];
int row = 0;
int col = 0;
int i = 0;
for (; i < len; i++) {
col = i % numberOfColumnsInMatrix;
if (col == 0) {
row = i / numberOfColumnsInMatrix;
System.out.println();
}
matrix[row][col] = characters[i];
System.out.print(characters[i] + " ");
}
for (col++; col < numberOfColumnsInMatrix; col++) {
matrix[row][col] = '_';
System.out.print(matrix[row][col] + " ");
}
System.out.println(System.lineSeparator());
i = 0;
char[] newCharacters = new char[rows * numberOfColumnsInMatrix];
for (col = 0; col < numberOfColumnsInMatrix; col++) {
for (row = 0; row < rows; row++) {
newCharacters[i++] = matrix[row][col];
}
}
return new String(newCharacters);
}
/**
* Recognizes two command-line arguments. First is string to manipulate.
* Second is number of columns in matrix.
*/
public static void main(String[] args) {
if (args.length > 1) {
System.out.println(cifradoTrans(args[0], Integer.parseInt(args[1])));
}
else {
System.out.println("ARGS: string int");
}
}
}

当我使用[命令行]参数"NOS ATACAN CON CARBUNCO"5运行上面的代码时,我得到以下输出:

N O S _ A 
T A C A N 
_ C O N _ 
C A R B U 
N C O _ _ 
NT_CNOACACSCORO_ANB_AN_U_

最新更新