我在线性代数中有一个学校任务,我必须创建一个加密应用程序。首先用户输入输入字符串,我将其转换为ASCII并将值放在数组中。之后,我创建一个具有用户输入长度的2D矩阵,并填充随机数字> = 0和< 100.现在我必须将ASCII数组与创建的2D矩阵相乘以获得编码消息。我从下面的网站中选择了矢量矩阵算法,但它似乎返回了错误的答案。 所有建议都高度赞赏! http://introcs.cs.princeton.edu/java/22library/Matrix.java.html
代码:
public static int[] convertToASCII(String input) {
int[] ascii = new int[input.length()];
System.out.println("ASCII: ");
for(char c : input.toCharArray()) {
for(int x = 0; x < 1;x++) {
//convert to ascii
ascii[x] = (int)c;
System.out.print(ascii[x] + " ");
}
}
return ascii;
}
// generate random matrix according to the length of user input.
private static double[][] rndMatrix() {
double[][] rndMatrix = new double[ASCII.length][ASCII.length];
System.out.println("\n" + "Random matrix: ");
Random rand = new Random();
for(int i = 0; i < rndMatrix.length;i++) {
System.out.print("|");
for(int j=0;j < rndMatrix[i].length;j++) {
Integer r = rand.nextInt()% 100;
rndMatrix[i][j] = Math.abs(r);
System.out.printf("%4d",(int)rndMatrix[i][j]);
}
System.out.println(" |");
}
return rndMatrix;
}
//crypt the message by multiplying randomly generated matrix with ascii codes
private static double[] cryptMsg(double[][] randomMatrix2, int[] ascii) {
int m = randomMatrix2.length;
int n = randomMatrix2[0].length;
double[] y = new double[m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++){
y[i] += randomMatrix2[i][j] * ascii[j];
System.out.println(y[i]);
}
}
return y;
}
示例:
Input:
hi
ASCII:
104 105
Random matrix:
| 85 15 |
| 79 21 |
Coded message:
8925.0 8295.0 (Has to be 10415.0 10421)
答案 0 :(得分:2)
您的convertToASCII(String input)
功能错误。您始终设置数组的第一个索引。将其更改为:
public static int[] convertToASCII(String input) {
int[] ascii = new int[input.length()];
for (int x = 0; x < ascii.length; x++) {
ascii[x] = input.codePointAt(x);
}
return ascii;
}
我测试了你的矩阵乘法,它很好:
public static void print(double[] arr) {
StringBuilder sb = new StringBuilder();
for (double x : arr) {
sb.append(x);
sb.append(", ");
}
System.out.println(sb.toString());
}
public static void main(String[] args) {
double[][] mx1 = { { 1, 2 }, { 4, 8 } };
int[] vec1 = { 0, 1 };
int[] vec2 = { 1, 0 };
int[] vec3 = { 5, 7 };
print(cryptMsg(mx1, vec1)); // 2.0, 8.0,
print(cryptMsg(mx1, vec2)); // 1.0, 4.0,
print(cryptMsg(mx1, vec3)); // 19.0, 76.0,
int[] vec4 = { 104, 105 };
double[][] mx2 = { { 85, 15 }, { 79, 21 } };
print(cryptMsg(mx2, vec4)); // 10415.0, 10421.0,
}