% Topic: Using the Monte Carlo method for finding probabilites 
% Case study: Problem three in session three (Two players roll a pair of dice in turn)
% If you have any question, send an email to: asahebpa@uwaterloo.ca
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clc
clear all

Number_of_Games = 10000;

for game = 1:Number_of_Games % Loop for repeating the game
    
   player = 0; % Player A : 0 
               % Player B : 1 
               % Player A starts the game so in first iteration player = 0
   PAwins_eachtrial = 5/36;% Sum of 6
   PBwins_eachtrial = 1/6; % Sum of 7
   
   while 1 % Loop for a game
       
      % In different versions of matlab, and many important programming languages..
      % like python, we only can generate uniform and some languages
      % also normal random variables, but in many cases like considering
      % case we are dealing with other random vriables.
      % In this case for example we have two events with some probabilities:
      % 1. Sum of 6 which is A's objective
      % 2. Sum of 7 which is B's objective
      % To do this, first we generate a uniform random variable from 0 to 1
      % and after that we check that if the random variable is less than
      % 1/6 when player A is playing or less than 5/36 when player B is
      % playing. because we know that if X ~ U(0,1) => P(X < c) = c (Area under the PDF)
      
      result = rand(1); % Uniform random variable which will indicate result of a turn in a match 
      
      
      if (result < PAwins_eachtrial && player == 0) || (result < PBwins_eachtrial && player == 1) % Player A wins with probability 5/36 and B wins with probability 1/6. 
          break % Loop breaks if player A or player B wins the game
      end
      player = ~player; % If game did not end in this iteration, player changes and game continues
   end
   
   winn(game) = player; % While have been break so we have a winner and we put the index of the winner in a matrix (0 or 1)
    
end

PAwinner_MonteCarlo = sum(~winn)/Number_of_Games % Counting number of games in which A was the winner and deviding by number of games to find probability
PAwinner_Analytical = 30/61 % Session 3, probelm 3

abs_error = abs(PAwinner_MonteCarlo - PAwinner_Analytical) % Error of using the Monte Carlo method