Code covered by the BSD License

MATLAB Contest - Peg Solitaire

09 May 2007 (Updated 06 Aug 2009)

All the files needed to develop and score an entry for the MATLABĀ® Programming Contest.

```function score = grade(board,moves)

% Copyright 2007 The MathWorks, Inc.

[m,n] = size(board);
tb = @(p) all([p>0 p<=[n m] ~rem(p,1)]);
if size(moves,2)~=4 || ~isnumeric(moves) || ~isreal(moves)
error('MOVES must be a numeric and real matrix with 4 columns')
end
moves = round(moves(1:min(nnz(board>0),end),:));
score = sum(board(board(:)>0));
lastPeg = [-1 -1];
for i = 1:size(moves,1)
f = moves(i,[2 1]);
t = moves(i,[4 3]);
if tb(f) && board(f(2),f(1))>0 % valid pick
score = score + any(lastPeg-f).*board(f(2),f(1));
lastPeg = f;
mp = (f+t)/2;
if tb(t) && board(t(2),t(1))==0 && all(sort(abs(f-t))==[0 2]) ...
&& board(mp(2),mp(1))>0 % valid move
lastPeg = t;
score = score - board(mp(2),mp(1));
board(t(2),t(1)) = board(f(2),f(1));
board([f(2) mp(2)],[f(1) mp(1)]) = 0;
end
else
lastPeg = [0 0];
end
end

```