Created
January 24, 2019 08:27
-
-
Save acro5piano/dc10a77312155a3e515f1748f232c1cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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