Level2 - 삼각 달팽이

손대중·2022년 7월 4일
0

문제 설명 및 링크

https://programmers.co.kr/learn/courses/30/lessons/68645?language=javascript

나의 풀이

크게 복잡한 부분은 없고, 결국 2차원 배열로 저 피라미드를 직접 구한 다음 리턴하면 됨.

다른 사람 풀이를 보니 다 비슷하게 푼 것 같은데, 코드 양이 더 짧은 좋은 코드들이 많다 ㅎㅎ

코드

모든 프로그래머스 문제 관련 코드들은 GitHub 링크 에 있음.

<script>
  function solution(n) {
      const triangle = [];
      const location = { x: 0, y: 0 };
      const condition = {
          count: 0,
          max: n,
          direction: 'down',
      };

      let num = 1;

      while (condition.max > 0) {
          if (!triangle[location.y]) {
              triangle[location.y] = [];
          }
          const arr = triangle[location.y];

          arr[location.x] = num;
          num++;

          condition.count++;

          if (condition.count >= condition.max) {
              condition.count = 0;
              condition.max--;

              condition.direction = 
                  condition.direction === 'down' ? 'right' :
                  condition.direction === 'right' ? 'up' : 'down';
          }

          if (condition.direction === 'down') {
              location.y++;
          } else if (condition.direction === 'right') {
              location.x++;
          } else if (condition.direction === 'up') {
              location.x--;
              location.y--;
          }
      }

      return triangle.flatMap(v => v);
  }
</script>

0개의 댓글