This was the question from hackerrack.com,
Explanation of the question
I solved the problem, but I am unable to find the optimistic solution, Can we do using object literals and 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 your code here
twoDimArr = getTwoDimention(input);
var firtDia = getFristDiagonal(twoDimArr);
var secDia = getSecondDiagonal(twoDimArr);
console.log(secDia - firtDia);
}
The actual working code is in jsfiddle
And also for some test case it is failing, when the number of elements vary on each row
Many thanks in advance
I think you mean the optimized solution.
Right now, you are iterating over the array 3 times, once to pull in your data (which takes more memory), and then twice to calculate each diagonal. One way to optimize this further would be to scan the file one line at a time instead of load it all into a 2D array, then calculate both diagonals at the same time on one pass.
So in sudo code:
JS Fiddle