gpt4 book ai didi

javascript - 奇数数组之和 - JS

转载 作者:行者123 更新时间:2023-12-03 02:56:10 25 4
gpt4 key购买 nike

给定连续奇数组成的三 Angular 形:

1
3 5
7 9 11
13 15 17 19
21 23 25 27 29

//根据行索引(从索引 1 开始)计算该三 Angular 形的行和,例如:

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 的奇数数组。接下来,我需要根据迭代 (j) 的长度(从 1 - n(已通过))创建一个子数组。然后最后push到主数组中。然后使用reduce获得该索引中所有值的总和+1(因为索引从1开始)。

知道我缺少什么以及如何实现这项工作吗?

最佳答案

大多数代码问题首先需要进行一些分析,以便发现模式,然后将其转换为代码。查看三 Angular 形,您会发现每行的总和遵循某种模式:

1: 1 === 1 ^ 3
2: 3 + 5 = 8 === 2 ^ 3
3: 7 + 9 + 11 = 27 === 3 ^ 3
... etc

因此,从上面的分析中,您可以看到您的代码可能会稍微简化 - 我不会发布答案,但请考虑使用 Math.pow

关于javascript - 奇数数组之和 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47607866/

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