我必须对阵列中的球队进行排名"名称" (下图)以谁赢得了最多的比赛顺序。如果两支球队赢得相同数量的比赛,那么我必须比较击败他们的球队的胜利。我到目前为止的代码如下。
这里给出了完整的问题陈述: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){
}
}
答案 0 :(得分: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.
...
}
}
}
答案 1 :(得分:0)
如果你的目标是编写一个面向对象的程序,我会按如下方式构建它:
Game
课程,其中包含对参加比赛的两支球队的参考,以及每支球队的得分。 Team
类,其中包含由Map
个对象组成的游戏(Game
个对象)。如果两个团队不止一次见面,那么你需要一个“多图”,每个键允许多个值对象。Tournament
个实例(可能是由团队名称编制的Team
)和Map
个对象(另一个Game
索引的Map
个对象。你选择的关键)。在你的比较器中,你可以比较两支球队的输赢记录,如果有关系,请查看每支球队的个人比赛。