Skip to content

Instantly share code, notes, and snippets.

@v1vendi
Created March 17, 2020 16:37
Show Gist options
  • Save v1vendi/3aa821f5f9a62a8e07f65ed4d17196f2 to your computer and use it in GitHub Desktop.
Save v1vendi/3aa821f5f9a62a8e07f65ed4d17196f2 to your computer and use it in GitHub Desktop.
matchmaker
from random import randrange
from ortools.algorithms import pywrapknapsack_solver
PLAYERS_COUNT = 6
PLAYERS_IN_MATCH = 6
regions = {
'eu': 0,
'na': 1,
'asia': 2,
}
regions_list = [0, 1, 2]
class Player:
def __init__(self, id, order, region, pings):
self.id = id
self.pings = pings
# example
# { id: 1, order: 1, region: 0, pings: [40, 100, 150] }
# { id: 2, order: 2, region: 2, pings: [140, 20, 150] }
def get_player(id):
player_region = randrange(0, 3)
pings = [
randrange(0, PLAYERS_COUNT) if player_region == region
else randrange(150, 250)
for region in regions_list
]
return Player(id, id, player_region, pings)
players = [
get_player(i) for i in range(PLAYERS_COUNT)
]
data = [
(p.order, p.pings[0], p.pings[1], p.pings[2]) for p in players
]
num_matches = int(PLAYERS_COUNT / PLAYERS_IN_MATCH)
matches = list(range(num_matches))
model = cp_model.CpModel()
x = {}
for player in players:
for match in matches:
for region in regions_list:
name = f'x_p{player}m{match}r{region}'
x[player, match, region] = model.NewBoolVar(name)
# exactly PLAYERS_IN_MATCH players in every match
for match in matches:
model.Add(
sum(
x[p, match, r] for r in regions_list for p in players
) == PLAYERS_IN_MATCH
)
# exactly one player per match
for player in players:
model.Add(
sum(
x[player, m, r] for r in regions_list for m in matches
) <= 1
)
model.Minimize(
sum(order for (order, ping0, ping1, ping2) in x)
)
@v1vendi
Copy link
Author

v1vendi commented Mar 17, 2020

from ortools.sat.python import cp_model

model = cp_model.CpModel()

x = model.NewIntVar(-1, 2, 'x')
y = model.NewIntVar(-1, 2, 'y')

model.Maximize(sum([x, y]))
model.Add(
    list([x, y]).count(x) == 1
)

solver = cp_model.CpSolver()

def run_stupid():
    status = solver.Solve(model)
    if status == cp_model.INFEASIBLE:
        print('not solved')
        return

    print(x)
    print(y)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment