2013-03-22 45 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]; 
}