Problem 44236. Mastermind I: Solve all 1296 cases

Solution 1215456

Submitted on 18 Jun 2017 by LY Cao
  • Size: 12
  • This is the leading solution.
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

Test Suite

Test Status Code Input and Output
1   Pass
tic v=1111:6666; vL=length(v); m=zeros(vL,4); for i=1:vL vp=v(i); for k=4:-1:1 m(i,k)=mod(vp,10); vp=floor(vp/10); end end mdel=sum((m==0)+(m>6),2)>0; m(mdel,:)=[]; v=m*[1000;100;10;1]; mL=size(m,1); mpc=zeros(mL); % 0.030 for j=1:mL mpc(:,j)=sum(m==repmat(m(j,:),mL,1),2); end mch=zeros(mL,6); % 0.038 for i=1:mL for k=1:6 mch(i,k)=nnz(m(i,:)==k); end end mc=zeros(mL); % 0.06 for j=1:mL mc(:,j)=sum(min(mch,repmat(mch(j,:),mL,1)),2); end mc=mc-mpc; % remove mpc part mpc5c=5*mpc+mc; fprintf('Initialization %.3f\n',toc) % finished initilaiztion calculation in less than 0.2 sec ztic=tic; solved=1; pcase=0; Lmax=0; Ltot=0; for ptr=randperm(1296) % anti-hack randomization pcase=pcase+1; mguess=[];mpegs=[]; while solved % loop until solved ztoc=toc(ztic); if ztoc>45 solved=0; break; end % if [mguessn]=solve_mastermind(mguess,mpegs,m,mpc,mc,mpc5c,v); mguessptr=find(v==mguessn*[1000;100;10;1]); if isempty(mguessptr),continue;end % invalid input mguess(end+1,:)=mguessn; mpegs(end+1,1)=mpc(ptr,mguessptr); mpegs(end,2)=mc(ptr,mguessptr); if mpegs(end,1)==4 % break on solved to ptr loop Lsol=size(mguess,1); Ltot=Ltot+Lsol; if Lsol>Lmax, Lmax=Lsol;end break; end end % while if ~solved,break;end % terminate case processing end % for all 1296 cases if solved fprintf('Solved in %.2f\n',ztoc) fprintf('Lmax %i Ltot %i\n',Lmax,Ltot) assert(isequal(solved,1)) else fprintf('Solved %i of 1296 cases in %.2f\n',pcase-1,ztoc) fprintf('Lmax %i Ltot %i\n',Lmax,Ltot) assert(isequal(solved,1)) end

Initialization 0.227 Solved in 38.30 Lmax 10568 Ltot 1603862

Suggested Problems

More from this Author241

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!