2013-03-22 70 views
0

上我有以下类型的ArrayList列表。如果未设置,则to属性将为-1。我有以下数组:Java的排序基于另一个列表

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

其中尺寸对应于移动类的'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+]++; 

此外,根据上述移动列表和历史数组,我需要根据相应历史索引的计数器以降序对移动列表进行排序。

这可能吗?

回答

0

您可以设置历史一个HashMap或单独的类来简化这个过程。但是,因为你也希望能够进行排序基于频率的历史,我会建议一个历史课:

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 
0

是的,你可以让你的比较器使用历史数组。作为一个例子,我根据其他数组counts对我的int列表进行排序。

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]; 
}