我有一個線性代數的學校任務,我必須創建一個加密應用程序。首先用戶輸入輸入字符串,我將其轉換爲ASCII並將值放入數組中。之後,我創建一個帶有用戶輸入長度的2D矩陣,並填充隨機數字> = 0和< 100.現在,我必須將ASCII陣列與創建的2D矩陣相乘以獲得編碼消息。我從下面的網站中選擇矢量矩陣算法,但它似乎返回錯誤的答案。 所有建議高度讚賞! http://introcs.cs.princeton.edu/java/22library/Matrix.java.html矩陣乘以矢量返回錯誤答案Java
代碼:
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)
代碼看起來不錯乍一看。你能舉一個例子,它返回什麼和預期的? –
我檢查(matrix.reshish.com/multiplication.php)的答案,但我的應用程序dotn匹配的答案,但他們必須匹配的原因,否則我不能解密我的消息。我還注意到,所有的答案都以0或5結尾,所以可以由類型轉換造成? –
你沒有正確地進行矩陣乘法。 –