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 ]
]
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.
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.
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++; } } }