JavaScript - 相同行和列中值的总和

标签 javascript arrays loops multidimensional-array

我有一个包含数字 0 和 1 的 JavaScript 数组,我需要对同一行和同一列中的所有数字求和(如果我想象我的数组是二维的)。我想创建第二个数组,其中包含第一个数组中每个值的总和。

第一项的二维数组可视化(X-Y 值表):
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
(总和:索引 0 处的值 8;0(不包括值本身))

真实数组我有:
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1
(总和:索引 0 处的值为 8)

第二项的二维数组可视化:
1,1,1,1, 1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1
1,1,1,1,1

(总和:索引 1 处的值为 8;0)
这样我需要遍历整个数组。

带有零分隔符的第二项的二维数组可视化:
1,1,1,1,1
1,1,1,1,1
1,0,1,1,1
1,1,1,1,1
1,1,1,1,1
(总和:索引 1 处的值为 5;0)
零之后的值我不想算进去。

对于前面的表,结果表应该是这样的...
8,5,8,8,8
8,5,8,8,8
4,x,6,6,6
8,5,8,8,8
8,5,8,8,8

非常感谢您的帮助!

最佳答案

var res = [];  //the 1D array to hold the sums
var hArr =  [
   [ 1, 1, 1, 1 ],
   [ 1, 1, 1, 1 ],
   [ 1, 0, 0, 1 ],
   [ 1, 1, 0, 0 ]
]; //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
  //to the left
  for(var i=(vInd-1); i>=0; i--) {
    //if a 0 is found, break
    if (hArr[hInd][i] == 0) {
      break;
    }
    sum += hArr[hInd][i];
  }

  //to the right
  for(var i=(vInd+1); i<hArr[hInd].length; i++) {
    //if a 0 is found, break
    if (hArr[hInd][i] == 0) {
      break;
    }
    sum += hArr[hInd][i];
  }

  //add vertical elements
  //towards top
  for(var i=(hInd-1); i>=0; i--) {
    //if a 0 is found, break
    if(vArr[vInd][i] == 0) {
      break;
    }
    sum += vArr[vInd][i];
  }

  //towards bottom
  for(var i=(hInd+1); i<vArr[vInd].length; i++) {
    //if a 0 is found, break
    if(vArr[vInd][i] == 0) {
      break;
    }
    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);
      res.push(sumR);
   }   
}

请检查它并让我知道它是否像您期望的那样工作。 res 变量保存结果。

关于JavaScript - 相同行和列中值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294579/

相关文章:

javascript - 单击内部 <a> 链接时禁用 div 上的 onclick 事件(无 js 框架)

javascript - log4javascript web.config

javascript - 带有代理脚本的 IMacros

c - while循环与++变量

Java ScriptEngine - 禁用导入

java - 将对象数组转换为自定义类型数组

arrays - 使用排序对数组数组进行升序和降序排序

c - 动态字符数组 C 中的随机字符

bash - 在 bash 中一次循环遍历变量 2 个元素

javascript - 如何通过Javascript Post函数保护通过PHP运行的SQL