Skip to content

Instantly share code, notes, and snippets.

@ryanomor
Last active June 27, 2018 14:20
Show Gist options
  • Save ryanomor/95d3a79eea33398c677c90c2131751e4 to your computer and use it in GitHub Desktop.
Save ryanomor/95d3a79eea33398c677c90c2131751e4 to your computer and use it in GitHub Desktop.
Given an array, check to see if at least one of its diagonals have the same values
let myArr = [1,2,3,4,
4,0,4,4,
7,0,1,4,
4,4,4,1],
myArr2 = [1,2,3,4,
4,1,4,4,
7,0,1,4,
4,4,4,1];
function checkDiagonals(arr) {
// Check if array is a perfect square
if (!Number.isInteger(Math.sqrt(arr.length))) {
return false;
}
let sqrt = Math.sqrt(arr.length);
let leftDiag = arr[0];
let rightDiag = arr[sqrt - 1];
for(let i = 1; i < sqrt; i++) {
let nextLeft = arr[((sqrt * i) + i)];
let nextRight = arr[((sqrt - 1) * (i + 1))];
// Check if current left and right diagonal value match the next value in respective diagonal
if (leftDiag !== nextLeft && rightDiag !== nextRight) {
return false;
};
// Reassign each value with the next value in the diagonal
leftDiag = nextLeft;
rightDiag = nextRight;
};
return true;
}
checkDiagonals(myArr); // false
checkDiagonals(myArr2); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment