0

次のタイプのArrayListがあります。

class Move
{
    int from, to;
}

fromプロパティには常に値があります。toプロパティが設定されていない場合、-1になります。私は次の配列を持っています:

int[][] history = new int[50][50];

ここで、ディメンションは、moveクラスの「from」および「to」に対応します。私の検索機能では、特定の条件に応じて、次のことを行う必要があります。

List<move> moves = board.getMoves();
for (int i = 0; i < moves.size(); i++)
    history[move.from][move.to]++;

move.toも-1になる可能性があるため、2次元配列1の次元を増やしてから、次のようにします。

history[move.from+1][move.to+]++;

また、上記の移動リストと履歴配列に基づいて、対応する履歴インデックスのカウンターに応じて移動リストを降順で並べ替える必要があります。

これは可能ですか?

4

3 に答える 3

1

Collections.sort(List、Comparator)をComparatorの実装で使用できます。これにより、必要に応じて並べ替えられます。

于 2013-03-22T09:50:54.603 に答える
0

はい、履歴配列を使用するコンパレータを作成できます。例として、intのリストを他の配列に従ってソートしますcounts

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.addAll(Arrays.asList(new Integer[]{0, 1, 2, 3, 4, 5}));
    final int[] counts = new int[] {3, 4, 1, 7, 0, 1};

    Collections.sort(list, new Comparator<Integer>() {

        @Override
        public int compare(Integer arg0, Integer arg1) {
            return counts[arg1] - counts[arg0];
        }
    });

    System.out.println(list);
}

出力:[3, 1, 0, 2, 5, 4]

あなたcompareは次のようになります:

@Override
public int compare(Move move0, Move move2) {
    return history[move1.from+1][move1.to] - history[move0.from+1][move0.to];
}
于 2013-03-22T09:56:07.563 に答える
0

これを簡単にするために、履歴をHashMapまたは個別のクラスとして設定できます。ただし、頻度に基づいて履歴を並べ替えることもできるようにしたいので、Historyクラスをお勧めします。

class Move {

   int from, to;

   @Override
   public int hashCode() {
      return from + (to * 100);
   }

   @Override
   public boolean equals(Object o) {
      return (o instanceof Move
              && ((Move) o).from == from
              && ((Move) o).to == to);
   }
}

class History extends Move implements Comparable<History> {

   int frequency;

   public History(Move m) {
      from = m.from;
      to = m.to;
      frequency = 1;
   }

   public void increment() {
      frequency += 1;
   }

   public int compareTo(History h) {
      // to be able to sort it in a TreeSet descending on frequency
      // note that it is not resorted if you change frequencies, so 
      // build the set, and then convert it to a TreeSet afterwards.
      return (frequency == h.frequency) ? 1 : (h.frequency - frequency);
   }
}

次に、HashMapを作成して履歴をすばやく入力し、それをTreeSetに変換して並べ替えます。

  List<Move> moves = board.getMoves();
  HashMap<History, History> fillTable = new HashMap<History, History>();
  for (Move m : moves) {
     History h = fillTable.get(m);
     if (h == null) {
        h = new History(m);
        fillTable.put(h, h);
     } else {
        h.increment();
     }
  }
  TreeSet<History> sorted = new TreeSet<History>(fillTable.values());
  .... ready to use
于 2013-03-22T10:50:38.073 に答える