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

[No.1] 단체 티셔츠 주문하기 / cos pro 2급 c언어 기출 문제

M개발자 2021. 5. 2. 22:40
반응형

단체 티셔츠 주문하기

 

문제 설명 

 

단체 티셔츠를 주문하기 위해 학생별로 원하는 티셔츠 사이즈를 조사했습니다.

이때 티셔츠 사이즈는 "XS", "S", "M", "L", "XL", "XXL"로 총 6종류가 있습니다.

학생별로 원하는 티셔츠 사이즈를 배열 shirt_size, shirt_size의 길이 shirt_size_len이 매개 변수로 주어질 때, 사이즈별로 티셔츠가 몇 벌씩 필요한지 가장 작은 사이즈부터 순서대로 배열에 담아 return하도록 solution 함수 완성하세요. 


예시

 

shirt_size shirt_size_len return
["XS", "S", "L", "L", "XL", "S"] 6 [1, 2, 0, 2, 1, 0]

코드 해석

 

shirt_size[i] 0 1 2 3 4 5
size [0]++ [1]++ [3]++ [3]++ [4]++ [2]++
int* solution(char* shirt_size[], int shirt_size_len) {
	int* size = (int*)malloc(sizeof(int) * 6);
   		 // 동적 메모리 할당
 		 // 왜인지는 모르겠으나 vs에서 실행할 시 동적할당을 주라는 런타임 오류 발생
    
	for (int i = 0; i < shirt_size_len; i++) {
		size[i] = NULL;
        //배열 메모리 초기화 
        
        //shirt_size[i]의 값과 "XS"이 같을 시 size[0] +1
        // if문 탈출 후 i++
		if (shirt_size[i] == "XS") {
			size[0]++;
		}
		else if (shirt_size[i] == "S") {
			size[1]++;
		}
		else if (shirt_size[i] == "M") {
			size[2]++;
		}
		else if (shirt_size[i] == "L") {
			size[3]++;
		}
		else if (shirt_size[i] == "XL") {
			size[4]++;
		}
		else if (shirt_size[i] == "XXL") {
			size[5]++;
		}
	}

	return size;
}

전체 코드 

더보기
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int* solution(char* shirt_size[], int shirt_size_len) {
	int* size = (int*)malloc(sizeof(int) * 6);
    
	for (int i = 0; i < shirt_size_len; i++) {
		size[i] = NULL;

		if (shirt_size[i] == "XS") {
			size[0]++;
		}
		else if (shirt_size[i] == "S") {
			size[1]++;
		}
		else if (shirt_size[i] == "M") {
			size[2]++;
		}
		else if (shirt_size[i] == "L") {
			size[3]++;
		}
		else if (shirt_size[i] == "XL") {
			size[4]++;
		}
		else if (shirt_size[i] == "XXL") {
			size[5]++;
		}
	}

	return size;
}

int main() {
	char* shirt_size[] = { "XS", "S", "L", "L", "XL", "S" };
	int shirt_size_len = 6;
	int* ret = solution(shirt_size, shirt_size_len);

	printf("solution 함수의 반환 값은 {");
	for (int i = 0; i < 6; i++) {
		if (i != 0) printf(", ");
		printf("%d", ret[i]);
	}
	printf("} 입니다.\n");
}

 


cos pro 2급 기출문제

github

 

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

반응형