Skip to content

Instantly share code, notes, and snippets.

@willmcneilly
Last active August 29, 2015 13:57
Show Gist options
  • Save willmcneilly/9428307 to your computer and use it in GitHub Desktop.
Save willmcneilly/9428307 to your computer and use it in GitHub Desktop.
Check for consecutive matches in multidimensional array in both rows and columns. Return the index of each match. Candy Crush style matching.
var grid =
[
['a', 'b', 'c', 'c', 'c', 'c', 'c', 'd'],
['a', 'c', 'a', 'c', 'a', 'a', 'b', 'a'],
['b', 'a', 'c', 'a', 'b', 'a', 'b', 'b'],
['a', 'a', 'a', 'b', 'a', 'd', 'b', 'b'],
['a', 'b', 'c', 'a', 'a', 'a', 'e', 'b'],
['a', 'b', 'c', 'a', 'a', 'a', 'b', 'b'],
['a', 'b', 'c', 'a', 'a', 'c', 'b', 'b'],
['a', 'c', 'a', 'c', 'a', 'd', 'b', 'b'],
]
findMatchesRow = function(grid) {
var gridSize = grid.length
var matches = [];
var rowMatch = [];
var columnMatch = [];
for (var i = 0; i < gridSize; i++) {
var oneBeforeRow = null;
var oneBeforeColumn = null;
var currentRow = null;
var currentColumn = null;
for (var t = 0; t < gridSize; t++) {
currentRow = grid[i][t];
currentColumn = grid[t][i];
if (currentRow === oneBeforeRow) {
rowMatch.push({x:t, y:i});
}
else {
if(rowMatch.length > 2) {
matches.push(rowMatch);
}
rowMatch = [];
rowMatch.push({x:t, y:i});
}
oneBeforeRow = currentRow
if (currentColumn === oneBeforeColumn) {
columnMatch.push({x:i, y:t});
}
else {
if(columnMatch.length > 2) {
matches.push(columnMatch);
}
columnMatch = [];
columnMatch.push({x:i, y:t});
}
oneBeforeColumn = currentColumn;
}
}
return matches;
}
findMatchesRow(grid);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment