%
% Golf Simulation for Stats Class
%
%
% Usage: golf( n ) : where n is the number of trial rounds of golf you want to use in the simulation
% Example: golf( 3 ) : will give the average score from 3 different random rounds of golf
%
% Usage: golf( n, 1 ) : where n is the number of trial rounds of golf you want to use in the simulation
%                     : AND the 1 will make sure that the shots of each golfer are displayed
% Example: golf( 3, 1 ) : will give the average score from 3 different random rounds of golf and
%                         the program will display their shots
%
function [ret] = golf( trials, yn=0 )

% States: 0 = Tee
%         1 = Fairway
%         2 = Rough
%         3 = Green
%         4 = Still on Fairway
%         5 = Still on Green
%         6 = In the cup
%
% Written January 16, 2015 - Michael K. Pellegrino
%
  
  state=0;
  scores=[];
  
  for( i=1 : trials )
    
    shots=0;
    state=0;
    
    % First Shot
    shots++;
    
    if( rand() <= 0.7 )
      show( "tee -> fairway", yn );
      state = 1;
    else
      show( "tee -> rough", yn );
      state = 2;
    endif

    while( state == 2 )
      if( rand() > 0.4 )
	shots++;
	state=2;
	show( "rough -> rough", yn );
      else
	shots++;
	state=3;
	show( "rough -> green", yn );
      endif
    endwhile

    % From Fairway to green
     if( state == 1 )
      shots++;
      if( rand() > 0.8 )
	state=3;
	show( "fairway -> green", yn );
      else
	state=4;
	show( "fairway -> fairway", yn );
      endif
    endif
    
    while( state == 4 )
      if( rand() > 0.9 )
	shots++;
	state=4;
	show( "fairway -> fairway", yn );
      else
	shots++;
	state=3;
	show( "fairway -> green", yn );
      endif
    endwhile

    % From green to cup
    if( state == 3 )
      shots++;
      if( rand() > 0.2 )
	state=5;
	show( "green -> green", yn );
      else
	state=6;
	show( "green -> cup", yn );
      endif
    endif
    
    while( state == 5 )
      if( rand() > 0.9 )
	shots++;
	state=5;
	show( "green -> green", yn );
      else
	shots++;
	state=6;
	show( "green -> cup", yn );
      endif
    endwhile
    
    scores=[ scores shots ];
    if( i < trials )
      show( "*** next trial ***", yn);
    else
      show( "** end of trials *", yn);
    endif
  endfor
  disp( "Average Score:" );
  ret=mean( scores );
endfunction
