본문 바로가기
코딩 테스트/[c언어] cos pro 2급 기출문제

[No.26] 타일 색칠 방법 구하기 / cos pro 2급 c언어 기출 문제

by M개발자 2021. 5. 15.
반응형

타일 색칠 방법 구하기


문제 설명

 

예를 들어 타일 길이가 11이면 "RRRGGBRRRGG"의 색으로 칠할 수 있습니다

 

타일 길이가 매개변수 tile_length로 주어질 때, 타일을 색칠한 순서를 문자열로 return 하는 solution 함수를 작성하려 합니다.

 

순서에 맞게 타일을 칠할 수 없다면 -1을 return 해주세요. 


예시

  tile_length return
예시 1 11 "RRRGGBRRRGG"
예시 2 16 "-1"

 


코드 해석 및 전체 코드

 

answer ) 타일을 색칠한 순서를 문자열로 return할 문자열 포인터

 

com ) 타일들.... 6개

 

if문 ) tile_length를 6으로 나누었을 때 나머지가 1이거나 2이거나 4이면 answer에 -1을 대입한다.

for in else ) 0 ~ tile_length - 1까지 반복하여 answer[i]에 com[ i % 6]를 대입한다. for문이 끝나면 tile_length에 '\0'(= null)를 넣는다.

 

예시 1

if

11 % 6 = 5
tile_length%6 == 1 X
tile_length%6 == 2 X
tile_length%6 == 4 X

 

else

i com[i % 6]
0 'R'
1 'R'
2 'R'
3 'G'
4 'G'
5 'B'
6 'R'
7 'R'
8 'R'
9 'G'
10 'G'

anwer은 "RRRGGBRRRGG"가 들어간다. 

 

예시 2

if

16 % 6 = 4
tile_length%6 == 1 X
tile_length%6 == 2 X
tile_length%6 == 4 O

if 조건문을 만족하므로 answer에는 "-1"이 들어간다. 

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
char* solution(int tile_length) {
	char* answer = (char*)malloc(sizeof(char) * (tile_length + 1));
	char com[6] = { 'R','R','R','G','G','B' };
	if (tile_length % 6 == 1 || tile_length % 6 == 2 || tile_length % 6 == 4)
		strcpy(answer, "-1");
	else {
		for (int i = 0; i < tile_length; i++)
			answer[i] = com[i % 6];
		answer[tile_length] = '\0';
	}
	return answer;
}
int main() {
	int tile_length1 = 11;
	char* ret1 = solution(tile_length1);


	printf("solution 함수의 반환 값은 %s 입니다.\n", ret1);

	int tile_length2 = 16;
	char* ret2 = solution(tile_length2);


	printf("solution 함수의 반환 값은 %s 입니다.\n", ret2);
}

cos pro 2급 기출문제

github

 

구름 goormedu COS PRO 2급 기출문제 - C언어

[3차] 문제6) 타일 색칠 방법 구하기

 

예시에 맞게 빈칸을 채울 수 있었지만 문제 자체를 이해하지 못했다................

반응형

댓글