0

I'm currently using a Multiset to hold a maximum of three numbers. I need to check if:

  1. A number appears more than once
  2. A number and another number appear the same amount of times
  3. There is only one number
  4. The list is empty

Below is my current code. In this case, team is a Multimap and points is the Multiset:

for(int a = 0; a <= team.keySet().size(); a++)
{
    if(points.count(a) > 1)
    {
    // Point 1
    }
    else if(points.size == 1)
    {
    // Point 3
    }
    else if(points.isEmpty()
    {
    // Point 4
    }
}

I'm stuck as to how I would implement Point 2 - any suggestions?

4

3 回答 3

0

我真的不明白你为什么要对 Multimap 的 keySet 大小进行 for 循环,然后检查递增计数器的计数......

这就是我假设您提到的Multimap原因,因为您想MultisetMultimap#keys(). 这里有示例代码:

final class MultisetFromMultimap {
  public static void main(String[] args) {
    Multimap<Integer, Integer> team = ImmutableMultimap.of(
        1, 1,
        1, 2,
        2, 22,
        2, 33,
        3, 0);
    test(team, 2, 1);
    test(ImmutableMultimap.of(42, 42), 42, 1);
    test(ImmutableMultimap.<Integer, Integer>of(), 0, 1);
  }

  private static void test(Multimap<Integer, Integer> team,
      Integer test1, Integer test2) {
    System.out.println("multimap: " + team);
    Multiset<Integer> points = team.keys();
    System.out.println("multiset: " + points);

    boolean ad1 = points.count(test1) > 1; // point 1
    boolean ad2 = points.count(test1) == points.count(test2); // point 2
    boolean ad3 = points.size() == 1; // point 3
    boolean ad4 = points.isEmpty(); // point 4
    System.out.println("answers: " + Arrays.asList(ad1, ad2, ad3, ad4));
  }
}

产生以下输出:

multimap: {1=[1, 2], 2=[22, 33], 3=[0]}
multiset: [1 x 2, 2 x 2, 3]
answers: [true, true, false, false]
multimap: {42=[42]}
multiset: [42]
answers: [false, false, true, false]
multimap: {}
multiset: []
answers: [false, true, false, true]
于 2012-08-11T10:18:01.557 回答
0

怎么样 :

Multiset<Integer> tmp = HashMultiset.create();
for(int a = 0; a <= team.keySet().size(); a++) {
  tmp.add(points.count(a));
}

现在看看 tmp 是否有一个 count() > 1 的值

于 2012-08-07T19:25:36.947 回答
0

for-loop 之前,声明 a如果某个数字 a 具有条目,则
Map<Integer,Boolean> numEntries = new HashMap<Integer,Boolean>();
此映射将包含一个true 值。 然后,在最后一个之后,您可以添加:
else if

if (numEntries.containsKey(points.count(a)) && numEntries.get(points.count(a)){
    //Point 2, some other number has already had this number of entries
} else {
    numEntries.put(points.count(a), true); // a has this number of entries!
    //Or do something more complicated to save that it was the number a that
    //"was here first" (you could change the value type from Boolean to Integer
    //or something to save this information)
}

由于对 points.count(a) 的大量使用,我会考虑将其设为局部变量。

编辑以前有错误的逻辑,上面的代码现在应该可以正常运行

于 2012-08-07T21:03:39.810 回答