Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Created January 24, 2019 08:27
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 acro5piano/dc10a77312155a3e515f1748f232c1cd to your computer and use it in GitHub Desktop.
Save acro5piano/dc10a77312155a3e515f1748f232c1cd to your computer and use it in GitHub Desktop.
'use strict';
const fs = require('fs');
const assert = require('assert').strict;
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.
function diagonalDifference(arr) {
const get = (plus, col = plus ? 0 : arr.length - 1, row = 0, res = 0) => {
if (row === arr.length) {
return res
}
return get(
plus,
plus ? col + 1 : col - 1,
row + 1,
res + arr[row][col],
)
}
return Math.abs(get(true) - get(false))
}
function unittest() {
let input = [[ 11, 2, 4 ], [ 4, 5, 6 ], [ 10, 8, -12 ]]
let expected = 15
assert.strictEqual(15, diagonalDifference(input))
}
unittest()
function main() {
const ws = fs.createWriteStream('/dev/stdout');
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