Cody

# Problem 43574. Connect 4 (the boardgame)

Solution 2078301

Submitted on 3 Jan 2020 by Chul Min Yeum
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

### Test Suite

Test Status Code Input and Output
1   Pass
games = 10; winners = zeros(games,1); for gamenum = 1:games % you play "games" different games % init the board board = zeros(5,7); % function finding the index at which the chip will fall in column c index = @(c,board) find(board(:,c)==0,1,'last'); % start the game whoWon = 0; done = false; turn = 1; while done == false if turn == 1 % you oppenent's turn % select random column allC = find(sum(board~=0,1)<5,7); % all not full columns c = allC(randi(length(allC),1,1)); % random placement % place chip in column c board(index(c,board),c) = 1; else % your turn % which column c = move(board); % place chip in column c i = index(c,board); % index if ~isempty(i) board(i,c) = 2; else disp('You have selected a full column, your turn goes lost') end end % check for a 4-in-a-row temp = board==turn; % gather all possible 4-in-a-row lines lines = cell(22,1); % horizontal for i = 1:5 lines{i} = temp(i,:)'; end % vertical for i = 1:7 lines{i+5} = temp(:,i); end % diagonal \ lines{13} = diag(temp(2:end,:)); for i = 1:4 lines{i+13} = diag(temp(:,i:end)); end % diagonal / temp = fliplr(temp); lines{18} = diag(temp(2:end,:)); for i = 1:4 lines{i+18} = diag(temp(:,i:end)); end for i = 1:length(lines) % find the maximum number of the same chips in this row temp = diff([0; lines{i}; 0]); if max(find(temp==-1,7)-find(temp==1,7))==4 % game is won! whoWon = turn; done = true; end end % is the board full without a winner? if sum(board==0)==0 done = true; end % switch turns turn = 3-turn; end % end of one game winners(gamenum) = whoWon; end disp(['Game results (#won/#lost/#draw): ' num2str(sum(winners==2)) '/' num2str(sum(winners==1)) '/' num2str(sum(winners==0))]) % Did you win all 10 games? assert(isequal(sum(winners==2),games))

Game results (#won/#lost/#draw): 10/0/0