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 300673

Submitted on 10 Aug 2013 by Alfonso Nieto-Castanon

Correct

197Size
Leading solution size is 23.
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
 
%%
%Tic-Tac-Toe
%Demonstration of Multi-Call with adaptive response
wins=0;
Pass=0;
for i=1:50 % Computer First;  51-100 will be Player First
 x=zeros(3);
 while true % exit on win or filled board
  if i<16 % Up bot
   p=find(x==0,1);
  elseif i<31 % Down bot
   p=find(x==0,1,'last');
  else % 31 thru 50 % random bot
   found=0;
   while ~found
    p=floor(9*rand)+1;
    if x(p)==0,break;end
   end
  end
  % Implement Computer move and Check for Win
  x(p)=1;
  wt=x;
  wt(wt==2)=0;
  win=any([sum(wt) sum(wt,2)' trace(wt) trace(fliplr(wt))]==3);
  if win,break;end % Computer Wins on its move
  % Draw check Post computer move (9th move)
  if sum(x(:))>=13,break;end
  % Implement player move and Check for Win
  p=tic_tac_toe(x);
  p=p(1);
  if x(p)~=0,break;end % Invalid move - Game over
  x(p)=2;
  wt=x;
  wt(wt==1)=0;
  win=any([sum(wt) sum(wt,2)' trace(wt) trace(fliplr(wt))]==6);
  if win
   wins=wins+1;
   break;
  end % Player Wins on their move
 end % gameover while 1:50
end % Games 1:50
% Output wins against Computer first
wins
for i=51:100 % Player First;  51-100 Player First
 x=zeros(3);
 while true % exit on win or filled board
  % Implement player move and Check for Win
  p=tic_tac_toe(x);
  p=p(1);
  if x(p)~=0,break;end % Invalid move - Game over
  x(p)=2;
  wt=x;
  wt(wt==1)=0;
  win=any([sum(wt) sum(wt,2)' trace(wt) trace(fliplr(wt))]==6);
  if win
   wins=wins+1;
   break;
  end % Player Wins on their move
  % Draw check Post computer move (9th move)
  if sum(x(:))>=13,break;end
  if i<66 % Up bot
   p=find(x==0,1);
  elseif i<81 % Down bot
   p=find(x==0,1,'last');
  else % 31 thru 50 % random bot
   found=0;
   while ~found
    p=floor(9*rand)+1;
    if x(p)==0,break;end
   end
  end
  % Implement Computer move and Check for Win
  x(p)=1;
  wt=x;
  wt(wt==2)=0;
  win=any([sum(wt) sum(wt,2)' trace(wt) trace(fliplr(wt))]==3);
  if win,break;end % Computer Wins on its move
 end % gameover while 51:100
end % Games 51:100
wins
if wins>65,Pass=1;end
assert(isequal(Pass,1))
wins =
    48
wins =
    97