Search code examples
javaalgorithmexceptionfixtures

My fixture algorithm throws exception when there are odd team numbers


My fixture generator algorithm throws java.lang.IndexOutOfBoundsException when the team list count is odd. I'm sending 21 sized team list and gives this exception. And throws the same exception even when it's 17, 19, 23. Here is the exception:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xelorium.soccerleaguetable, PID: 1189
java.lang.IndexOutOfBoundsException: Index: 21, Size: 21
    at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
    at java.util.LinkedList.get(LinkedList.java:476)
    at com.xelorium.soccerleaguetable.FixtureGenerator.getFixtures(FixtureGenerator.java:34)

FixtureGenerator.java:

public class FixtureGenerator<T extends Object> {

public List<List<MatchModel<T>>> getFixtures(List<T> teams, boolean includeReverseFixtures) {

    int numberOfTeams = teams.size();

    boolean ghost = false;
    if (numberOfTeams % 2 != 0) {
        numberOfTeams++;
        ghost = true;
    }

    int totalRounds = numberOfTeams - 1;
    int matchesPerRound = numberOfTeams / 2;
    List<List<MatchModel<T>>> rounds = new LinkedList<List<MatchModel<T>>>();

    for (int round = 0; round < totalRounds; round++) {
        List<MatchModel<T>> fixtures = new LinkedList<MatchModel<T>>();
        for (int match = 0; match < matchesPerRound; match++) {
            int home = (round + match) % (numberOfTeams - 1);
            int away = (numberOfTeams - 1 - match + round) % (numberOfTeams - 1);

            if (match == 0) {
                away = numberOfTeams - 1;
            }
            //Here where it throws the exception
            fixtures.add(new MatchModel<T>(teams.get(home), teams.get(away)));
        }
        rounds.add(fixtures);
    }

Solution

  • In here, you are increasing team count and trying to match a team that even doesn't exist.

    if (numberOfTeams % 2 != 0) {
        numberOfTeams++;
        ghost = true;
    }
    

    Let's assume you have 21 teams, last index in list of teams is 20 (index begins from zero). But "numberOfTeams" is 22. In this if block "away" will be 22 - 1 = 21 and then try to reach 21st indexed team in list. But this team doesn't exist.

    if (match == 0) {
        away = numberOfTeams - 1;
    }
    
    //Here where it throws the exception
    fixtures.add(new MatchModel<T>(teams.get(home), teams.get(away)));
    

    As a solution you can add empty team to list for bypass when team count is odd.