sumOfDiagonals.js (***Coding test***)
/**Sum of Diagonals
Description
Given a square matrix, print the sum of all the numbers on both the diagonals.
Input format
First line contains a positive integer n, denoting the number of rows and columns It is
followed by n lines. Each line contains space separated integers denoting elements of that
row.
Output format
One line containing the sum of all the numbers on both the diagonals.
Sample input
3
1 2 3
4 5 6
7 8 9
Sample output
30
Explanation
First line is 3, i.e. 3 rows and 3 columns. We can see that there are 2 diagonals [1,5,9] and
[3,5,7]. When we add all the numbers in both the diagonals, it comes up to 15 + 15 which i
s 30 which is our output
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1].trim();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This part is only for taking Inputs
const rowsAndcoloumns = parseInt(readLine()); // 3 is the no. of rows and coloumns
let arr = []; // we will push all the elements in this array
for (let i = 0; i < rowsAndcoloumns; i++) {
let elements = readLine().split(" ");
// console.log(elements); // [ '1', '2', '3' ]
// [ '4', '5', '6' ]
// [ '7', '8', '9' ] , all green color elements.
for (let j = 0; j < rowsAndcoloumns; j++) {
elements[j] = parseInt(elements[j])
}
// console.log(elements); // [ 1, 2, 3 ]
// [ 4, 5, 6 ]
// [ 7, 8, 9 ] , all yellow color elements.
arr.push(elements)
}
// console.log(arr); // [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] all yellow color elements
// The real operation starts here
let sum = 0;
for (let i = 0; i < arr.length; i++) // 0) i=0<3 true , go inside the forloop
// 1) i=1<3 true, go inside the forloop
// 2) i=2<3 true, go inside the forloop
{
const leftDiagonalElements = arr[i][i]; // 0) arr[0][0] = 1
// 1) arr[1][1] = 5
// 2) arr[2][2] = 9
sum += leftDiagonalElements; // 0) sum = 1
// 1) sum => 4+5 = 9
// 2) sum => 14 +9 = 23
const rightDiagonalElements = arr[i][arr.length - 1 - i]; //0) arr[0][2] = 3
// 1) arr[1][1] = 5
// 2) arr[2][0] = 7
sum += rightDiagonalElements; // 0) sum => 1+3 =4
// 1) sum => 9+5 =14
// 2) sum => 23+7 = 30
// after this exit the forloop and console
the sum.
}
console.log(sum); // 2) 30
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:
Comments
Post a Comment