gpt4 book ai didi

java - 矩阵乘以 vector 返回错误答案 Java

转载 作者:行者123 更新时间:2023-12-02 04:06:36 24 4
gpt4 key购买 nike

我有一项线性代数的学校任务,我必须创建一个加密应用程序。首先,用户键入输入字符串,我将其转换为 ASCII 并将值放入数组中。之后,我使用用户输入的长度创建一个 2D 矩阵,并填充 >= 0 和 < 100 的随机数字。现在我必须将 ASCII 数组与创建的 2D 矩阵相乘才能获得编码消息。我从下面的站点选择了 vector 矩阵算法,但它似乎返回了错误的答案。所有建议都受到高度赞赏! 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)

最佳答案

您的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,
}

关于java - 矩阵乘以 vector 返回错误答案 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34225967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com