S = randperm(500000);
A1 = zeros(50,100,100);
A1(S(1:498000))=0;
A1(S(498001:500000))=1;
B1=zeros(50,100,100)+2;
C=[A1;B1];
V=zeros(100,100,100);
S=randperm(1000000);
V(S(1:166667))=1;
V(S(166668:333334))=2;
V(S(333335:500000))=3;
V(S(500001:666667))=4;
V(S(666668:833333))=5;
V(S(833334:1000000))=6;
R9=zeros(2,104,104);
R10=R9+2;
C=[R9;C;R10];
C1=[R1,R5,R2];
C2=[R8,C,R6];
C3=[R3,R7,R4];
trans=zeros(100,104,104);
trans(:,:,1:2)=C1;
trans(:,:,3:end-2)=C2;
trans(:,:,end-1:end)=C3;
C=trans;
for i=3:102
for j=3:102
for k=3:102
if (C(i,j,k)==1&&V(i,j,k)==1)
if C(i-1,j,k)==1||(C(i-2,j,k)==1&&V(i-2,j,k)==2)...
||(C(i-1,j-1,k)==1&&V(i-1,j-1,k)==4)||(C(i-1,j+1,k)==1&&V(i-1,j+1,k)==3)...
||(C(i-1,j,k-1)==1&&V(i-1,j,k-1)==6)||(C(i-1,j,k+1)==1&&V(i-1,j,k+1)==5)
D(i,j,k)=1;
else D(i-1,j,k)=1;
end
elseif (C(i,j,k)==1&&V(i,j,k)==3)
if C(i,j-1,k)==1||(C(i-1,j-1,k)==1&&V(i-1,j-1,k)==2)...
||(C(i+1,j-1,k)==1&&V(i+1,j-1,k)==1)||(C(i,j-2,k)==1&&V(i,j-2,k)==4)...
||(C(i,j-1,k-1)==1&&V(i,j-1,k-1)==6)||(C(i,j-1,k+1)==1&&V(i,j-1,k+1)==5)
D(i,j,k)=1;
else D(i,j-1,k)=1;
end
elseif (C(i,j,k)==1&&V(i,j,k)==4)
if C(i,j+1,k)==1||(C(i-1,j+1,k)==1&&V(i-1,j+1,k)==2)...
||(C(i+1,j+1,k)==1&&V(i+1,j+1,k)==1)||(C(i,j+2,k)==1&&V(i,j+2,k)==3)...
||(C(i,j+1,k-1)==1&&V(i,j+1,k-1)==6)||(C(i,j+1,k+1)==1&&V(i,j+1,k+1)==5)
D(i,j,k)=1;
else D(i,j+1,k)=1;
end
elseif (C(i,j,k)==1&&V(i,j,k)==5)
if C(i,j,k-1)==1||(C(i-1,j,k-1)==1&&V(i-1,j,k-1)==2)...
||(C(i+1,j,k-1)==1&&V(i+1,j,k-1)==1)||(C(i,j-1,k-1)==1&&V(i,j-1,k-1)==4)...
||(C(i,j+1,k-1)==1&&V(i,j+1,k-1)==3)||(C(i,j,k-2)==1&&V(i,j,k-2)==6)
D(i,j,k)=1;
else D(i,j,k-1)=1;
end
elseif (C(i,j,k)==1&&V(i,j,k)==6)
if C(i,j,k+1)==1||(C(i-1,j,k+1)==1&&V(i-1.j,k+1)==2)...
||(C(i+1,j,k+1)==1&&V(i+1,j,k+1)==1)||(C(i,j-1,k+1)==1&&V(i,j-1,k+1)==4)...
||(C(i,j+1,k+1)==1&&V(i,j+1,k+1)==3)||(C(i,j,k+2)==1&&V(i,j,k+2)==5)
D(i,j,k)=1;
else D(i,j,k+1)=1;
end
elseif (C(i,j,k)==1&&V(i,j,k)==0)
D(i,j,k)=1;
end
end
end
end