Tuesday, October 28, 2014

generate a tournament schedule

In a tournament with N teams, where in one team can play only one match per day, develop an algo which schedules the matches in the tournament.

Each team shall play with the other team once.


N need to be power of 2.

 This is a popular interview problem that has been asked by MS, Google, Bloomberg.

//idea from careercup
void tourna(vector<int>& myinput,vector<vector<int>>&ret){
    int n=myinput.size();
//i is the size of group. a member  inside one group do play with that of the neighbor group.
    for(int i=1;i<=n/2;i<<=1){
        for(int j=0;j<i;j++){//j is the alignment number
            vector<int> com;
            for(int start=0;start<n;start+=2*i){//everytime process two neighbor groups
                int rstart=start+i;
                for (int k=0;k<i;k++)//pair players in the two neighbor groups
                {
                    com.push_back(myinput[start+k]);
                    com.push_back(myinput[rstart+(j+k)%i]);
                }
              
            }
            ret.push_back(com);
        }
    }
}


//idea from stackoverflow



for example: A....H

If you start with this setup (teams in the upper row playing against the corresponding lower team):
A B C D
H G F E
you set one team as fixed (e.g., A) and rotate the rest (e.g., clockwise):
A H B C     A G H B     A F G H     A E F G    A D E F    A C D E  
G F E D     F E D C     E D C B     D C B H    C B H G    B H G F
Voilà, 7 rounds, and every team plays each other team.

void tourna2(vector<int>& myinput,vector<vector<int>>&ret){
    int n=myinput.size();
    for (int i=0;i<n-1;i++){//i is the alignment number
        vector<int> com;
        com.push_back(myinput[0]);
        com.push_back(myinput[1+(n-2+i)%(n-1)]);
        int step=0;
        while(step<(n-2)/2){
            int left=1+(i+step)%(n-1);
            int right=1+(n-3+i-step)%(n-1);
            com.push_back(myinput[left]);
            com.push_back(myinput[right]);
            step++;

        }
        ret.push_back(com);
    }
}

No comments:

Post a Comment