简体   繁体   English

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

[英]How to check the sum of every lines in js

Okay, so if I have this: 好的,如果我有这个:

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

And what I want is to sum: 我想总结一下:

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

Like in tic tac toe, so my question is how can I do that without filling my code with 300 lines of code? 像井字游戏一样,所以我的问题是如何在不用300行代码填充代码的情况下做到这一点?

You could take two arrays with the start values of row and column and take the sum as index for calculating the wanted sum. 您可以将两个数组的行和列的起始值作为起始值,并将其作为索引来计算所需的总和。

  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; } 

Assuming the array is always 9 entries, this is easiest done by identifying the indexes manually. 假设数组始终为9个条目,则通过手动标识索引最容易做到。 The indexes are 0...8: 索引是0 ... 8:

0 1 2
3 4 5
6 7 8

We can then model the rows, columns and diagonals as such: 然后,我们可以像这样对行,列和对角线进行建模:

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 "/"

Then extract the sums from the array array : 然后从数组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]]

And now you can print your results with 现在,您可以使用

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}`);

In your question your array had string values, rather than numbers. 在您的问题中,数组具有字符串值,而不是数字。 This answer assumes the array contains numbers. 该答案假定数组包含数字。 I'll leave the conversion from strings to numbers as a google exercise. 我将保留从字符串到数字的转换作为Google练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM