Round-robin tournament schedule: Difference between revisions
Content added Content deleted
(Add Scala implementation) |
(Add Swift implementation) |
||
Line 1,854: | Line 1,854: | ||
Round 4: ( 1 vs 3 ) ( 4 vs 2 ) ( 5 vs 0 ) |
Round 4: ( 1 vs 3 ) ( 4 vs 2 ) ( 5 vs 0 ) |
||
Round 5: ( 1 vs 2 ) ( 3 vs 0 ) ( 4 vs 5 ) |
Round 5: ( 1 vs 2 ) ( 3 vs 0 ) ( 4 vs 5 ) |
||
</pre> |
|||
=={{header|Swift}}== |
|||
{{trans|Java}} |
|||
<syntaxhighlight lang="Swift"> |
|||
import Foundation |
|||
func roundRobin(teamCount: Int) { |
|||
if teamCount < 2 { |
|||
fatalError("Number of teams must be greater than 2: \(teamCount)") |
|||
} |
|||
var rotatingList = Array(2...teamCount) |
|||
var effectiveTeamCount = teamCount |
|||
if teamCount % 2 == 1 { |
|||
rotatingList.append(0) // Adding a 'bye' in case of odd number of teams |
|||
effectiveTeamCount += 1 |
|||
} |
|||
for round in 1..<effectiveTeamCount { |
|||
print("Round \(round):", terminator: "") |
|||
let fixedList = [1] + rotatingList |
|||
for i in 0..<(effectiveTeamCount / 2) { |
|||
print(" (\(fixedList[i]) vs \(fixedList[effectiveTeamCount - 1 - i]))", terminator: "") |
|||
} |
|||
print() |
|||
rotatingList.rotate(shift: 1) |
|||
} |
|||
} |
|||
extension Array { |
|||
mutating func rotate(shift: Int) { |
|||
let index = shift >= 0 ? |
|||
self.index(self.startIndex, offsetBy: self.count - shift, limitedBy: self.endIndex) : |
|||
self.index(self.startIndex, offsetBy: -shift, limitedBy: self.endIndex) |
|||
guard let validIndex = index else { return } |
|||
self = Array(self[validIndex..<self.endIndex] + self[self.startIndex..<validIndex]) |
|||
} |
|||
} |
|||
// Example usage |
|||
print("Round robin for 12 players:") |
|||
roundRobin(teamCount: 12) |
|||
print("\nRound robin for 5 players, 0 denotes a bye:") |
|||
roundRobin(teamCount: 5) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Round robin for 12 players: |
|||
Round 1: (1 vs 12) (2 vs 11) (3 vs 10) (4 vs 9) (5 vs 8) (6 vs 7) |
|||
Round 2: (1 vs 11) (12 vs 10) (2 vs 9) (3 vs 8) (4 vs 7) (5 vs 6) |
|||
Round 3: (1 vs 10) (11 vs 9) (12 vs 8) (2 vs 7) (3 vs 6) (4 vs 5) |
|||
Round 4: (1 vs 9) (10 vs 8) (11 vs 7) (12 vs 6) (2 vs 5) (3 vs 4) |
|||
Round 5: (1 vs 8) (9 vs 7) (10 vs 6) (11 vs 5) (12 vs 4) (2 vs 3) |
|||
Round 6: (1 vs 7) (8 vs 6) (9 vs 5) (10 vs 4) (11 vs 3) (12 vs 2) |
|||
Round 7: (1 vs 6) (7 vs 5) (8 vs 4) (9 vs 3) (10 vs 2) (11 vs 12) |
|||
Round 8: (1 vs 5) (6 vs 4) (7 vs 3) (8 vs 2) (9 vs 12) (10 vs 11) |
|||
Round 9: (1 vs 4) (5 vs 3) (6 vs 2) (7 vs 12) (8 vs 11) (9 vs 10) |
|||
Round 10: (1 vs 3) (4 vs 2) (5 vs 12) (6 vs 11) (7 vs 10) (8 vs 9) |
|||
Round 11: (1 vs 2) (3 vs 12) (4 vs 11) (5 vs 10) (6 vs 9) (7 vs 8) |
|||
Round robin for 5 players, 0 denotes a bye: |
|||
Round 1: (1 vs 0) (2 vs 5) (3 vs 4) |
|||
Round 2: (1 vs 5) (0 vs 4) (2 vs 3) |
|||
Round 3: (1 vs 4) (5 vs 3) (0 vs 2) |
|||
Round 4: (1 vs 3) (4 vs 2) (5 vs 0) |
|||
Round 5: (1 vs 2) (3 vs 0) (4 vs 5) |
|||
</pre> |
</pre> |