Skip to content

Instantly share code, notes, and snippets.

@MohamedGamil
Created April 17, 2022 06:15
Show Gist options
  • Save MohamedGamil/d6bf7784e3657ea53c479492b6c3881e to your computer and use it in GitHub Desktop.
Save MohamedGamil/d6bf7784e3657ea53c479492b6c3881e to your computer and use it in GitHub Desktop.
HackerRank / Diagonal Difference
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'diagonalDifference' function below.
*
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
function diagonalDifference(arr) {
const n = arr.length;
let leftSum = 0, rightSum = 0;
for(let idx = 0; idx < n; idx++) {
leftSum += arr[idx][idx];
rightSum += arr[idx][n - 1 - idx];
}
return Math.abs(leftSum - rightSum);
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine().trim(), 10);
let arr = Array(n);
for (let i = 0; i < n; i++) {
arr[i] = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
}
const result = diagonalDifference(arr);
ws.write(result + '\n');
ws.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment