gpt4 book ai didi

java - Java 分数排序

转载 作者:太空宇宙 更新时间:2023-11-04 14:45:17 24 4
gpt4 key购买 nike

几天前我从这里得到了一些方法来帮助我提高分数。基本上,当游戏结束时,我希望获得得分最高的顶尖玩家,并将他们放入第 2 轮,因此,如果有 8 名玩家,我希望将他们分成两半,上半部分是得分最高的玩家,下面的方法工作正常,但如果游戏中有 3 名玩家,则只会取前 1 名,而不是 2 名,游戏中 5 名玩家,则只会取前 2 名,而不是 3 名。

如何获得得分最高的上半区,如果有 2 名玩家得分相同,那么他们都会晋级。例如:

Player 1 = 1;
Player 2 = 10;
Player 3 = 10;
Player 4 = 25;

下面的方法将返回玩家 4 和 3,但玩家 2 也有 10 分,所以他也应该在其中。

public static Map<String, Integer> getTopHalf(Map<String, Integer> map){
Map<String, Integer> sorted = sortByComparator(map);
Map<String, Integer> out = new HashMap<String, Integer>();
Iterator<Entry<String,Integer>> it = sorted.entrySet().iterator();
for(int i = 0; i<map.size()/2; i++){
Entry<String, Integer> e = it.next();
out.put(e.getKey(), e.getValue());
}
return out;
}

private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap){
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>(){
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2){
return o2.getValue().compareTo(o1.getValue());

}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}

public static void printMap(Map<String, Integer> map){
for (Entry<String, Integer> entry : map.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}

为了测试我使用这个:

Map<String, Integer> unsortMap = new HashMap<String, Integer>();
unsortMap.put("B", 89);
unsortMap.put("A", 45);
unsortMap.put("f", 43);
unsortMap.put("j", 47);
unsortMap.put("h", 41);
System.out.println("After sorting descindeng order and deleting half......");
Map<String, Integer> half = getTopHalf(unsortMap);
printMap(half);

最佳答案

List<Integer> achievedPoints = new ArrayList<>(allPlayers.values());
Collections.sort(achievedPoints); /*- from few points to many points */
int requiredScore = achievedPoints.get(achievedPoints.size());

Map<String, Integer> playersInNextRound = new HashMap<>();
for (Map.Entry<String, Integer> player : allPlayers.entrySet()) {
if (player.getValue() >= requiredScore) {
playersInNextRound.put(player.getKey(), player.getValue());
}
}

关于java - Java 分数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24467137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com