Skip to content

Instantly share code, notes, and snippets.

@harryWonder
Last active June 12, 2022 19:08
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 harryWonder/3ef533f329b684baec28ccd65bf11d6f to your computer and use it in GitHub Desktop.
Save harryWonder/3ef533f329b684baec28ccd65bf11d6f to your computer and use it in GitHub Desktop.
This File Shows My Solution To The 2D Diagonal Difference Algorithm Question (Difficulty: Easy)
function DiagonalDifference(InputArray) {
const Input = InputArray
/**
* Determine the matrix type [3,3] || [4,4]
* Validate the matrix is in the desired order.
* Confirm that all the sub-array has the required length.
* Pick the most common length from the array and remove the sub-arrays that don't match.
*/
/**
* Get the size || length of each of the sub-arrays
*/
const SubArraySize = [];
Input.forEach((el) => {
SubArraySize.push(el.length);
});
/**
* Get the most common || re-occuring length from the previous sub-arrays
*/
let maxOccuringNumber = SubArraySize.map((el) => {
return SubArraySize.filter((ind) => (ind == el)).length
});
let matrixSize = Math.max(...[...new Set(maxOccuringNumber)]);
/**
* Sort the array by removing sub-arrays that dont match the matrixSize(no of columns)
*/
const SortedInput = Input.filter((el) => {
if (el.length == matrixSize) {
return el;
}
});
/**
* Calculate The Diagonal Difference
*/
let leftSide = SortedInput.map((el, index) => {
return el[index];
}).reduce((a, b) => a + b);
let rightSide = SortedInput.map((el, index) => {
let reverseMatrixSize = matrixSize - 1;
return el[Math.abs(index - reverseMatrixSize)];
}).reduce((a, b) => a + b);
return Math.abs(leftSide - rightSide);
}
DiagonalDifference([
// [0,2],
// [0, 1],
[2,3,4],
[0,3,1],
[6,3,5]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment