clc
clear all
n=26;
STOPTRIG=0;
cst=1;
dst=1;

    exru1=[];exru2=[];exru3=[];
  exru2=[1 15; 5 17; 6 11; 18 19; 25 26];
    exru3=[exru2(:,2) exru2(:,1)];
    exru=[exru1; exru2; exru3];
    


    compid=[];
    compid(1,1)=1;
    for t=1:7
        compid(2,t)=3*t;
        compid(1,t+1)=3*t+1;
    end
    compid(2,size(compid,2))=n;
    for t=1:size(compid,2)
        classx(compid(1,t):compid(2,t))=t;
    end
compid(numel(compid))=26
while STOPTRIG==0
    for t=1:n;
         EXC{t}=exru(find(exru(:,1)==t),2);
    end

    rounds=[];
    rounds(:,1)=randperm(n);
    rounds(:,2)=randperm(n);
    rounds(:,3)=randperm(n);
    %exru1=[1:n;1:n]';
  

    for t1=1:size(rounds,2)
        for t2=1:n;
            idx=find(rounds(:,t1)==t2);
            curround=classx(idx);
            curex=EXC{t2};
            plt=rounds(compid(1,curround):(compid(2,curround)),t1);
            if length(plt)==5
                valp12=find(plt==t2);

                if valp12==1
                    plt([1 2 5])=[];
                elseif valp12==2
                    plt([1 2 3])=[];
                elseif valp12==3
                    plt([2 3 4])=[];
                elseif valp12==4
                    plt([4 2 5])=[];
                elseif valp12==5
                    plt([1 4 5])=[];
                end
            else
                plt(find(plt==t2))=[];
            end
            pl2=[];
%             for t3=1:length(plt);
%                 if ~isempty(find(plt(t3)==exru(:,1), 1))
%                     pl2=[pl2 exru(find(plt(t3)==exru(:,1)),2)];
%                 end
%             end
                              
                
                
            EXC{t2}=[curex; plt; pl2'];
        end
    end
    maxw(1:n)=0;
    for t=1:n
        maxw(t)=length(find(diff(sort(EXC{t}))==0));
    end
    xs(cst)=sum(maxw);
    if    sum(maxw)==0
        STOPTRIG=1;
    end
    
    if sum(maxw)<7
%         disp('hit')
        if sum(maxw)==min(xs)
%             disp('hit2')
            BIN{dst}=rounds;
            dst=dst+1;
        end
    end
    cst=cst+1;
    
    if mod(cst,100)==0
        disp(num2str(min(xs)))
%         hist(xs,max(xs)-min(xs))
    end
end
disp('done')
%%

%save('rounds','rounds')
load names
load rounds
C{size(rounds,1),size(rounds,2)+1}=[];
for t1=1:(size(C,1))
            C{t1,1}=classx(t1);
    for t2=1:(size(C,2)-1)
        curteam=rounds(t1,t2);
        C{t1,t2+1}=names{curteam,2};

    end
end

        
xlswrite('randomizationresult29.xls',[C])