[英]Sum of Array of Odd numbers - JS
给定连续奇数的三角形:
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的奇数数组。接下来,我需要基于迭代长度(j)创建一个子数组,该长度从1-n(通过)。 然后最后将其推入主阵列。 然后使用reduce来获得该索引+ 1中所有值的总和(因为索引从1开始)。
知道我缺少什么以及如何进行这项工作吗?
大多数代码问题首先涉及一些分析,以便发现模式,然后可以将其转换为代码。 查看三角形,您将看到每行的总和遵循一个模式:
1: 1 === 1 ^ 3
2: 3 + 5 = 8 === 2 ^ 3
3: 7 + 9 + 11 = 27 === 3 ^ 3
... etc
因此,从上面的分析中,您可以看到您的代码可能会稍作简化-我不会发表答案,但请考虑使用Math.pow
。
无需任何循环。
function rowSumOddNumbers(n) {
// how many numbers are there in the rows above n?
// sum of arithmetic sequence...
let numbers_before_n_count = (n - 1) * n / 2;
let first_number_in_nth_row = numbers_before_n_count * 2 + 1;
let last_number_in_nth_row = first_number_in_nth_row + 2 * (n - 1);
// sum of arithmetic sequence again...
return n * (first_number_in_nth_row + last_number_in_nth_row) / 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.