我有一个二维数组,我需要比较数组中的数组,以找到它们之间的相似之处。如果在一个数组中找到一个项目而在另一个数组中找到一个项目则会在计数中添加Count记录相似之处。如果计数到目前为止最高,那么它就是最相似的。然后它将打印空白最类似于空白。
double[][] ratingDB = {{4.0, 3.0, 3.0, 3.0, 3.0}, {3.0, 2.0, 3.0, 3.5, 3.0},
{4.0, 3.0, 4.0, 3.0, 3.0}, {3.0, 2.0, 3.0, 3.5, 3.0}, {3.0, 2.0, 3.0, 3.5, 3.0}};
String temp = null;
for (int i = 0; i < ratingDB.length; i++) {
for (int j = 1; j < ratingDB.length; j++) {
int maxCount = 0;
int count = 0;
for (int k = 0; k < ratingDB.length-1; k++) {
if (ratingDB[i][k] == ratingDB[j][k]) {
count++;
if (count >= maxCount) {
maxCount = count;
temp = "User_" + k;
}
}
}
}
System.out.println("User_" + i + " is most simlar to " + temp);
}
这是需要做的事情的总体思路。然而,我正在努力获得正确的结果,我无法弄明白。我从这段代码得到的结果是:
User_0 is most simlar to User_2
User_1 is most simlar to User_3
User_2 is most simlar to User_3
User_3 is most simlar to User_3
User_4 is most simlar to User_3
我需要的结果是:
user_0 most similar to user_2
user_1 most similar to user_4
user_2 most similar to user_0
user_3 most similar to user_4
user_4 most similar to user_3
答案 0 :(得分:0)
您的代码的问题在于您同时重置计数和maxCount,并且当您递增计数并立即设置maxCount = count时,它会使maxCount几乎总是与count相同。
查看以下代码和以下结果:
double[][] ratingDB = {
{4.0, 3.0, 3.0, 3.0, 3.0},
{3.0, 2.0, 3.0, 3.5, 3.0},
{4.0, 3.0, 4.0, 3.0, 3.0},
{3.0, 2.0, 3.0, 3.5, 3.0},
{3.0, 2.0, 3.0, 3.5, 3.0}};
int height = ratingDB.length;
int width = ratingDB[0].length;;
for (int i = 0; i < height; i++) {
int maxCount = 0;
int temp = -1;
for (int j = 0; j < height; j++) {
int count = 0;
for (int k = 0; k < width; k++) {
if (ratingDB[i][k] == ratingDB[j][k] && i != j) {
count++;
}
}
if (count > maxCount) {
maxCount = count;
temp = j;
}
}
System.out.println("User_" + i + " is most similar to User_" + temp);
}
注意“count”在k循环开始之前设置为0,并且恰好在之后进行比较。另请注意,在count = 0的循环外,“maxCount”设置为0。 这将返回以下结果,这些结果有效:
User_0 is most similar to User_2
User_1 is most similar to User_3
User_2 is most similar to User_0
User_3 is most similar to User_1
User_4 is most similar to User_1
答案 1 :(得分:-2)
{{1}}