I'm trying to write a script to randomise a round-robin schedule for a tournament.
The constraints are:
- 8 Teams
- Teams face each other twice, once at home and once away
- 14 weeks, one game for each team per week
My code works fine in theory, but when it's generated it sometimes freezes on certain weeks when there are only two teams left for that week, and both possible games have already been played. I use a numpy array to check which matchups have been played.
At the moment my code looks like this:
import random
import numpy
regular_season_games = 14
regular_season_week = 0
checker = numpy.full((8,8), 0)
for x in range (0,8):
checker[x][x] = 1
teams_left = list(range(8))
print ("Week " + str(regular_season_week+1))
while (regular_season_week < regular_season_games):
game_set = False
get_away_team = False
while get_away_team == False:
Team_A = random.choice(teams_left)
if 0 in checker[:,Team_A]:
for x in range (0,8):
if checker[x][Team_A] == 0 and x in teams_left:
teams_left.remove(Team_A)
get_away_team = True
break
while game_set == False:
Team_B = random.choice(teams_left)
if checker[Team_B][Team_A] == 0:
teams_left.remove(Team_B)
print(str(Team_A) + " vs " + str(Team_B))
checker[Team_B][Team_A] = 1
game_set = True
if not teams_left:
print ("Week " + str(regular_season_week+2))
teams_left = list(range(8))
regular_season_week = regular_season_week + 1
I've used an adaptation of the scheduling algorithm from here to achieve this. Basically, we generate a list of the teams -
list(range(8))
- and choose as our initial matchup0 vs 4, 1 vs 5, 2 vs 6, 3 vs 7
. We then rotate the list, excluding the first element, and choose as our next matchup0 vs 3, 7 vs 4, 1 vs 5, 2 vs 6
. We continue on in the following way until we have every pairing.I've added a handler for home & away matches - if a pairing has already been played, we play the opposite home/away pairing. Below is the code, including a function to check if a list of games is valid, and a sample output.
Code:
Sample Output: