2

How can I make a sum of values in same row and column and make another array (can be one-dimensional) of results.

Array [
    [ 1, 1, 0, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 1, 1 ],
    [ 1, 1, 0, 1 ]
]
2
  • 1
    what you have tried so far?? Commented Jul 10, 2015 at 10:48
  • Something like...for (var iX = 0; iX < countInLine; iX++) { for (var iY = 0; iY < countInLine; iY++) { if($(this).hasClass("barrier") == false) { if (indexX == iX) { count++; } else if (indexY == iY) { count++; } } } Commented Jul 10, 2015 at 10:53

1 Answer 1

2
var res = [];  //the 1D array to hold the sums
var hArr =  [
   [ 1, 1, 0, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 1, 0, 1 ]
]; //your array


var vArr = []; //Now lets create an array of arrays with the columns of hArr

for (var j=0; j<hArr[0].length; j++) {
  var temp = [];
  for (var i=0; i<hArr.length; i++) {
      temp.push(hArr[i][j]);
  }
  vArr.push(temp);
}

//sum all the element in the line - Vertically and Horizontally
function SumVH (hInd, vInd) {
  var sum = 0;
  //add horizontal elements
  for(var i=0; i<hArr[hInd].length; i++) {
    sum += hArr[hInd][i];
  }
  //add vertical elements
  for(var i=0; i<vArr[vInd].length; i++) {
    sum += vArr[vInd][i];
  }
  //console.log("hInd="+hInd+" vInd="+vInd+" Sum="+sum);
  return sum;
}

// go through the main array and get result
var sumR = 0;
//sum of each row
for (var i=0; i<hArr.length; i++) {
   for (var j=0; j<hArr[i].length; j++) {
      sumR = SumVH(i,j) - (2 * hArr[i][j]);
      res.push(sumR);
   }   
}

Please check it now. The variable res holds the result

For my array writen above I want result array like 7, 7, 5, 7, 8, 8, 6, 8, 8, 8, 6, 8, 7, 7, 5, 7

Now the above code does not count the number itself in sum. But to get the result as your comment, please replace this line

sumR = SumVH(i,j) - (2 * hArr[i][j]);

with

sumR = SumVH(i,j);

Thank you.

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you very much - I'm going to try that in the moment.
This doesn't work as I expect. For my array writen above I want result array like 7, 7, 5, 7, 8, 8, 6, 8, 8, 8, 6, 8, 7, 7, 5, 7 but I get 4, 4, 3, 3, 2, 4, 4, 4.
Please visit this page. It describes what I want better. stackoverflow.com/questions/31294579/…
Ok, I got it. Doing it now.
Edited the answer. Please check it now. It should work. @JanChalupa
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.