プロが教える店舗&オフィスのセキュリティ対策術

配列の組み合わせを数えるイイ方法はないでしょうか?

たとえば
ArrayA[]={"aaa","bbb","aaa","ccc","bbb","aaa"}
ArrayB[]={"1","1","1","2","1","2"}

↑の配列があるとして、
aaa - 1 : 2個
aaa - 2 : 1個
bbb - 1 : 2個
ccc - 2 : 1個
と組み合わせの数を数えることができる方法で悩んでいます。
Strtusを用いて作成しています。

よろしくお願いします。

A 回答 (3件)

配列のまま数えるなら


String[] a = { "aaa", "bbb", "aaa", "ccc", "bbb", "aaa" };
String[] b = { "1", "1", "1", "2", "1", "2" };
int length = a.length;
int[] c = new int[length];
java.util.Arrays.fill(c, 1);
for (int i = length - 1; i >= 0; i--) {
int count = c[i];
String ai = a[i], bi = b[i];
for (int j = i - 1; j >= 0 && count > 0; j--) {
if (a[j] == ai && b[j] == bi) {
c[j] += count;
count = 0;
}
}
if (count > 0) {
System.out.println(ai + " - " + bi + " : " + count + "個");
}
}
    • good
    • 0

キーをString(ArrayAの要素)、値を「キーをString(ArrayBの要素)、値をInteger(件数)とするMap」とするMapと、2重にMapを使うのが判りやすいのではないでしょうか?



Map mapA = new HashMap();
for (int index=0; index < ArrayA.length; index++ ) {
 String keyA = ArrayA[index];
 String keyB = ArrayB[index];

 Map mapB = (Map) mapA.get(keyA);
 if (mapB == null) {
  mapB = new HashMap();
  mapA.put(keyA,mapB);
 }

 Integer count = (Integer) mapB.get(keyB);
 if (count == null) {
  count = new Integer(0);
 } else {
  count = new Integer(count.intValue() + 1);
 }
 mapB.put(keyB,count);
}

for (Iterator iteA = mapA.keySet(); iteA.hasNext(); ) {
 String keyA = (String)iterA.next();
 Map mapB = (Map) mapA.get(keyA);
 for (Iterator iterB = mapB.keySet(); iterB.hasNext(); ) {
  String keyB = (String)iterB.next();
  Integer count = (Integer) mapB.get(keyB);
  System.out.println(keyA + " - " + keyB + " : " + count + "個");
 }
}
    • good
    • 0

配列 A,B 双方を合成したものをキーとしてMapで出現数を数えるのが一番簡単だと思います。


以下サンプルソース。

String[] arrayA = { "aaa","bbb","aaa","ccc","bbb","aaa" };
String[] arrayB = { "1","1","1","2","1","2" };
// 出現数を記録するMap
Map map = new TreeMap();
for (int i = 0; i < arrayA.length; i++) {
// 配列の合成
String key = arrayA[i] + arrayB[i];
//mapにすでに組み合わせ要素が存在するなら、出現数を+1
if(map.containsKey(key)){
Integer count = (Integer)map.get(key);
count = new Integer( count.intValue() + 1 );
map.put( key, count );
}else{
// 初出の組み合わせは出現数1をセット
map.put( key, new Integer(1) );
}
}
// 出力
for (Iterator iter = map.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
Integer count = (Integer) map.get( key );
System.out.println(key + " : " + count + "個");
}

Stringなら合成は単純に連結させるだけでいいですが、それ以外のオブジェクトは合成に関して一工夫必要だと思います。
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!