function [] = lec220(in, skip) % lec220. animation of execution of max-of-sequence example in 2/20 lecture % usage: lec220() or lec220(inputValues) or lec220(inputValues, skip) % $inputValues$: the vector of input values, excluding the terminating 0 % $skip$: % 0 (default value): animate each step % 1 : animate only loop iterations (skip loop body) % inf : generate html/png output % lec220([5 -3 8 17 5 19 18], inf) if nargin == 0 in = [5 -3 8 17 5 19 18]; end if nargin <= 1 skip = 0; end if any(in == 0) error('input sequence contains 0') end invcolor = 'g'; % color of invariant when true notinvcolor = 'r'; % color of invariant when false yescolor = 'c'; % color of activated if/while when guard is true nocolor = 'm'; % color of activated if/while when guard is false oncolor = 'b'; % color of other activated line of code in = [in(:)' 0]; step = []; step = [step -1]; i = 0; i = i+1; num = in(i); curmax = -inf; stopping = 0; % inv %0 step = [step 1]; while num ~= stopping %1 step = [step 2]; if num > curmax %2 step = [step 3]; curmax = num; %3 CURMAX{length(step)} = curmax; step = [step 4]; end %4 step = [step 5]; i = i+1; num = in(i); %5 I{length(step)} = i; step = [step 6 1]; end %6 step = [step 7]; % after %7 CURMAX{length(step)+1} = []; I{length(step)+1} = []; tests = [1 2]; % lines with tests program = strvcat(... 'num = input(prompt); curmax = -inf;', ... '% inv: curmax = maxsofar(excluding num)', ... 'while num ~= stopping', ... ' if num > curmax;', ... ' curmax = num;', ... ' end', ... ' num = input(prompt);', ... 'end', ... '... code after while loop...'); figure(1); set(1,'Position',[10 300 870 384]); clf hold on axis([-2 9 0 14]); axis ij axis off adj = 2; for line = -1:7 h(line+adj) = mytext(1, adj+line, program(line+adj,:)); end h(0+adj) = myplot([.8 .8 8 8 .8], [2.5 1.5 1.5 2.5 2.5], invcolor); set(mytext(0, 12, 'input:'), 'HorizontalAlignment','right'); for i = 1:length(in) hin(i) = mytext(i, 12, sprintf('%d', in(i))); end set(hin,'HorizontalAlignment','center') harrow = myplot([0 .75], [0+adj 0+adj], 'k->'); hnum = mytext(1, 11, 'num'); set(hnum, 'HorizontalAlignment','center'); hnuml = myplot([.5 1.5], [11.5 11.5], 'y'); hmax = mytext(0.5, 11, 'maxsofar = -oo'); set(hmax, 'HorizontalAlignment','right'); hmaxl = myplot([0 .5], [11.5 11.5], 'b'); hcur = mytext(0.5, 13, 'curmax = -oo'); set(hcur, 'HorizontalAlignment','right'); hcurl = myplot([0 .5], [12.5 12.5], 'b'); num = in(1); curmax = -inf; maxsofar = -inf; ii = 1; if isinf(skip) for i = 1:length(step) prev = find(step==1); prev = max(prev(prev < i)); next = find(step==1); next = min(next(next > i)); fid = fopen(sprintf('%02d.htm',i),'w'); fprintf(fid, '\n'); fprintf(fid, '
\n', i); fprintf(fid, '
program: | %s%s
---|
loop iteration: | %s%s
line of code: | %s%s