% Control3_3.m
% Solution to problem 3 of control3, including 3A and 3B
% Instead of an infinite deck, we replace drawn cards to the 10-card deck
% Jose M Soler, May.2022

% Set parameters
clear
nc = 10;          % number of cards in deck
m0 = ones(1,nc);  % initial deck (all cards present)
M = 2e3;          % number of games played
smax = 21;        % max sum of drawn cards

% Loop on whether drawn cards are replaced or not (exercises 3A and 3B)
for replace = 0:1
  for s = 1:smax    % loop on s (sum of player's cards)
    
    % Simulate M games and count wins
    nw = 0;         % games won by groupier
    for i = 1:M     % loop on games
      
      % First, player draws cards
      sp = inf;     % make sure that sp~=s initially
      while sp~=s   % restart game until player's cards sum s
        m = m0;     % deck of (remaining) cards
        sp = 0;     % sum of cards drawn by player
        while sp<s  % draw cards until sp>=s
          [c,m] = funCartas_JMS(m,replace);
          sp = sp+c;
        end
      end           % after this, sp=s
      
      % Next, groupier draws cards
      sg = 0;       % sum of cards drawn by groupier
      while sg<s    % draw cards until sg>=sp
        [c,m] = funCartas_JMS(m,replace);
        sg = sg+c;
      end
      if sg<=smax   % game won by groupier
        nw = nw+1;
      end
      
    end % i
    pg(s) = nw/M;   % probability of win by groupier
    
  end % s

  % Plot conditional probabilities
  figure(11+2*replace)
  s = 1:smax;
  plot(s,pg, s,1-pg, 'LineWidth',1.5)
  legend('Groupier wins','Player wins')
  xlabel('Sum of player''s cards')
  ylabel('Conditional probability')
  grid on
  answer = {'no','yes'};
  title(['Drawn cards replaced?: ',answer{1+replace}])
  set(gca,'FontSize',15)
  
  % Now, find the probability of win by player if he stops after sp>=s
  % This was not part of control 3
  for s = 1:smax
    pp(s) = 0;        % probability of win by player
    for i = 1:M       % loop on games
      m = m0;         % deck of (remaining) cards
      sp = 0;         % sum of cards drawn by player
      while sp<s      % draw cards until sp>=s
        [c,m] = funCartas_JMS(m,replace);
        sp = sp+c;
      end
      if sp<=smax     % game not lost by player after drawing his cards
        pp(s) = pp(s) + (1-pg(sp));  % prob. of win by player, after groupier draws
      end
    end % i
    pp(s) = pp(s)/M;  % average probability of win by player
  end
  
  % Plot final probabilities (not part of control 3)
  figure(12+2*replace)
  s = 1:smax;
  plot(s,1-pp, s,pp, 'LineWidth',1.5)
  legend('Groupier wins','Player wins')
  xlabel('Minimum sum of player''s cards')
  ylabel('Probability')
  grid on
  answer = {'no','yes'};
  title(['Drawn cards replaced?: ',answer{1+replace}])
  set(gca,'FontSize',15)
  
end % replace
