%% Golf Scorecards
% Every hole in golf has an associated "par" that indicates the expected number of strokes needed to sink the ball. Skilled players usually complete each hole with a number of strokes very close to par. It is necessary to play several holes and let scores accumulate before a clear winner emerges in a match.
% Ben, Jen, and Ken play a full round, which consists of 18 holes. The course has an assortment of par-3, par-4, and par-5 holes. At the end of the game, the players tabulate their scores.

hole = 1:18;
par = [4 3 5 3 4 5 3 4 4 4 5 3 5 4 4 4 3 4];

nms = {'Ben';'Jen';'Ken'};

Ben = [4 3 4 2 3 5 2 3 3 4 3 2 3 3 3 3 2 3];
Jen = [4 3 4 3 4 4 3 4 4 4 5 3 4 4 5 5 3 3];
Ken = [4 3 4 3 5 5 4 4 4 4 5 3 5 4 5 4 3 5];

T = table(hole',par',Ben',Jen',Ken', ...
    'VariableNames',['hole';'par';nms])

%
% The winner of the round is the player whose lower cumulative sum drifts the most below par at the end. Compute the sums for the three players to determine the winner. Make every shift in mean detectable by setting a small threshold.

[~,b,~,Bensum] = cusum(Ben-par,1,1e-4,0);
[~,j,~,Jensum] = cusum(Jen-par,1,1e-4,0);
[~,k,~,Kensum] = cusum(Ken-par,1,1e-4,0);

plot([Bensum;Jensum;Kensum]')
legend(nms,'Location','best')

%
% Ben wins the round. Simulate their next game by adding or subtracting a stroke per hole at random.

Ben = Ben+randi(3,1,18)-2;
Jen = Jen+randi(3,1,18)-2;
Ken = Ken+randi(3,1,18)-2;

[~,b,~,Bensum] = cusum(Ben-par,1,1e-4,0);
[~,j,~,Jensum] = cusum(Jen-par,1,1e-4,0);
[~,k,~,Kensum] = cusum(Ken-par,1,1e-4,0);

plot([Bensum;Jensum;Kensum]')
legend(nms,'Location','best')

% Copyright 2012 The MathWorks, Inc.