diff --git a/src/main/java/de/tims/leaderboard/Leaderboard.java b/src/main/java/de/tims/leaderboard/Leaderboard.java index fd4d8f7..c7fd4c8 100644 --- a/src/main/java/de/tims/leaderboard/Leaderboard.java +++ b/src/main/java/de/tims/leaderboard/Leaderboard.java @@ -17,8 +17,25 @@ public class Leaderboard { public Player[] getTop10Players() { Player[] top10Players = new Player[NUM_PLAYERS_ON_LEADERBOARD]; - for (int i = 0; i < allPlayers.size() && i < NUM_PLAYERS_ON_LEADERBOARD; i++) { - top10Players[i] = allPlayers.get(i); + for (Player actualPlayer : allPlayers) { + for (int i = 0; i < NUM_PLAYERS_ON_LEADERBOARD; i++) { + if (top10Players[i] == null) { + top10Players[i] = actualPlayer; + + break; + } else if (actualPlayer.getPoints() > top10Players[i].getPoints()) { + Player playerToInsert = actualPlayer; + Player tmp; + + for (int j = i; j < NUM_PLAYERS_ON_LEADERBOARD; j++) { + tmp = top10Players[j]; + top10Players[j] = playerToInsert; + playerToInsert = tmp; + } + + break; + } + } } return top10Players; diff --git a/src/test/java/de/tims/leaderboard/LeaderboardTest.java b/src/test/java/de/tims/leaderboard/LeaderboardTest.java index 899fa90..1705457 100644 --- a/src/test/java/de/tims/leaderboard/LeaderboardTest.java +++ b/src/test/java/de/tims/leaderboard/LeaderboardTest.java @@ -40,7 +40,22 @@ class LeaderboardTest { "TestPlayer", new Player[] {new Player("Eins", 140), new Player("Zwei", 130), new Player("Drei", 120), new Player("Vier", 110), new Player("Fuenf", 100), new Player("Sechs", 90), new Player("Sieben", 80), new Player("Acht", 70), - new Player("Neun", 60), new Player("Zehn", 50)})); + new Player("Neun", 60), new Player("Zehn", 50)}), + Arguments.of("UnsortedListWithLessThan10ElementsReturnsElementsSortedByPoints", + List.of(new Player("Eins", 20), new Player("Zwei", 30), new Player("Drei", 10), new Player("Vier", 60), + new Player("Fuenf", 50), new Player("Sechs", 90)), + "TestPlayer", + new Player[] {new Player("Sechs", 90), new Player("Vier", 60), new Player("Fuenf", 50), new Player("Zwei", 30), + new Player("Eins", 20), new Player("Drei", 10), null, null, null, null}), + Arguments.of("UnsortedListWithMoreThan10ElementsReturns10ElementsWithMostPointsSortedByPoints", + List.of(new Player("Eins", 0), new Player("Zwei", 130), new Player("Drei", 20), new Player("Vier", 10), + new Player("Fuenf", 20), new Player("Sechs", 70), new Player("Sieben", 60), new Player("Acht", 20), + new Player("Neun", 60), new Player("Zehn", 50), new Player("Elf", 90), new Player("Zwoelf", 20), + new Player("Dreizehn", 40), new Player("Vierzehn", 80)), + "TestPlayer", + new Player[] {new Player("Zwei", 130), new Player("Elf", 90), new Player("Vierzehn", 80), new Player("Sechs", 70), + new Player("Sieben", 60), new Player("Neun", 60), new Player("Zehn", 50), new Player("Dreizehn", 40), + new Player("Drei", 20), new Player("Fuenf", 20)})); } }