Question

I'm creating a scoring system using a treeMap and I want to only display the top 3 results.
When the player inputs the 4th result (if it's bigger than the current smallest value) how do I make it delete the smallest value and replace it with the new value.

My code so far so sorting the scores:

 Map<Integer, String> treeMap = new TreeMap<Integer, String>(new MyCopr());
    treeMap.put(name1val, name1);
    treeMap.put(name2val, name2);
    treeMap.put(name3val, name3);
    treeMap.put(tempval, tempname);

    for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
        playername1.append("Key : " + entry.getKey() + " Value : "
                + entry.getValue() + "\n");
    }
}

class MyCopr implements Comparator<Integer> {
    @Override
    public int compare(Integer lhs, Integer rhs) {
        return rhs.compareTo(lhs);
    }
}

From here what can I do to replace the smallest value? Thanks.

Was it helpful?

Solution

I would use a set of scores (like this) -

private static int MAX_SCORES = 3;
private SortedSet<Score> scores = new TreeSet<Score>();

public Set<Score> getScores() {
  return scores;
}

public void addScore(String name, int score) {
  scores.add(new Score(name, score));
  while (scores.size() > MAX_SCORES) {
    scores.remove(scores.first());
  }
}

private class Score implements Comparable<Score> {
  private String name;
  private int score;

  private Score(String name, int score) {
    this.name = name;
    this.score = score;
  }

  public int compareTo(Score obj) {
    if (this == obj) {
      return 0;
    }
    if (this.score < obj.score) {
      return -1;
    } else if (this.score > obj.score) {
      return 1;
    }
    return name.compareTo(obj.name);
  }

  public String toString() {
    return name + " - score = " + score;
  }
}

And then use it like so ...

System.out.println(obj.getScores());
obj.addScore("Player 1", 1);
obj.addScore("Player 2", 2);
obj.addScore("Player 3", 3);
System.out.println(obj.getScores());
obj.addScore("Player 4", 4);
System.out.println(obj.getScores());

Which yields this (when I run it) -

[]
[Player 1 - score = 1, Player 2 - score = 2, Player 3 - score = 3]
[Player 2 - score = 2, Player 3 - score = 3, Player 4 - score = 4]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top