M家面试

Given 4 teams and 3 gamedays, create an algorithm such that each team plays another team every gameday and by the end of the 3 game days each team should have played one game with every other team.

Alg 1:

Round-robin tournament Scheduling algorithm:

If there are n teams, then there will be n(n-1)/2 games. If n is even, then in (n-1) rounds, n/2 games can be run concurrently. 

Standard algorithm can be represented in a table. Imagine the teams as a two-rows table, each column represents a game match.

Round 1:

1   2 3 4 5

10 9 8 7 6

Round 2: switch the competitors in the first column or last column, and then rotate the competitors in clockwise

1 10 2 3 4

9 8   7 6 5

Repeat this until it almost back at the initial position:

1 3   4 5 6

2 10 9 8 7

Code:

public List createTournament(int teams, int rounds) {
List games;
int num = teams/2;

//assign the team into a array
for (int i =0; i
int cycle[i] = i+1;
}

for (int d=0; d
//rotate in clockwise
int switch = cycle[0];
for (int i=0; i
int pr = cycle[i+1];
cycle[i+1] = switch;
switch = pr;
}
cycle[0] = switch;

for (int i=0; i
Pair pair = new Pair(cycle[i],cycle[teams-i-1]);
games.add(pair);
}
//switch the competitors in the first column 
cycle[0] = cycle[teams-1]
cycle[teams-1] = switch;
}
return games;
}


 

你可能感兴趣的:(M家面试)