CodeWars 코딩 문제 2021/03/15 - Perimeter of squares in a rectangle

이호현·2021년 3월 15일
0

Algorithm

목록 보기
89/138

[문제]

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 = 80

Could 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;
}

규칙을 보면 마지막 두 사각형의 변의 길이 합이 다음 사각형 변의 길이가 된다.
결국 피보나치 수열 구해서 다 더하고, 4 곱하면 끝.

profile
평생 개발자로 살고싶습니다

0개의 댓글