관리 메뉴

기억을 위한 기록들

[Code Wars] Build Tower(C++) 본문

Coding Test - cpp/Etc

[Code Wars] Build Tower(C++)

에드윈H 2024. 2. 22. 14:09

https://www.codewars.com/kata/576757b1df89ecf5bd00073b

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

Build a pyramid-shaped tower, as an array/list of strings, given a positive integer number of floors.
A tower block is represented with "*" character.


양의 정수 층수가 주어졌을 때, 피라미드 모양의 탑을 줄 배열/목록으로 짓습니다. 탑 블록은 "*" 문자로 표현됩니다.

 

 

나의 풀이 : 전체 필요한 칸이 얼마만큼인지 구하고 *이 몇개찍어야하는지에대해서 접근했었다

#include <string>
#include <vector>
#include <iostream>

std::vector<std::string> towerBuilder(unsigned nFloors) {
  
  int n=(nFloors*2)-1;
  std::vector<std::string> v;

  int min = n/2;
  int max = n/2;
  
  //전체 층
  for(unsigned int i=0;i<nFloors;i++)
  {
    std::string s;
    
    //해당 층에대한 판별
    for(int j=0;j<n;j++)
    {      
      if(min<=j && j <= max)
      {        
        s+="*";  
      }else
      {
        s+=" ";   
      }
    }
    
    v.push_back(s);
    min--;
    max++;    
  }
  
  return v;
}

 

 

다른사람의 풀이 :  내가 작성한 코드를 보고 마음에 들지 않았고, BestPractices를 보고 크게 한번 또 배웠다...

for문에 계산값을 두개로 만든 점과, string 생성자에 바로 문자열를 만들어서 간결하게 만들었다는 점이다.

#include <string>
#include <vector>

using namespace std;

vector<string> towerBuilder(unsigned nFloors) {
  vector <string> vect;
  for(unsigned i = 0, k = 1; i < nFloors; i++, k+=2)
    vect.push_back(string(nFloors-i-1, ' ') + string(k, '*') + string(nFloors-i-1, ' '));
  return {vect};
}