javaandroid

Issue with ranking Players in app in Java


I am trying to Rank players based on the number of wins they have.

Below is my code for the player results model:

public class PlayerResults implements Comparable<PlayerResults> {
    
    private String rank = "0";
    private String userName;
    private int wins;
    ...

    public int getPlayerWins() {

        return wins;                                 

    }

    @Override
    public int compareTo(PickemResults another) {

        return wins.compareTo(another.wins);

    }

}

and below is the ranking for the players algo:

public static void standardRanking(List<PlayerResults> playerList) {

    for (int i = 0, rank = 0, group = 0; i < playerList.size(); i++) {

        if (group < playerList.size() && i == playerList.get(group).getPlayerWins()) {

            rank = i + 1;
            group++;

        }

        System.out.printf("%d %s%n", rank, playerList.get(i).getPlayerWins(),playerList.get(i).getPlayerUsername());

    }

}

This is the sort done prior to the ranking:

playerList.sort(Comparator.comparing(PlayerResults::getPlayerWins, Comparator.reverseOrder()));

Expected Result

1 44 Solomon
2 42 Jason
2 42 Errol
4 41 Garry
4 41 Bernard
4 41 Barry
7 39 Stephen

Can anyone see what I'm missing here!?


Solution

  • Start by sorting the playerList by wins, in descending order.

    Assign i to the rank, whenever the value decreases.

    Here is an example.

    public static void standardRanking(List<PlayerResults> pr) {
        pr.sort(Comparator.comparingInt(x -> x.wins));
        Collections.reverse(pr);
        int i = 1, r = 1, pw = pr.get(0).wins;
        for (PlayerResults p : pr) {
            if (pw > p.wins) {
                r = i;
                pw = p.wins;
            }
            i++;
            System.out.printf("%d %d %s%n", r, p.wins, p.userName);
        }
    }
    

    Output

    1 44 Solomon
    2 42 Errol
    2 42 Jason
    4 41 Barry
    4 41 Bernard
    4 41 Garry
    7 39 Stephen