Channi Studies

[C++] (Program) Word Pyramid/ 문자열 피라미드 본문

C++/프로젝트 (Project)

[C++] (Program) Word Pyramid/ 문자열 피라미드

Chan Lee 2023. 12. 15. 23:57

코드 설명

사용자로부터 문자열을 입력 받고, 이를 피라미드 형태로 출력하는 것입니다.

예시

일반적인 예제인 asterisk(*) 피라미드와는 다르게 반복문과 string에 대한 이해가 필요해서 조금 시간이 걸렸습니다.

 


(나의) 코드

#include <iostream>
#include <string>

using namespace std;

int main() {
  string choice{};

  cout << "Enter the string you want to make it to a pyramid: ";
  getline(cin,choice);                                     // melon
  string reversed_choice{choice};                          // melon
  reverse(reversed_choice.begin(), reversed_choice.end()); // nolem

  cout << "You entered: " << choice << endl << endl; // You entered: melon

  // for each row: 1, 2, 3, 4, 5
  for (size_t row{1}; row <= choice.size(); row++) {
    // making a blank for each row
    // for melon, choice.size() = 5, so blank goes
    // (5 - 1 = 4), (5 - 2 = 3), (5 - 3 = 2), (5 - 4 = 1), and (5 - 5 = 0)
    for (size_t blank{choice.size()}; blank > row; blank--) {
      cout << " ";
    }

    // num is for the first half (including the middle alphabet) string
    // through each rows, it outputs a string with 1, 2, 3, 4, and 5
    // characeters.
    for (size_t num{}; num < row; num++) {
      cout << choice.at(num);
    }

    // num2 is for the second half (excluding the middle alphabet) string
    // that means that it must produce -1 length than first half of the final
    // string through each rows, it outputs a reversed string in the index of 4,
    // (3-4), (2-4), (1-4), and (0-5).
    for (size_t num2{choice.size() - row + 1}; num2 < choice.size(); num2++) {
      cout << reversed_choice.at(num2);
    }

    cout << endl;
  }
}

 

 

출력 예시 1
출력 예시 2

원하던 대로 나온 것 같긴 하지만 뭔가 비효율적이고 불완전한 느낌이다.

처음에 너무 헷갈려서 피라미드를 만드는 과정을 큰 for loop 내부의 3가지 세부 과정으로 나누어서 생각했다.

1. 한 줄을 생성할 때 한번씩 반복하는 external for loop을 만들자.

2. 해당 for loop 내부에서 각 줄 당 빈 공간을 만드는 for loop을 구현하자.

3. 빈공간 이후에 문자열의 절반 (홀수일 시 가운데의 문자도 포함) 을 출력하는 for loop을 구현하자.

4. 마지막으로 뒤집힌 문자열의 뒤쪽 substring을 출력하자.

 

udemy 수업 assignment였는데 다 풀고 나서 모범 답안을 보니 내 코드보다 훨씬 직관적이고 깔끔했다.

 


모범답안

// Letter Pyramid
// Written by Frank J. Mitropoulos

#include <iostream>
#include <string>

int main() {
  std::string letters{};

  std::cout
      << "Enter a string of letters so I can create a Letter Pyramid from it: ";
  getline(std::cin, letters);

  size_t num_letters = letters.length();

  int position{0};

  // for each letter in the string
  for (char c : letters) {

    size_t num_spaces = num_letters - position;
    while (num_spaces > 0) {
      std::cout << " ";
      --num_spaces;
    }

    // Display in order up to the current character
    for (size_t j = 0; j < position; j++) {
      std::cout << letters.at(j);
    }

    // Display the current 'center' character
    std::cout << c;

    // Display the remaining characters in reverse order
    for (int j = position - 1; j >= 0; --j) {
      // You can use this line to get rid of the size_t vs int warning if you
      // want
      auto k = static_cast<size_t>(j);
      std::cout << letters.at(k);
    }

    std::cout << std::endl; // Don't forget the end line
    ++position;
  }

  return 0;
}