Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Solution 43444

Submitted on 17 Feb 2012 by @bmtran

Correct

133Size
Leading solution size is 26.
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

Test Suite

Test
Code Input and Output
1
Pass
 
%%
  doDraw=false; %set to true for display
  params=struct('n',50,'str','NESW','D',[-1,50,1,-50],'wins',[0,0,0]);
  rand('state',0);
  for nboards=1:100,
      % initialize board
      params.board=zeros(params.n);
      params.board([1,end],:)=-3;
      params.board(:,[1,end])=-3;
      [i,j]=find(params.board|1);
      [nill,pos1]=max((i==2|j==2)+~params.board(:)+rand(params.n*params.n,1));
      params.board(pos1)=1;
      [nill,pos2]=max((i==2|j==2)+~params.board(:)+rand(params.n*params.n,1));
      params.board(pos2)=2;
      while 1
          % blue's next movement
          params.state=rand('state');
          assignin('caller','params',params);
          d1=tron(params.board);
          params=evalin('caller','params');
          rand('state',params.state);
          % red's next movement
          i=find(params.board==2);
          [nill,j]=max(~params.board(i+params.D)+.5*(params.board(i-params.D)==-2));
          d2=params.str(j);
          % evaluate movements
          d1=findstr(params.str,d1);
          d2=findstr(params.str,d2);
          assert(~isempty(d1));
          params.board(pos1)=-1;
          params.board(pos2)=-2;
          pos1=pos1+params.D(d1);
          pos2=pos2+params.D(d2);
          if pos1==pos2||(params.board(pos1)&&params.board(pos2)), %tie
              params.wins(2)=params.wins(2)+1;
              if doDraw, disp('tie'); end
              break;
          elseif params.board(pos1), %loose
              if doDraw, disp('loose'); end
              params.wins(3)=params.wins(3)+1;
              break;
          elseif params.board(pos2), %win
              if doDraw, disp('win'); end
              params.wins(1)=params.wins(1)+1;
              break;
          end
          params.board(pos1)=1;
          params.board(pos2)=2;
          if doDraw
              image(4+params.board);
              axis equal off;
              colormap([1,1,1;.5,0,0;0,0,.5;0,0,0;0,0,1;1,0,0]);
              set(gcf,'color','k');
              drawnow;
          end
      end
      if doDraw, pause; end
  end
  disp(sprintf('%d wins; %d ties; %d looses',params.wins));
  assert(params.wins(1)>=90,sprintf('%d wins; %d ties; %d looses',params.wins));
91 wins; 1 ties; 8 looses