您好,我目前正在研究算法问题集。
给定 file.txt 文件中的以下文件,
yahoo,ap42
google,ap42
twitter,thl76
google,aa314
google,aa314
google,thl76
twitter,aa314
twitter,ap42
yahoo,aa314
网络服务器在日志文件中记录页面浏览量。日志文件由每个页面 View 一行组成。页面 View 由页面 ID 和用户 ID 组成,以逗号分隔。一对页面的亲和性是查看这两个页面的不同用户的数量。例如,在引用的日志文件中,yahoo 和 google 的相似度为 2(因为 ap42 和 aa314 都看过)。
我的要求是创建一个算法,返回具有最高亲和性的页面对。
目前,我已经编写了下面的代码,但是,现在它没有返回具有最高亲和性的页面对,有没有关于我如何修改代码以使其工作的建议?谢谢。 :
Scanner in = new Scanner(new File("./file.txt"));
ArrayList<String[]> logList = new ArrayList<String[]>();
while (in.hasNextLine()) {
logList.add(in.nextLine().split(","));
}
String currentPage;
String currentUser;
int highestCount =0;
for (int i = 0; i < logList.size()-1; i++) {
int affinityCount =0;
currentPage = logList.get(i)[0];
currentUser = logList.get(i)[1];
for (int j = logList.size()-1; j > 0; j--) {
if (i != j) {
if (!currentPage.equals(logList.get(j)[0])
&& currentUser.equals(logList.get(j)[1])) {
affinityCount++;
System.out.println("currentPage: "+currentPage+" currentUser: "+ currentUser);
System.out.println("logList.get(j)[0]: "+logList.get(j)[0]+" logList.get(j)[1]): "+ logList.get(j)[1]);
System.out.println(affinityCount);
}
}
}
}
最佳答案
我打算在这里写算法。您可以将其转换为代码。
- 遍历文件并创建一个 hashMap 。
- 遍历后,您将获得每个用户浏览过的页面。
现在遍历这个数据集。对于每个用户,取出他浏览过的页面列表。对页面对进行所有可能的组合,并将其放入值设置为 1 的最大堆中。如果组合存在于堆中,则增加值。 确保在比较时对待 - yahoo,google 与 google,yahoo 相同。
最后,堆顶部的元素就是您的输出。
关于java - 在 Java 中找到具有最高亲和性的值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39354597/