【问题标题】:finding the value pair that has the highest affinity in Java?在 Java 中找到具有最高亲和力的值对?
【发布时间】:2016-09-06 17:21:54
【问题描述】:

您好,我目前正在研究算法问题集。

鉴于file.txt文件中的以下文件,

yahoo,ap42
google,ap42
twitter,thl76
google,aa314
google,aa314
google,thl76
twitter,aa314
twitter,ap42
yahoo,aa314

Web 服务器在日志文件中记录页面浏览量。日志文件由每个页面视图一行组成。页面视图由页面 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);
                }
            }
        }
    }

【问题讨论】:

  • 您是否只需要亲和力最高的前 2 个页面或更多?
  • 是的,我希望找到具有最高亲和力的前 2 个页面对。谢谢。
  • 你知道不同网页的数量和用户名的大小吗?
  • 还有如果有平局,你输出哪一个?

标签: java arrays algorithm sorting data-structures


【解决方案1】:

我要在这里写算法。您可以将其转换为代码。

  1. 遍历文件,创建一个hashMap。
  2. 遍历之后,你会得到每个用户浏览过的页面。
  3. 现在遍历这个数据集。对于每个用户,取出他查看的页面列表。制作所有可能的页面对组合并将其放入最大堆中,并将值设置为 1。如果该组合存在于堆中,则增加该值。 确保您在比较时对待 - yahoo,google 与 google,yahoo 相同。

  4. 最后,堆顶的元素就是你的输出。

【讨论】:

    猜你喜欢
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 2020-04-04
    • 2019-04-11
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多