我有一個2維數組,我需要比較數組中的數組以找出它們之間的相似性。如果在一個數組中找到一個項目,而另一個項目將爲計數添加一個項目。伯爵追蹤相似之處。如果計數是迄今爲止最高的,那麼它就是最相似的那個。然後它會打印空白最類似於空白。在二維數組中查找相似度
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
看起來很奇怪...您的計數變量將永遠是一個,因此你也MAXCOUNT,因爲你增加它之前,你將它設置爲0. – CCC
@Jordan我修復了最大值和計數變量的位置。現在他們在數組迭代完成後重置。 –