# diagonal attack

0

0

The code in this function takes a string and divides it into pieces using the stringβs split() method. Next, it creates an empty matrix using the map() function. Next, it loops through each piece of the string and stores the corresponding value in the matrix using the stringβs split() method again. Finally, it checks if the leftRightDiag and rightLeftDiag values are equal and if they are, the code prints the contents of the matrix.

``````function diagonalAttack(string) {
const matrix = [];
let leftRightDiag = 0;
let rightLeftDiag = 0;

for (let i = 0; i < string.length; i++) {
matrix.push(
string[i].split(' ').map((string) => {
return Number(string);
})
);
}
// Diagonals sum:

for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix.length; j++) {
if (i === j) {
leftRightDiag += matrix[i][j];
}
if (i + j === matrix.length - 1) {
rightLeftDiag += matrix[i][j];
}
}
}
// Checking diagonal sums equality and printing the results:

if (leftRightDiag === rightLeftDiag) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix.length; j++) {
if (i === j || i + j === matrix.length - 1) {
continue;
} else {
matrix[i][j] = rightLeftDiag;
}
}
}
console.log(matrix.map((arr) => arr.join(' ')).join('\n'));
} else {
console.log(matrix.map((arr) => arr.join(' ')).join('\n'));
}
}``````
• Rulesets
• Playground
• Snippets
• Cookbooks
###### Legal

We are SOC-2 Compliance Certified