【问题标题】:How to keep track of number of occurrences between two dependent LinkedLists?如何跟踪两个依赖链表之间的出现次数?
【发布时间】:2021-05-17 20:49:17
【问题描述】:

我在弄清楚如何跟踪两个相关的 LinkedList 之间的事件时遇到了一些麻烦。

让我用一个例子来详细说明:

这些是有问题的链表。

它们是相互依赖的,因为第一个列表中的每个值都对应于具有相同索引 i 的第二个列表中的值。两个列表的长度始终相同。

{sunny, sunny, rainy, sunny, cloudy, sunny, ...}
{yes, no, no, maybe, yes, no, ...}

我需要以某种方式跟踪发生的“对”。 例如:

sunny -> 1 yes, 1 maybe, 2 no
rainy -> 1 no
cloudy -> 1 yes

注意:不一定只有 3 个选项。可以有更多或更少。此外,列表中的项目名称以前是未知的。

所以是的,我想知道存储这些信息的最佳方式是什么,因为我遇到了死胡同。

感谢任何帮助。

【问题讨论】:

    标签: java list data-structures linked-list


    【解决方案1】:

    您可以通过Map<String, Map<String, Integer> 来做到这一点。

    • 外图的关键是天气(sunny、rainy等)
    • 该值是另一个映射,其中包含每个可能的值(yes、no、maybe...)以及该值出现的次数。

    像这样合并两个列表:

    public static Map<String, Map<String, Integer>> count(List<String> weathers, List<String> answers) {
        //weathers olds the strings 'sunny', 'rainy', 'sunny'...
        //answers old the strings 'yes', 'no'...
        //this code assumes both lists have the same size, you can enforce this in a check or throw if not the case
        Map<String, Map<String, Integer>> merged = new HashMap<>();
        for (int j = 0; j < weathers.size(); j++) {
            if (merged.containsKey(weathers.get(j))) {
                Map<String, Integer> counts = merged.get(weathers.get(j));
                counts.put(answers.get(j), counts.getOrDefault(answers.get(j), 0) + 1);
            } else {
                Map<String, Integer> newAnswer = new HashMap<>();
                newAnswer.put(answer.get(j), 1);     
                merged.put(weathers.get(j), newAnswer);
            }
        }
        return merged;
    }
    

    应用到上述代码的逻辑是循环遍历列表的每个事件,然后检查您的地图是否已经包含该天气。

    • 如果是这种情况,您将获得已经存在的地图并增加该答案的数量(如果答案尚不存在,您将从零开始)
    • 如果不是这种情况,您可以为该天气添加一张新地图,其中您只有第一个答案,计数为 1。

    示例用法:

    Map<String, Map<String, Integer>> resume = count(weathers, answers);
    //How many times 'sunny' weather was 'maybe'? 
    Integer answer1 = resume.get("sunny").get("maybe");
    //How many times 'rainy' weather was 'no'? 
    Integer answer2 = resume.get("rainy").get("no");
    //etc.
    

    【讨论】:

    • 感谢您的快速回复。该代码对我来说很有意义,但由于某种原因,我得到了 UnsupportedOperationException 或更准确地说是 ImmutableCollection 异常。我从 Map.Entry> 循环中调用函数,其中 List 是“天气”列表,因此我将 entry.getValue() 参数传递给您编写的函数。我假设我在某个地方犯了错误,但我无法确定它。
    • 哦,是的,这是因为 Map.of() 创建了一个不可变的地图,但是您尝试在下一次迭代时再次更新它。在这里用处不大。我会更新我的代码
    • 谢谢!现在它完美地工作了。你为我节省了很多时间!
    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多