gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:50:14 25 4
gpt4 key购买 nike

好的,如果我有这个:

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

我想要的是求和:

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

就像在井字游戏中一样,所以我的问题是如何在不使用 300 行代码填充我的代码的情况下做到这一点?

最佳答案

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

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

关于javascript - 如何检查js中每一行的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com