How to Check if the Matrix is a Magic Square in JavaScript?
Last Updated :
16 May, 2024
We are going to Check if the Matrix is a Magic Square in JavaScript. A matrix is said to be Magic Square if the sum of elements of any row, column or diagonal is equal to a specific number. Below is an example to understand the problem clearly.
Example:
Input:
[ [2, 7, 6] ,
[9, 5, 1] ,
[4, 3, 8] ] ;
Output: True
Explanation: The sum of elements of every row, column and diagonal is equal to a specific number.
Below are the approaches in JavaScript to Check if the matrix is a magic square or not:
Naive Approach
In this method, calculate the sum of the first row. Then, iterate through each row and column. If any row's or column's sum doesn't match the sum of the first row, return false. Next, calculate the sums of the main and secondary diagonals. If either doesn't match the sum of the first row, return false. If all checks pass, return true.
Example: To demonstrate checking if the matrix is a magic square in JavaScript using brute force approach
JavaScript
function magicSquare(matrix) {
const n = matrix.length;
let sum = 0;
for (let j = 0; j < n; j++) {
sum += matrix[0][j];
}
for (let i = 1; i < n; i++) {
let rowSum = 0;
for (let j = 0; j < n; j++) {
rowSum += matrix[i][j];
}
if (rowSum !== sum) {
return false;
}
}
for (let j = 0; j < n; j++) {
let columnSum = 0;
for (let i = 0; i < n; i++) {
columnSum += matrix[i][j];
}
if (columnSum !== sum) {
return false;
}
}
let diagonalSum = 0;
for (let i = 0; i < n; i++) {
diagonalSum += matrix[i][i];
}
if (diagonalSum !== sum) {
return false;
}
diagonalSum = 0;
for (let i = 0; i < n; i++) {
diagonalSum += matrix[i][n - i - 1];
}
if (diagonalSum !== sum) {
return false;
}
return true;
}
const matrix = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
];
console.log(magicSquare(matrix));
Time complexity: O(n^2)
Space complexity: O(1)
Using Mathematical Properties
To verify if a matrix is a magic square, use the formula n * (n^2 + 1) / 2 to calculate the expected sum for each row, column, and diagonal, where n is the matrix size. Iterate through rows and columns, summing elements and comparing with the expected sum. Additionally, compute the sums of the main and secondary diagonals. If any sum deviates from the expected value, return false; otherwise, return true if all sums align with the expected sum.
Example: To demonstrate checking if the matrix is a magic square in JavaScript using mathematical properties approach.
JavaScript
function magicSquare(matrix)
{
const n = matrix.length;
const expectedSum = n * (n * n + 1) / 2;
let rowSum = 0, colSum = 0, mainDiagSum = 0;
for (let i = 0; i < n; i++) {
rowSum = 0;
colSum = 0;
for (let j = 0; j < n; j++) {
rowSum += matrix[i][j];
colSum += matrix[j][i];
}
if (rowSum !== expectedSum || colSum !== expectedSum)
{
return false;
}
mainDiagSum += matrix[i][i];
}
let secondaryDiagSum = 0;
for (let i = 0; i < n; i++) {
secondaryDiagSum += matrix[i][n - i - 1];
}
if (secondaryDiagSum !== expectedSum || mainDiagSum !== expectedSum) {
return false;
}
return true;
}
const matrix = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
];
console.log(magicSquare(matrix));
Time complexity: O(n^2)
Space complexity: O(1)
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read