% fifteen.m
% C Bishop 
% randomized version of the fifteen puzzle in which 
% the empty box moves at random. Prof Robert Hough
% wrote a paper on how long it takes puzzles of this 
% form to become randomized. This is a kind of random 
% walk on a finite, but large, set of possible states, 
% and the mixing time is howlong it takes for every 
% state to be approximately equally likely

num=4;
stop4print=[1:50,100,200,300,400,500];
steps=1000;
delay=0;
skip=1;
pt=1;
perm=[1:16];
% Each row of m represents a box in the 4x4 grid 
% The first number is the number of neighboring points
% Tthe following non-zero numbers (2,3, or 4 of them) are the 
% labels of these neighbors. 
m=[ 2,2,5,0,0;
    3,1,3,6,0;
    3,2,4,7,0;
    2,3,8,0,0;
    3,1,6,9,0;
    4,2,5,7,10;
    4,3,6,8,11;
    3,4,7,12,0;
    3,5,10,12,0;
    4,6,9,11,14;
    4,7,10,12,15;
    3,8,11,16,0;
    2,9,14,0,0;
    3,10,13,15,0;
    3,11,14,16,0;
    2,12,15,0,0];
counter=0;
setc=jet(16);
setc=cool(16);
setc=gray(32);
setc=setc(17:32,:);
setc(1,:)=[0,0,0];
figure; axis equal; axis off; hold on;
       a=reshape(perm,[4,4]);
       image(a);
       for j=1:4
           for k=1:4
               n=a(j,k)-1;
               if n <10
               text(k-.18,j-.1,num2str(n),'FontSize',45,'Interpreter','latex')
               else 
               text(k-.35,j-.1,num2str(n),'FontSize',45,'Interpreter','latex')
               end % i f
           end % for  k
       end %  for j
       colormap(setc);
     %  colorbar;
       title(['\fontsize{30}step = ',num2str(counter)]);
       pause(1);
       temp=input('paused, hit return to continue');
while counter < steps
    counter=counter+1
    new=m(pt,randi(m(pt,1))+1);
    perm(pt)=perm(new);
    perm(new)=1;
    pt=new;
    if mod(counter,skip)==0
          if ismember(counter, stop4print)
           %close all;
           %figure; axis equal; axis off; hold on;
           %figure; axis equal; axis off; hold on;
          a=reshape(perm,[4,4]);
          image(a);
          for j=1:4
              for k=1:4
                  n=a(j,k)-1;
                 if n <10
                  text(k-.18,j-.1,num2str(n),'FontSize',45,'Interpreter','latex')
                 else 
                  text(k-.35,j-.1,num2str(n),'FontSize',45,'Interpreter','latex')
                  end % i f
              end % for  k
          end % FOR J
       colormap(setc);
     %  colorbar;
       title(['\fontsize{30}step = ',num2str(counter)]);
       pause(1);
       %temp=input('paused');
       end % if
    end % if skip
end % while 

