public void FillDivisions() { var latitudalTeams = Teams.OrderBy(team => team.City.Latitude).ToList(); PutTeamsInTheCorners(latitudalTeams); while (!Enumerable.SequenceEqual(Divisions.Select(division => division.Teams.Count).ToArray(), _maxDivisionTeamCounts)) { (Team team, Division division)bestPair = (null, null); var furthestNeighbour = double.MinValue; for (var i = 0; i < latitudalTeams.Count; i++) { var team = latitudalTeams[i]; (Team team, Division division)pair = (null, null); if (Divisions.Any(division => division.Teams.Contains(team))) { continue; } var closestDistance = double.MaxValue; for (var j = 0; j < Divisions.Count; j++) { var division = Divisions[j]; var divisionHasRoom = division.Teams.Count < _maxDivisionTeamCounts[j]; var squaredDistance = division.SquaredDistanceTo(team.City); if (divisionHasRoom && squaredDistance < closestDistance) { closestDistance = squaredDistance; pair = (team, division); } } if (closestDistance > furthestNeighbour) { furthestNeighbour = closestDistance; bestPair = pair; } } bestPair.division.Teams.Add(bestPair.team); Divisions = Divisions.OrderBy(division => division.Teams.Count).ToList(); } }