我有一个如下类型的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,我是否应该将二维数组的维度增加1,然后执行以下操作:
history[move.from+1][move.to+]++;
另外,基于上述的移动列表和历史数组,我需要根据相应历史索引的计数器以降序对移动列表进行排序。
这是可能的吗?
回答:
你可以将历史记录设置为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) { // 能够根据频率以降序在TreeSet中排序它 // 请注意,如果你更改频率,它不会重新排序,所以 // 构建集合,然后之后将其转换为TreeSet。 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()); .... 准备使用