matrixDiagonal.js with less dry run
/*Matrix Diagonal
Write a function which takes a 2 dimentional array of size nxn where n > 0 and changes its diagonal according to the following conditions
if an element e < 0 replace it with 0
If element e >= 0 replace it with 1
Input
The first line contains n, denoting the number of lists.
This is followed by n lines. Each line contains n integers separated by a space
Output
n lines, each line representing a list of numbers separated by a space.
Example
Input:
4
2 0 1 4
0 -1 1 10
0 0 0 0
1 2 3 4
Output:
1 0 1 4
0 0 1 10
0 0 1 0
1 2 3 1
*/
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 rows = parseInt(readLine()); // 4 is the no. of rows
let rowArray = []; // we will push the arrays in this matrix
for (let i = 0; i < rows; i++) {
subArray = readLine().split(" ");
// //console.log(subArray); [ '2', '0', '1', '4' ]
// [ '0', '-1', '1', '10' ]
// [ '0', '0', '0', '0' ]
// [ '1', '2', '3', '4' ] all green color element because they have not been converted to integer.
for (let j = 0; j < rows; j++) {
subArray[j] = parseInt(subArray[j]); //
}
// //console.log(subArray); [ 2, 0, 1, 4 ]
// [ 0, -1, 1, 10 ]
// [ 0, 0, 0, 0 ]
// [ 1, 2, 3, 4 ] all yellow color element now
rowArray.push(subArray);
}
//console.log(rowArray); //[ [ 2, 0, 1, 4 ], [ 0, -1, 1, 10 ], [ 0, 0, 0, 0 ], [ 1, 2, 3, 4 ] ]
// This is the actual operation
for (let i = 0; i < rows; i++) {
if (rowArray[i][i] >= 0)
rowArray[i][i] = 1;
else
rowArray[i][i] = 0;
}
//console.log(rowArray) [ [ 1, 0, 1, 4 ], [ 0, 0, 1, 10 ], [ 0, 0, 1, 0 ], [ 1, 2, 3, 1 ] ]
for (let i = 0; i < rowArray.length; i++) {
console.log(...rowArray[i]) // this ... is called spread operator
}
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:

Comments
Post a Comment