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

どうですか:

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

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

for-loopの前に、
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 に答える