【发布时间】:2017-12-02 12:23:47
【问题描述】:
给定连续奇数的三角形:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
// 从行索引(从索引 1 开始)计算这个三角形的行和 例如:
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
我尝试使用 for 循环来解决这个问题:
function rowSumOddNumbers(n){
let result = [];
// generate the arrays of odd numbers
for(let i = 0; i < 30; i++){
// generate sub arrays by using another for loop
// and only pushing if the length is equal to current j
let sub = [];
for(let j = 1; j <= n; j++){
// if length === j (from 1 - n) keep pushing
if(sub[j - 1].length <= j){
// and if i is odd
if(i % 2 !== 0){
// push the i to sub (per length)
sub.push(i);
}
}
}
// push everything to the main array
result.push(sub);
}
// return sum of n
return result[n + 1].reduce(function(total, item){
return total += item;
});
}
我上面的代码不起作用。基本上,我计划首先生成一个小于 30 的奇数数组。接下来,我需要根据从 1 - n(通过)的迭代长度(j)创建一个子数组。然后最后将其推送到主数组。然后使用 reduce 得到该索引中所有值的总和 + 1(因为索引从 1 开始)。
知道我缺少什么以及如何使其工作吗?
【问题讨论】:
-
要理解为什么这不起作用,最好的办法是在调试器中单步执行代码,查看变量的值等。您的 IDE 中可能内置了一个(如果没有,请考虑查看另一个 IDE,例如 VS Code),在 Node 中有一个(它使用 Chrome 作为其 UI),当然在所有主要浏览器中也是如此。
-
因为这大概是一个作业,我不会发布代码,但是:有一个戏剧性地更简单的方法来解决这个问题;根本不需要数组。给定行的第一个数字是
n * (n - 1) + 1,当然该行的长度是n奇数,所以一个短的for循环或一些进一步的数学就可以了。
标签: javascript arrays