CS99 FALL 2002 PRELIM 2 ------------------------------------------------------------------------------- % Problem1 % Inititalize variables: clear; MAX = 10; % 10 marbles to start with MIN = 0; % can't have neg marables whiteTotal = randInt(MIN,MAX); % choose white marbles blackTotal = MAX - whiteTotal; % choose black marbles count = 0; % taken-marble counts % Extract marbles until one color runs out % or both colors run out: while whiteTotal >= MIN & blackTotal >= MIN & count < MAX % Take a marble: switch readInt(0,1,'Try to take a marble [0 (W),1 (B)]: ') case 0 if whiteTotal > MIN whiteTotal=whiteTotal-1; count = count+1; else disp('Sorry! Out of white marbles!'); end case 1 if blackTotal > 0 blackTotal=blackTotal-1; count = count+1; else disp('Sorry! Out of black marbles!'); end otherwise error('Error!'); end end % Report total amount of marbles taken. disp(['Total marbles taken: ',num2str(count)]); ------------------------------------------------------------------------------- % Problem2 % Inititalize variables: size = randInt(1,10); % do rows fprintf('\n'); for row=1:size % do cols for col=1:2*size if col <= size-row, fprintf(' '); elseif col > size-row & col <= size, fprintf('/'); elseif col > size & col <= size+row, fprintf('\\'); else fprintf(' '); end end fprintf('\n'); end for row=size+1:2*size % do cols for col=1:2*size if col < row-size, fprintf(' '); elseif col >= row-size & col <= size, fprintf('\\'); elseif col > size & col <= 3*size-row+1 , fprintf('/'); else fprintf(' '); end end fprintf('\n'); end fprintf('\n'); % Example session: % /\ % //\\ % ///\\\ % \\\/// % \\// % \/ ------------------------------------------------------------------------------- % Problem 3 function test = Problem3() % PROBLEM3 Test randChars test = randChars(2,4); function result = randChars(rows,cols) % RANDCHARS fill array with random lowercase letters % Fill array $a$ with random lowercase letters: for r=1:rows for c=1:cols result(r,c)=char(randInt(double('a'),double('z'))); end end % more compressed answer: % result=char(floor(rand(rows,cols)*('z'-'a'+1))+floor('a')) ------------------------------------------------------------------------------- % Problem 4 function result = Problem4() result = core(rand(4,5)); function result = core(x) result = x(2:end-1,2:end-1);