如何检查js中每一行的总和

时间:2018-01-14 18:00:03

标签: javascript

好的,如果我有这个:

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];

我想要的是总结:

1 + 2 + 3 && 1 + 4 + 7 && 1 + 5 + 9

就像在tic tac toe中一样,我的问题是如何在不用300行代码填充代码的情况下做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用行和列的起始值取两个数组,并将总和作为计算所需总和的索引。

              15
            /
  1   2   3 |  6
  4   5   6 | 15
  7   8   9 | 24
--- --- --- \
 12  15  18   15

var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
    rows = [0, 3, 6].map(i => [0, 1, 2].reduce((s, j) => s + +array[i + j], 0)),
    cols = [0, 1, 2].map(i => [0, 3, 6].reduce((s, j) => s + +array[i + j], 0)),
    slash = [0, 4, 8].reduce((s, i) => s + +array[i], 0),
    backslash = [2, 4, 6].reduce((s, i) => s + +array[i], 0);
    
console.log(rows);       // -
console.log(cols);       // |
console.log(slash);      // /
console.log(backslash);  // \
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

假设数组总是9个条目,这是通过手动识别索引最简单的方法。索引是0 ... 8:

0 1 2
3 4 5
6 7 8

然后我们可以对行,列和对角线进行建模:

const rows = [
  [0, 1, 2], //Top row
  [3, 4, 5], //Middle row
  [6, 7, 8]  //Bottom row
];

const columns = [
  [0, 3, 6], //Left column
  [1, 4, 7], //Middle column
  [2, 5, 8]  //Right column
];

const bsDiag = [0, 4, 8]; //Backslash diagonal "\"
const fsDiag = [6, 4, 2]; //Forward slash diagonal "/"

然后从数组array中提取总和:

const rowSums = rows.map((row, index) => array[row[0]] + array[row[1]] + array[row[2]]);
const columnSums = columns.map((col, index) => array[col[0]] + array[col[1]] + array[col[2]]);
const bsDiagSum = array[bsDiag[0]] + array[bsDiag[1]] + array[bsDiag[2]]
const fsDiagSum = array[fsDiag[0]] + array[fsDiag[1]] + array[fsDiag[2]]

现在您可以使用

打印结果
rowSums.forEach((sum, index) => console.log(`Row ${index + 1} has sum: ${sum}`));
columnSums.forEach((sum, index) => console.log(`Column ${index + 1} has sum: ${sum}`));
console.log(`Backslash diagonal has sum ${bsDiagSum}`);
console.log(`Forward slash diagonal has sum ${fsDiagSum}`);

在你的问题中,你的数组有字符串值,而不是数字。这个答案假设数组包含数字。我将保留从字符串到数字的转换作为谷歌练习。