简体   繁体   English

奇数数组的总和-JS

[英]Sum of Array of Odd numbers - JS

Given the triangle of consecutive odd numbers: 给定连续奇数的三角形:

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

// Calculate the row sums of this triangle from the row index (starting at index 1) eg: //根据行索引(从索引1开始)计算此三角形的行总和,例如:

rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8

I tried to solve this using for loops: 我尝试使用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;
  });
}

My code above is not working. 我上面的代码无法正常工作。 Basically I was planning to 1st generate an array of odd numbers less than 30. Next I need to create a sub array base on the length of iteration (j) that would from 1 - n (passed). 基本上,我计划首先生成小于30的奇数数组。接下来,我需要基于迭代长度(j)创建一个子数组,该长度从1-n(通过)。 Then finally push it to the main array. 然后最后将其推入主阵列。 And then use reduce to get the sum of all the values in that index + 1 (since the index starts at 1). 然后使用reduce来获得该索引+ 1中所有值的总和(因为索引从1开始)。

Any idea what am I missing and how to make this work? 知道我缺少什么以及如何进行这项工作吗?

Most code problems involve some analysis first in order to spot patterns which you can then convert into code. 大多数代码问题首先涉及一些分析,以便发现模式,然后可以将其转换为代码。 Looking at the triangle, you'll see the sum of each row follows a pattern: 查看三角形,您将看到每行的总和遵循一个模式:

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

So from the analysis above you can see that your code could probably be simplified slightly - I won't post an answer, but think about using Math.pow . 因此,从上面的分析中,您可以看到您的代码可能会稍作简化-我不会发表答案,但请考虑使用Math.pow

No need for any loops. 无需任何循环。

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.

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