본문 바로가기

algorithm/백준알고리즘

[백준알고리즘] 17478번: 재귀함수가 뭔가요? -C++

728x90

[백준알고리즘] 17478번: 재귀함수가 뭔가요? -C++

17478번: 재귀함수가 뭔가요? (acmicpc.net)

 

17478번: 재귀함수가 뭔가요?

평소에 질문을 잘 받아주기로 유명한 중앙대학교의 JH 교수님은 학생들로부터 재귀함수가 무엇인지에 대하여 많은 질문을 받아왔다. 매번 질문을 잘 받아주셨던 JH 교수님이지만 그는 중앙대

www.acmicpc.net

또다시 오랜만에 문제를 풀 수밖에 없었어서 실버 단계로 시작했다. 쉬워 보이는데 정답률이 왜 낮나 했더니 오타가 잘 발생하는 듯하다. 나도 그대로 복사했다고 생각했는데 IDE에서 어쩌다가 자동으로 조절되면서 오타가 발생했던 거였다.

 

참고로 오타는 Online Diff 사이트를 통해 직접 확인해서 고쳤다. 어디가 오타인지 모르겠는 분들은 그냥 diff 쓰시거나 온라인으로 쓰시면 될 것 같다.

- 링크 : Diffchecker - Compare text online to find the difference between two text files

 

Diffchecker

Compare text Diffchecker will compare text to find the difference between two text files.Just paste your files and click Find Difference

www.diffchecker.com

 

잘못된 점이나 부족한 점 지적해주시면 감사하겠습니다


문제 풀이

문제자체는 어렵지 않았다. 재귀적으로 같은 출력문들을 반복해서 출력해주면 됐고, 이때 재귀의 단계가 들어갈수록 "____"(언더바 4개)를 PREFIX로 붙여주면 된다.

 

구현하는 방법이야 여러 방법이 있고 쉬워서 따로 설명은 필요하지 않을 것 같다.

 

다만, 요즘 클린 코드 책을 읽고 있어서 최대한 함수를 나눠서 구현하는 연습을 할 겸 나눠서 작성했다. 이번 문제를 풀기 위한 코드가 간단한 기능이라고 하지만, 최대한 한 가지 기능만을 하도록 나눠서 작성했더니 하나로 합쳐져 있을 때보다 읽기 편한 것 같다.

 

아래는 소스코드다.

#include <cstdio>
#include <string>

void printHeader();
void printRecursive(const int iStep, const int iTarget);
void printQuestion(const int iStep);
void printRecursionStory(const int iStep);
void printAnswer(const int iStep);
void printFooter(const int iStep);
std::string getIndent(const int iStep);

static const std::string s_header = "어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.\n";
static const std::string s_question = "\"재귀함수가 뭔가요?\"\n";
static const std::string s_recursionStory[3] = {
	"\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.\n",
	"마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.\n",
	"그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"\n",
};
static const std::string s_answer = "\"재귀함수는 자기 자신을 호출하는 함수라네\"\n";
static const std::string s_footer = "라고 답변하였지.\n";
static const std::string s_indent = "____";

int main(void) {
	int iLoop = 0;
	scanf("%d", &iLoop);

	printHeader();

	printRecursive(1, iLoop);

	return 0;
}

void printHeader() {
	printf("%s", s_header.c_str());
}

void printRecursive(const int iStep, const int iTarget) {
	printQuestion(iStep);

	if (iStep <= iTarget) {
		printRecursionStory(iStep);
		printRecursive(iStep + 1, iTarget);	
	}
	else {
		printAnswer(iStep);
	}

	printFooter(iStep);
}

void printQuestion(const int iStep) {
	printf("%s", (getIndent(iStep) + s_question).c_str());
}

void printRecursionStory(const int iStep) {
	std::string sCurrentIndent = getIndent(iStep);

	for (int iIndex = 0; iIndex < 3; ++iIndex) {
		printf("%s", (sCurrentIndent + s_recursionStory[iIndex]).c_str());
	}
}

void printAnswer(const int iStep) {
	printf("%s", (getIndent(iStep) + s_answer).c_str());
}

void printFooter(const int iStep) {
	printf("%s", (getIndent(iStep) + s_footer).c_str());
}

std::string getIndent(const int iStep) {
	std::string sCurrentIndent;
	for (int iLoop = 1; iLoop < iStep; ++iLoop) {
		sCurrentIndent += s_indent;
	}
	return sCurrentIndent;
}
728x90