簡體   English   中英

奇數數組的總和-JS

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM