Skip to content

Instantly share code, notes, and snippets.

@vincentntang
Created April 13, 2019 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincentntang/c5efd901e95e1a2abebb1d22d43a6f61 to your computer and use it in GitHub Desktop.
Save vincentntang/c5efd901e95e1a2abebb1d22d43a6f61 to your computer and use it in GitHub Desktop.
hackerrank diagnol difference
"use strict";
const fs = require("fs");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", inputStdin => {
inputString += inputStdin;
});
process.stdin.on("end", function() {
inputString = inputString
.replace(/\s*$/, "")
.split("\n")
.map(str => str.replace(/\s*$/, ""));
main();
});
function readLine() {
return inputString[currentLine++];
}
// Complete the diagonalDifference function below.
// Indices [row, column]
// if n=4, where n is number array length, i must be 3 or less
// diagnolA [0,0], [1,1], [2,2], [3,3], - [i,i] where i is iterated arr.length from 0
// diagnolB [3,0], [2,1], [1,2], [0,3] - [arr.length-i, i] ""
function diagonalDifference(arr) {
function absDiff(a, b) {
return Math.abs(a - b);
}
function arraySum(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
let diagnolA = [];
let diagnolB = [];
for (let i = 0; i < arr.length; i++) {
diagnolA.push(arr[i][i]);
diagnolB.push(arr[arr.length - 1 - i][i]);
}
return absDiff(arraySum(diagnolA), arraySum(diagnolB));
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const n = parseInt(readLine(), 10);
let arr = Array(n);
for (let i = 0; i < n; i++) {
arr[i] = readLine()
.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