CodeWars符号化問題2021年3月15日-矩形ボックスのボックス


[質問]


The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It's easy to see that the sum of the perimeters of these squares is : 4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:
alternative text

Hint:
See Fibonacci sequence
Ref:
http://oeis.org/A000045
The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.
perimeter(5) should return 80
perimeter(7) should return 216
(要約)上図に示すように、正方形が貼り付けられて矩形が形成されると、徐々に大きくなると、すべての矩形エッジの長さと4を乗じた値はreturnである.

[回答]

function perimeter(n) {
  const arr = [1];

  for(let i = 0; i < n; i++) {
    if(arr.length === 1) {
      arr.push(1);
    }
    else {
      arr.push(arr[arr.length - 1] + arr[arr.length - 2]);
    }
  }

  return arr.reduce((acc, n) => acc + n, 0) * 4;
}
規則的に見ると,最後の2つの矩形エッジの長さの和が次の矩形エッジの長さである.
最後にフィボナッチ数列を求め、すべてを加えて四乗で終わりました.