javascript - You are given a square matrix of size N times N. Calculate the absolute difference of the sums across the two main diagonals -


this question hackerrack.com,

explanation of question

enter image description here

i solved problem, unable find optimistic solution, can using object literals , come across optimal solution?

function gettwodimention(input){     var input = input.split('\n');     var twodimarr=[];     for(var n=0; n<input.length; n++){          var subarr = input[n].split(' ');        if(subarr.length > 1){            twodimarr.push(subarr)        }     }     return twodimarr; }  function getfristdiagonal(twodimarr){     var sum = 0;     for(var i=0; i<twodimarr.length; i++){         for(var j=i; j<=i; j++){            sum += parsefloat(twodimarr[i][j]);         }     }     return sum; } function getseconddiagonal(twodimarr){     var sum = 0;j=twodimarr.length-1;     for(var i=0; i<twodimarr.length; i++){             sum += parsefloat(twodimarr[i][j--]);     }     return sum; } function processdata(input) {     //enter code here     twodimarr = gettwodimention(input);     var firtdia = getfristdiagonal(twodimarr);     var secdia = getseconddiagonal(twodimarr);      console.log(secdia - firtdia);  }  

the actual working code in jsfiddle

fiddle demo

and some test case failing, when number of elements vary on each row

many in advance

i think mean optimized solution.

right now, iterating on array 3 times, once pull in data (which takes more memory), , twice calculate each diagonal. 1 way optimize further scan file 1 line @ time instead of load 2d array, calculate both diagonals @ same time on 1 pass.

so in sudo code:

for each row i=0     sumlefttoright += line[i];             sumrighttoleft += line[size-i-1];     print sumrighttoleft - sumlefttoright 

js fiddle


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -