1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| package com.hmall.test.utils;
import java.util.*;
public class Top {
private Top() { throw new IllegalStateException("Utility class"); }
private static final Random random = new Random();
public static Map<Integer, User> generateRanking(List<User> scores, List<RankRule> rules, int maxRank) { scores.sort(Comparator.comparing(User::getScore).reversed());
Map<Integer, User> ranking = new TreeMap<>();
int currentRank = 1; int index = 0;
for (RankRule rule : rules) { while (currentRank <= rule.getEndRank() && index < scores.size()) { Double score = scores.get(index).getScore(); if (score >= rule.getMinScore()) { ranking.put(currentRank, scores.get(index)); currentRank++; index++; } else { while (currentRank <= rule.getEndRank()) { ranking.put(currentRank, null); currentRank++; } break; } } }
while (currentRank <= maxRank && index < scores.size()) { ranking.put(currentRank, scores.get(index)); currentRank++; index++; }
while (currentRank <= maxRank) { ranking.put(currentRank, null); currentRank++; }
return ranking; }
public static void main(String[] args) { List<RankRule> rules = Arrays.asList( new RankRule(1, 1, 40000), new RankRule(2, 3, 15000), new RankRule(4, 5, 10000), new RankRule(6, 10, 7000), new RankRule(11, 20, 5000), new RankRule(21, 30, 3000), new RankRule(31, 40, 2000), new RankRule(41, 50, 1000) ); List<User> scores = new ArrayList<>(); scores.add(new User(1L, "peter", 40000.0)); scores.add(new User(2L, "Tom", 15000.0)); scores.add(new User(3L, "Alex", 10000.0)); scores.add(new User(4L, "Tomas", 7000.0)); scores.add(new User(5L, "Jerry", 5000.0)); scores.add(new User(6L, "Tim", 3000.0)); scores.add(new User(7L, "Vivo", 2000.0)); scores.add(new User(8L, "Apple", 1000.0)); scores.add(new User(9L, "Test", 6999.0));
Map<Integer, User> ranking = generateRanking(scores, rules,50);
System.out.println(" 排名 | 名称 | 分数 "); ranking.forEach((rank, user) -> System.out.println(" " + rank + " | " + (user != null ? user.getName() : "NULL") + " | " +(user != null ? user.getScore() : "NULL")) ); } }
|