% make a random regular graph of degree p

function G=make_rand_reg_graph(n,p)
G=sparse(n,n);
degree=zeros(1,n);
for k=1:n
% find how many vertices are already
% adjacent to k
count=0;
while degree(k)<p
count=count+1;
j=randi(n);
if (j~=k)&(degree(j)<p)&(G(j,k)==0)
G(j,k)=1;
G(k,j)=1;
degree(j)=degree(j)+1;
degree(k)=degree(k)+1;
end % if
% this is to handle a special case
% when all vertices have degree p
% except one
if count>n^2
j=randi(n);
adj=find(G(j,:)>0);
if (j~=k)&(length(adj)>1)
m=adj(1);
G(j,m)=0;
G(j,k)=1;
G(k,j)=1;
G(k,m)=1;
G(m,k)=1;
degree(k)=degree(k)+2;
end % if
end % if
end % while deg
end % for k
figure
spy(G)
return