2012-08-03 80 views
3

我必須按照誰贏得最多遊戲的順序來排列陣列「名稱」(下面)中的球隊。如果兩支球隊贏得相同數量的比賽,那麼我必須比較擊敗他們的球隊的勝利。我到目前爲止的代碼如下。如何遞歸使用比較器?

完整的問題陳述在這裏給出:http://www.cs.duke.edu/csed/newapt/tournamentrank.html

所以我想用遞歸比較。比較器如何訪問原始數據?我嘗試創建一個Team類,它爲團隊打敗了同一類的變量,但這顯然不起作用。困在這裏,請幫忙!

public class TournamentRanker implements Comparator<String>{ 

public class Team { 
    String name; 
    Integer wins; 
    Team beatEm; 
} 

     //HOW TO make maps visible to comparator? 
     public String[] rankTeams(String[] names, String[] lostTo) { 

      //map all teams to number of wins & to team that beat them 
      ArrayList<String> teams = new ArrayList<String>(); 
      HashMap<String, Integer> Teamwins = new HashMap<String, Integer>(); 
       HashMap<String, String> Whobeat = new HashMap<String, String>(); 

      for(int x=0; x<names.length; x++) 
      { 
       if(!teams.contains(names[x])) 
        teams.add(names[x]); 

       if(!Teamwins.containsKey(names[x])) 
        Teamwins.put(names[x], 0); 
       Whobeat.put(names[x], lostTo[x]); 
       if(!Teamwins.containsKey(lostTo[x]) && !lostTo[x].equals("")) 
        Teamwins.put(lostTo[x], 0); 
       if(!lostTo[x].equals("")) 
        Teamwins.put(lostTo[x], (Teamwins.get(lostTo[x])+1)); 
      } 
      for(String s: names) 
      { 
       Integer wins = Teamwins.get(s); 
       Team beatEm = new Team(Whobeat.get(s), Teamwins.get(Whobeat.get(s)), ????) 
      } 
      //SORT list & turn into ARRAY 
      Comparator<String> comp = new TournamentRanker(); 
      Collections.sort(teams, comp); 
      String [] sortedTeams = new String[teams.size()]; 
      return teams.toArray(sortedTeams); 



     } 
     //NEED to use compareTo***?? OTHER strategy???? 

     //USE COMPARTOR - how to access all the data? 

     public int compare(String team1, String team2){ 


     }  

} 

回答

1

爲了使地圖可見,我建議把Comparator一個內部類的TournamentRanker,並使TournamentRanker類的地圖實例成員如下:

public class TournamentRanker { 

    public class Team { 
     String name; 
     Integer wins; 
     Team beatEm; 
    } 

    // Map all teams to number of wins & to team that beat them 
    ArrayList<String> teams = new ArrayList<String>(); 
    HashMap<String, Integer> Teamwins = new HashMap<String, Integer>(); 
    HashMap<String, String> Whobeat = new HashMap<String, String>(); 

    public String[] rankTeams(String[] names, String[] lostTo) { 
     TeamComparator teamComparator = new TeamComparator(); 

     // Use teamComparator to sort teams. 
     ... 
    } 

    private TeamComparator implements Comparator<String> { 
     public int compare(String team1, String team2){ 
      // This function can now access the maps. 

      // Perform the comparison here. 
      ... 
     } 
    } 
} 
0

如果你的目標是寫一個面向對象的程序,我會按如下方式構造它:

  1. A Game類包含兩個參與遊戲的團隊e,以及每個球隊的得分。
  2. A Team類別包含Map所玩遊戲(Game對象),由對方隊伍ID索引。如果兩個團隊會見不止一次,則需要一個允許每個鍵上有多個值對象的「多圖」。
  3. 一個包含兩個Team實例Tournament對象(可能是隊名索引的Map)和Game對象(另Map由您選擇的一些獨特的密鑰索引)。

在你的比較中,你可以比較兩支球隊的輸贏記錄,以及在關係情況下查看每支球隊的個人比賽。