Skip to content

Instantly share code, notes, and snippets.

@lucnat
Created February 17, 2019 21:02
Show Gist options
  • Save lucnat/c54b3b9deb163dc34b897710bc6c30b8 to your computer and use it in GitHub Desktop.
Save lucnat/c54b3b9deb163dc34b897710bc6c30b8 to your computer and use it in GitHub Desktop.
Select teams in competition with random drawing and non-trivial matching
# A script to find plays in a group of N people where in one game k players plays
# To be executed in python 3
# Written by Luca Naterop and Philippe frei
# January, 2019
from itertools import combinations
import numpy as np
from random import randint
from operator import itemgetter
def fact(n, total=1):
while True:
if n == 1:
return total
n, total = n - 1, total * n
def get_all_combinations(N,k):
combs = combinations(np.linspace(1,N,N), k)
amount_combinations = fact(N)/(fact(k)*fact(N-k))
M = np.zeros([amount_combinations,k])
i = 0
for combination in combs:
combination_as_array = np.asarray(combination)
M[i,:] = combination_as_array
i = i+1
return M
def games_match(game1,game2):
amount_shared = 0
for i in range(0,len(game1)):
for j in range(i,len(game2)):
if game1[i] == game2[j]:
amount_shared = amount_shared + 1
if amount_shared >= 2:
return True
return False
def want_this_game(M,game,amount_for_each):
# returns true if we want that new game otherwise false
# kommt spieler mit am wenigsten vor im kandidat?
index_of_player_with_least = min(enumerate(amount_for_each), key=itemgetter(1))[0]
player_with_least = index_of_player_with_least + 1
if not (player_with_least in game):
return False
for i in range(0,len(M)):
if games_match(game, M[i]):
return False
return True
def amount_games_for_each_player(games,N):
want = False
amount_games = np.zeros([N+1])
for game in games:
for player in game:
amount_games[int(player-1)] += 1
return amount_games
N = 8
k = 3
tries = 1000
j = 0
M = get_all_combinations(N,k)
games = np.zeros([10,k])
for i in range(0,tries):
random_index = randint(0,len(M)-1)
next_candidate = M[random_index,:]
amount_for_each = amount_games_for_each_player(games,N)
if(want_this_game(games,next_candidate,amount_for_each)):
games[j,:] = next_candidate
j += 1
amount_for_each = amount_games_for_each_player(games,N)
print(games)
print(amount_for_each)
print('amount games', j)
print('----------------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment