Check if connect 4 occurs in matrix
Show older comments
Could someone help me with a code to check if there is a Connect 4 in the following matrix:
0 0 0 0 0 0 0 0 = empty
0 0 2 1 2 2 0 1 = green
1 2 2 2 1 1 2 2 = blue
2 1 1 1 2 1 1
2 1 2 1 2 2 2
1 2 1 2 1 2 1
A Connect 4 occurs when (in this case) 4 of the same color (in this case 1 and 2) line up horizontally, vertically or diagonally.
All help is greatly appreciated!
1 Comment
The Legend
on 15 Dec 2019
Accepted Answer
More Answers (1)
It's a little tricky to find a vector within a matrix when the dimensions of the matrix are all larger than the vector. I'm converting the values to characters and using regular expressions to do the matching but there may be a better way.
In any case, here's a demo. See inline comments for details.
% The input matrix
data = [
0 0 0 0 0 0 0
0 0 2 1 2 2 0
1 2 2 2 1 1 2
2 1 1 1 2 1 1
2 1 2 1 2 2 2
1 2 1 2 1 2 1];
% defined minimum consecutive values (ie, cx=4 equals "connect 4")
cx = 4;
% Define the value to check
checkVal = 2;
% The following checkxxx are all logicals (1/0) where a 1 means a connection is found
checkRows = any(~cellfun(@isempty,regexp(cellstr(char(data)),char(checkVal*ones(1,cx)))));
checkCols = any(~cellfun(@isempty,regexp(cellstr(char(data).'),char(checkVal*ones(1,cx)))));
dataDiags = spdiags(data); % a list of all diagonals
checkDiags = any(~cellfun(@isempty,regexp(cellstr(char(dataDiags).'),char(checkVal*ones(1,cx)))));
% output a final logical 1/0 that indicates a connection was found.
connectionFound = any([checkRows,checkCols,checkDiags]);
This could easily be put into a loop to find connections for any non-0 element.
unqVals = unique(data(data>0));
for i = 1:numel(unqVals)
checkVal = unqVals(i);
. . .
end
4 Comments
The Legend
on 16 Dec 2019
The Legend
on 16 Dec 2019
The Legend
on 16 Dec 2019
Adam Danz
on 16 Dec 2019
" how to output the winning team"
"checkVal" determines which group to test, 1 or 2. You can run it on both groups and output the group that wins. But see Stephen's updated answer since it's simpler.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!