전설적인 "숫자 삼각형 문제"

제목에서 알 수 있듯이 이 많은 전설적인 문제를 가능한 한 간단하게 해결하고 싶습니다. 이번에는 이 문제를 해결하기 위해 JS를 선택하겠습니다(언제든지 JS를 선택하겠지만 LOL).

목표



기본적으로 두 개의 루프가 필요합니다. 첫 번째는 "행 수"(이것을 "메인 루프"라고 함)를 생성하고 두 번째는 "형제"(이를 "내부 루프"라고 함)를 생성합니다.

메인 루프는 다음과 같은 값을 생성해야 합니다.

**5**
**4**
**3**
**2**
**1**


그리고 내부 루프는 다음과 같이 첫 번째 루프를 완료해야 합니다.

5   **4**   **3**   **2**   **1**   
4   **3**   **2**   **1**   
3   **2**   **1**   
2   **1**   
1   


암호



그것을 달성하는 코드는 다음과 같습니다.

const pyramidize = (maxRows = 5) => {
  // the finalContainer will be our final string output
  let finalContainer = "";
  // say we define the max rows to 5, it means, we will
  // generate 5 lines of numbers.
  for (let currentRow = maxRows; currentRow > 0; currentRow--) {
    // make a new variable to store the current row strings
    let _currentRowContainer = "";
    // to generate the siblings we need to do a for-loop again
    // we will call it an inner-loop with initial index
    // (we will name it as currentSibling) equals to currentRow
    //
    // say the currentRow equals to 5, after the inner for-loop
    // finished you will get
    // 5
    // 4
    // 3
    // 2
    // 1
    for (
      let currentSibling = currentRow;
      currentSibling > 0;
      currentSibling--
    ) {
      // the first iteration (we assume the current row is 5)
      // will produce this string:
      //
      // _currentLevel = "5"
      //
      // the next iteration will be 4, so it will reproduce the
      // _currentLevel like this
      //
      // _currentLevel = "5 4"
      //
      // and so on until _currentLevel = "5 4 3 2 1"
      _currentRowContainer += `${currentSibling}\t`;
    }
    // after the inner-loop finished, simply concat the result
    // into our final container (don't forget to add \n for new line)
    finalContainer += `${_currentRowContainer}\n`;
  }
  return finalContainer;
};


이 코드는 변수를 다음과 같이 단순화하면 실제로 10줄 코드입니다.

const pyramidize = (n = 5) => {
  let final = "";
  for (let i = n; i > 0; i--) {
    let _temp = "";
    for (let j = i; j > 0; j--) {
      _temp += `${j}\t`;
    }
    final += `${_temp}\n`;
  }
  return final;
};


운동장



우리의 게으름을 위해 코드샌드박스를 가져왔습니다.

경고: 브라우저 충돌을 원하지 않는 한 1000보다 높은 값을 입력하지 마십시오(시간 복잡도를 통해 이러한 일이 발생할 수 있는 이유는 자세히 설명합니다). ㅋ!



시간 복잡도



마지막으로 지루한 부분. 이 코드가 어떻게 확장되는지 볼 것입니다.

플레이그라운드 콘솔을 통해 재현되는 각 행의 반복 횟수를 확인하세요. 다음은 반복 횟수의 공식입니다(n = rows).

(n * (n + 1)) / 2



공식을 단순화하면 다음을 얻을 수 있습니다.

(n^2 + n) / 2



복잡성 측정에서 constants don't really matter부터 상수를 빼면 다음과 같은 큰 O 표기법이 나타납니다.

O(n^2)



실제 계산은 실제 공식과 ​​big O 표기법 간에 매우 다를 수 있지만 다음은 그 차이가 얼마나 큰지에 대한 시뮬레이션입니다.



결론



전설적인 숫자 삼각형 문제는 몇 줄의 코드로 해결할 수 있습니다. 코딩하기는 쉽지만 확장성이 떨어집니다. 이 설명이 도움이 되길 바랍니다!

좋은 웹페이지 즐겨찾기