title: SET game odds simulation (MATLAB)
body: <p>I have recently found the great card came - <a href="http://setgame.com" rel="nofollow noreferrer"><strong>SET</strong></a>. Briefly, there are 81 cards with the four features: <strong>symbol</strong> (oval, squiggle or diamond), <strong>color</strong> (red, purple or green), <strong>number</strong> (one, two or three) and <strong>shading</strong> (solid, striped or open). The task is to locate (from selected 12 cards) a SET of 3 cards, in which each of the four features is either all the same on each card or all different on each card (no 2+1 combination).</p>
  
  <p>I've coded it in MATLAB to find a solution and to estimate odds of having a set in randomly selected cards.</p>
  
  <p>Here is my code to estimate odds:</p>
  
  <pre><code>%% initialization
  K = 12; % cards to draw
  NF = 4; % number of features (usually 3 or 4)
  setallcards = unique(nchoosek(repmat(1:3,1,NF),NF),'rows'); % all cards: rows - cards, columns - features
  setallcomb = nchoosek(1:K,3); % index of all combinations of K cards by 3
  
  %% test
  tic
  NIter=1e2; % number of test iterations
  setexists = 0; % test results holder
  % C = progress('init'); % if you have progress function from FileExchange
  for d = 1:NIter
  % C = progress(C,d/NIter);    
  
  % cards for current test
  setdrawncardidx = randi(size(setallcards,1),K,1);
  setdrawncards = setallcards(setdrawncardidx,:);
  
  % find all sets in current test iteration
  for setcombidx = 1:size(setallcomb,1)
      setcomb = setdrawncards(setallcomb(setcombidx,:),:);
      if all(arrayfun(@(x) numel(unique(setcomb(:,x))), 1:NF)~=2) % test one combination
          setexists = setexists + 1;
          break % to find only the first set
      end
  end
  end
  fprintf('Set:NoSet = %g:%g = %g:1\n', setexists, NIter-setexists, setexists/(NIter-setexists))
  toc
  </code></pre>
  
  <p>100-1000 iterations are fast, but be careful with more. One million iterations takes about 15 hours on my home computer. Anyway, with 12 cards and 4 features I've got around 13:1 of having a set. This is actually a problem. The instruction book said this number should be 33:1. And it was recently confirmed by <a href="http://norvig.com/SET.html" rel="nofollow noreferrer">Peter Norvig</a>. He provides the Python code, but I didn't test it yet.</p>
  
  <p>So can you find an error? Any comments on performance improvement are welcome.</p>