function spin ( trial_num )

%*****************************************************************************80
%
%% spin() simulates a game involving two spinning disks.
%
%  Discussion:
%
%    A game involves two spinnable disks, each divided into three sectors.
%    A player spins disk 1 or 2 according to the following rules:
%    * if the player spins disk i, and it stops in region Pij, he
%      moves from disk i to disk j;
%    * if the spinner stops in region Pi3, the game ends.
%    * if the game ends in P13, the player wins.
%    What is the probablity that the player, starting with disk 1, wins?
%
%  Example:
%
%     10,000 games, P estimate is 0.6574
%    100,000 games, P estimate is 0.6498.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    28 January 2018
%
%  Author:
%
%    Paul Nahin
%
%  Reference:
%
%    Paul Nahin,
%    Digital Dice: Computational Solutions to Practical Probability Problems,
%    Princeton, 2008,
%    ISBN: 978-0-691-15821-1.
%
%  Input:
%
%    integer trial_num: the number of trials.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'spin():\n' );
  fprintf ( 1, '  A game involves two spinnable disks, each divided into three sectors.\n' );
  fprintf ( 1, '  A player spins disk 1 or 2 according to the following rules:\n' );
  fprintf ( 1, '  * if the player spins disk i, and it stops in region Pij, he\n' );
  fprintf ( 1, '    moves from disk i to disk j;\n' );
  fprintf ( 1, '  * if the spinner stops in region Pi3, the game ends.\n' );
  fprintf ( 1, '  * if the game ends in P13, the player wins.\n' );
  fprintf ( 1, '  What is the probablity that the player, starting with disk 1, wins?\n' );

  p = [ 0.20, 0.40; 
        0.30, 0.35 ];

  wins = 0;

  for loop = 1 : trial_num

    keep_going = 1;
    disk = 1;

    while ( keep_going == 1 )

      spin_pointer = rand ( );

      if ( spin_pointer < p(disk,1) )
        disk = 1;
      else
        if ( spin_pointer < p(disk,1) + p(disk,2) )
          disk = 2;
        else
          keep_going = 0;
          if ( disk == 1 )
            wins = wins + 1;
          end
        end
      end

    end
  end

  wins = wins / trial_num;

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Probabiity of winning = %g\n', wins );
  fprintf ( 1, '  Theoretical value     = %g\n', 0.65 );

  return
end
