Skip to content

Instantly share code, notes, and snippets.

@chrisrng
Last active April 20, 2016 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisrng/d870ccf25031efaba43137c9a0d2b52e to your computer and use it in GitHub Desktop.
Save chrisrng/d870ccf25031efaba43137c9a0d2b52e to your computer and use it in GitHub Desktop.
function Longest(matrix) {
const cache = getMarkedUpMatrix(matrix);
let current = 1;
let longest = 1;
Object.keys(cache).map((value) => {
const cacheObj = cache[value];
const cacheObj2 = cache[(parseInt(value, 10) + 1) + ''];
if (isNeighbor(cacheObj, cacheObj2)) {
current++;
if (current > longest) {
longest = current;
}
} else {
current = 1;
}
});
return longest;
}
function getMarkedUpMatrix(matrix) {
const cache = {};
const markedupMatrix = matrix.map((row, rowIndex) => {
return row.map((colValue, colIndex) => {
cache[colValue] = {col: colIndex, row: rowIndex};
});
});
return cache;
}
function isNeighbor(first, second) {
if (!first || !second) { return false; }
const x1 = first.row;
const x2 = first.col;
const y1 = second.row;
const y2 = second.col;
const y1range = Boolean([y2 - 1, y2, y2 + 1, y2 + 2].includes(y1));
const x1range = Boolean([y1 - 1, y1, y1 + 1, y1 + 2].includes(x1));
return Boolean((x1 === y1 && y1range ) || (x2 === y2 && x1range));
}
console.log(Longest([[0, 1, 4], [2, 3, 5], [8, 7, 6]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment