Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checking for particular types of matrix in JavaScript
Problem
We are required to write a JavaScript function that takes in a 2-D array of literals, arr, as the first and the only argument.
Our function should check if every diagonal from top-left to bottom-right has the same element.
If it is so, we should return true, false otherwise.
For example, if the input to the function is
Input
const arr = [ [6, 7, 8, 9], [2, 6, 7, 8], [1, 2, 6, 7], ];
Output
const output = true;
Output Explanation
In the above array, the diagonals are −
[1], [2,2], [6,6,6], [7,7,7], [8,8], [9]
In each diagonal all elements are the same, so the answer is True.
Example
Following is the code −
const arr = [
[6, 7, 8, 9],
[2, 6, 7, 8],
[1, 2, 6, 7],
];
const checkMatrix = (arr = []) => {
const validate = (row, col) => {
while (
row < arr.length
&& col < arr[0].length
&& arr[row + 1]
&& arr[row + 1][col + 1] !== undefined
) {
if (arr[row + 1][col + 1] !== arr[row][col]) {
return false
}
row += 1
col += 1
}
return true
}
for (let i = 0; i < arr[0].length; i++) {
if (!validate(0, i)) {
return false
}
}
for (let i = 0; i < arr.length; i++) {
if (!validate(i, 0)) {
return false
}
}
return true
}
console.log(checkMatrix(arr));
Output
true
Advertisements