2012-08-07 108 views
0

我目前使用Multiset来保存最多三个数字。我需要检查:使用Multiset来计算出现次数

  1. 一个数字出现不止一次
  2. 一些和另一个号码出现的次数相同数量
  3. 只有一个数字
  4. 列表为空

下面是我目前的代码。在这种情况下,球队是一个Multimap之和的点是多集:

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 
    } 
} 

我坚持为我将如何落实2点 - 有什么建议?

回答

0

如何:

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

现在看看tmp目录有计数()> 1

0

for -loop之前,申报
Map<Integer,Boolean> numEntries = new HashMap<Integer,Boolean>();
此地图将包含true如果某个数字a有条目。
然后,最后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(一),我会考虑将它的局部变量。

编辑收到了错误的逻辑,上面的代码现在应该循规蹈矩

0

我真不明白你为什么for循环对Multimap之的键集大小做,然后增加计数器检查个性化......

这就是为什么我假设你提到Multimap,因为你想从Multimap#keys()获得Multiset。在这里,你有例子代码:

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]