%% Lecture 7 % % Last week. % (lecture) functions that take the name of another function as an argument. % (lab) NIM % This week, touching on NIM, and a key computer science topic: recursion, % % The game of NIM. % % In the lab: I asked you to write a "playGame" % function winner = playGame(strategy1, strategy2, n) % and this required a loop: % % currentPlayer = 1; % while n > 1 % if currentPlayer == 1 % n = feval(strategy1,n); % currentPlayer = 2; % else % n = feval(strategy2,n); % currentPlayer = 1; % end % end % instead, what if we take the more direct approach: the first step is to just do strategy1 on n coins: n = feval(strategy1,n); then, we have a number of coins, 2 strategies. Wouldn't it be great if there was some way to compute what else would happen? function winner = playGame(strategy1, strategy2,n) if n == 1, winner = 2, else n = feval(strategy1,n); winner = 3-playGame(strategy2, strategy1, n); end % KEY is that the game must be the same. % and you must define the stopping condition. % (usually best to work up!). % Another game, Towers of Hanoi. % % Given the poles, and rings stacked in order of size on 1 pole, % how can we move them to be stacked in order on another pole, % when we only move one at a time, and when a bigger ring can never % be on top of a smaller one? % Play the game w/ 4 rings? % % Solve(N, Src, Aux, Dst) if N is 0 exit else Solve(N-1, Src, Dst, Aux) Move from Src to Dst Solve(N-1, Aux, Src, Dst) % Now, think about poor Gauss, and what he is doing for this?