rightToLeftDiagonal.js (*** Pay extra attention to the input taking process***)
/**
* Right to Left Diagonal
Write a function rightToLeftDiagonal which takes a matrix (as an array of arrays)
and returns an array of numbers containing elements of the anti-diagonal of the given matrix.
Input
First line contains an integer (say m), which denotes the size of the matrix.
This is followed by m lines, each containing m space separated elements.
Output
m lines containing one element each.
Note
The code for reading input and printing output is already given as part of the template.
You only need to write the function rightToLeftDiagonal.
Example
Input:
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4
7
10
13
Explanation
Anti-Diagonal is the diagonal of a matrix that leads from top-right to bottom-left,
here for the given square matrix the elements present in the anti-diagonal of the
matrix are [4, 7, 10, 13].
*/
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];
}
// -------- Do NOT edit anything above this line ----------
///////////////////////////////////////////////////////////////////////////////////////////////////////
// name your function as rightToLeftDiagonal
function rightToLeftDiagonal(matrix) {
let ans = []; // we will push the ans here
for (let i = 0; i < matrix.length; i++) {
// 0)i=0
// 1)i=1
// 2)i=2
// 3)i=3
ans.push(matrix[i][matrix.length - 1 - i]);
//0) matrix[0][4-1-0] and matrix[0][3] => 4
// 1) matrix[1][4-1-1] and matrix[1][2]=> 7
// 2) matrix[2][4-1-2] and matrix[2][1]=> 10
// 3) matrix[3][4-1-3] and matrix[3][0]=> 13
}
return ans //[ '4', '7', '10', '13' ] this ans will be returned to result
// variable who called the function
}
// Do not change anything below this line
// This part is only taking the input
let m = parseInt(readLine()); // 4
let matrix = [];// we will push all the array in this matrix
for (let row = 0; row < m; row++) {
let rowElements = readLine().split(" ");
// console.log(rowElements)
//[ '1', '2', '3', '4' ]
// [ '5', '6', '7', '8' ]
// [ '9', '10', '11', '12' ]
// [ '13', '14', '15', '16' ] all green color elements
matrix.push(rowElements);
//OR the below one both will give the same output
// matrix[row] = rowElements;
}
// console.log(matrix)
// [
// [ '1', '2', '3', '4' ],
// [ '5', '6', '7', '8' ],
// [ '9', '10', '11', '12' ],
// [ '13', '14', '15', '16' ]
// ]
let result = rightToLeftDiagonal(matrix); // invoking the rightToLeftDiagonal function
for (element of result) { // maybe this will convert the array as a line by line element
console.log(element);
}
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:

Comments
Post a Comment