%Generates simple, connected, bipartite, 3-regular graphs uniformly at random, calculates second largest
%eigenvalue, and stores.  This done in a loop running over sizes of the graphs (nVec)
clear all; close all; pack
tic
options.disp=0;
EigenTwo=0;
SampleSize = 1000;%number of steps per walks
k=3;
nVec=[1258 1584 1995 2511 3162 3981 5011 6309 7943 10000];%n is size of HALF of the graph.
EigenTwo=zeros(SampleSize, length(nVec));
%These values have been chosen so that on a loglog plot, the data points are evenly spaced on n-axis   
for c=1:length(nVec)
   n=nVec(c);
   for w = 1:SampleSize
      A=spalloc(n,n,3*n); 
      while(max(max(A))~=1)%Continues until SIMPLE graphs is foun
         %This loop uses Bollobas' collapsing vectors method to generate
         %k-regular graphs.  For description see section 2 in N.C. Wormald's Models of Random Regular Graphs
         Pairs=mod([randperm(n*k); randperm(n*k)+n],n);
         A=spalloc(2*n,2*n,3*n);  
         for i=1:(n*k)
            m1= Pairs(1,i)+1;
            m2= Pairs(2,i)+n+1;         
            A(m1,m2) =  A(m1,m2) + 1;
            A(m2,m1) =  A(m2,m1) + 1;
         end
      end
      E=sort(eigs(A,2,'LA', options));%2 sorted Eigenvalues of A.
      if((E(1)==E(2))==0)%true if A represents a CONNECTED graph.
         EigenTwo(w,c)=E(1);
      else
         w=w-1;
      end
   end
   save Mother3 EigenTwo SampleSize nVec
end
RunTime=toc;
save Mother3 EigenTwo n RunTime nVec