2012-08-07 111 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]