본문 바로가기

프로그램언어/C언어

cos pro2급 샘플문제1

문제1

A 학교에서는 단체 티셔츠를 주문하기 위해 학생별로 원하는 티셔츠 사이즈를 조사했습니다. 선택할 수 있는 티셔츠 사이즈는 작은 순서대로 "XS", "S", "M", "L", "XL", "XXL" 6종류가 있습니다.

 

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

 

매개변수 설명

학생별로 원하는 사이즈를 조사한 결과가 들어있는 배열 shirt_sizeshirt_size의 길이 shirt_size_lensolution 함수의 매개변수로 주어집니다.

* shirt_size_len1 이상 100 이하의 자연수입니다.

* shirt_size 에는 치수를 나타내는 문자열 "XS", "S", "M", "L", "XL", "XXL" 이 들어있습니다.

 

return 값 설명

티셔츠가 사이즈별로 몇 벌씩 필요한지 가장 작은 사이즈부터 순서대로 배열에 담아 return 해주세요.

* return 하는 배열에는 [ "XS" 개수, "S" 개수, "M" 개수, "L" 개수, "XL" 개수, "XXL" 개수] 순서로 들어있어야 합니다.

 

예시

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

 

예시 설명

* "XS""XL"은 각각 한 명씩 신청했습니다.

* "S""L"은 각각 두 명씩 신청했습니다.

* "M""XXL"을 신청한 학생은 없습니다.

 

따라서 순서대로 [1, 2, 0, 2, 1, 0]을 배열에 담아 return 하면 됩니다.

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int* solution(char* shirt_size[], int shirt_size_len) {

    // Write code here.

    int* answer;

    return answer;

}

 

// The following is main function to output testcase.

int main() {

    char* shirt_size[] = {"XS", "S", "L", "L", "XL", "S"};

    int shirt_size_len = 6;

    int* ret = solution(shirt_size, shirt_size_len);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is {");

    for(int i = 0; i < 6; i++){

        if (i != 0) printf(", ");

            printf("%d", ret[i]);

    }

    printf("} .\n");

}

 

정답 소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

#include <string.h>

 

int* solution(char* shirt_size[], int shirt_size_len) {

    int* size_counter = (int*)malloc(sizeof(int)*6);

    for(int i = 0; i < 6; ++i)

        size_counter[i] = 0;

        for(int i = 0; i < shirt_size_len; ++i) {

            if(strcmp(shirt_size[i],"XS") == 0)

                size_counter[0]++;

            else if(strcmp(shirt_size[i],"S") == 0)

                size_counter[1]++;

            else if(strcmp(shirt_size[i],"M") == 0)

                size_counter[2]++;

            else if(strcmp(shirt_size[i],"L") == 0)

                size_counter[3]++;

            else if(strcmp(shirt_size[i],"XL") == 0)

                size_counter[4]++;

            else if(strcmp(shirt_size[i],"XXL") == 0)

                size_counter[5]++;

        }

    return size_counter;

}

 

 

문제2

A 쇼핑몰에서는 회원 등급에 따라 할인 서비스를 제공합니다회원 등급에 따른 할인율은 다음과 같습니다(S = 실버, G = 골드, V = VIP)

 

등급 | 할인율 

 "S"  | 5% 

 "G"  | 10% 

 "V"  | 15% 

 

상품의 가격 price와 구매자의 회원 등급을 나타내는 문자열 grade가 매개변수로 주어질 때, 할인 서비스를 적용한 가격을 return 하도록 solution 함수를 완성해주세요.

 

매개변수 설명

상품의 가격 price와 회원 등급 grade가 매개변수로 주어집니다.

* price100 이상 100,000 이하의 100단위 자연수입니다.

* grade"S", "G", "V" 세 가지 중 하나입니다.

 

return 값 설명

할인한 가격을 return 하도록 solution 함수를 작성해주세요.

 

예시

| price  | grade | return |

| 2500  |    "V" |   2125 |

| 96900 |    "S" | 92055 |

 

예시 설명

예시 #1

2500원의 15%375원 입니다. 2500 - 375 = 2125 입니다.

 

예시 #2

96900원의 5%4845원 입니다. 96900 - 4845 = 92055 입니다.

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int price, char* grade) {

    // Write code here.

    int answer = 0;

    return answer;

}

 

// The following is main function to output testcase.

int main() {

    int price1 = 2500;

    char* grade1 = "V";

    int ret1 = solution(price1, grade1);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret1);

 

    int price2 = 96900;

    char* grade2 = "S";

    int ret2 = solution(price2, grade2);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret2);

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int price, char* grade) {

    int answer = 0;

    if (grade == "S")

        answer = price * 0.95;

    if (grade == "G")

        answer = price * 0.9;

    if (grade == "V")

        answer = price * 0.85;

    return answer;

}

 

 

문제3

시작 날짜와 끝 날짜가 주어질 때, 두 날짜가 며칠만큼 떨어져 있는지(D-day)를 구하려 합니다. 이를 위해 다음과 같이 3단계로 간단히 프로그램 구조를 작성했습니다. (, 윤년은 고려하지 않습니다.)

 

1단계. 시작 날짜가 11일로부터 며칠만큼 떨어져 있는지 구합니다.

2단계. 끝 날짜가 11일로부터 며칠만큼 떨어져 있는지 구합니다.

3단계. (2단계에서 구한 날짜) - (1단계에서 구한 날짜)를 구합니다.

 

시작 날짜의 월, 일을 나타내는 start_month, start_day, 끝 날짜의 월, 일을 나타내는 end_month, end_day가 매개변수로 주어질 때, 시작 날짜와 끝 날짜가 며칠만큼 떨어져 있는지 return 하도록 solution 함수를 작성했습니다. 이때, 위 구조를 참고하여 중복되는 부분은 func_a라는 함수로 작성했습니다. 코드가 올바르게 동작할 수 있도록 빈칸을 알맞게 채워주세요.

 

매개변수 설명

시작 날짜의 월, 일을 나타내는 start_month, start_day, 끝 날짜의 월, 일을 나타내는 end_month, end_daysolution 함수의 매개변수로 주어집니다.

 

* 잘못된 날짜가 주어지는 경우는 없습니다.

* 끝 날짜는 항상 시작 날짜보다 뒤에 있는 날이 주어집니다.

* 끝 날짜가 다음 해로 넘어가는 경우는 주어지지 않습니다.

* , start_month <= end_month를 항상 만족합니다.

* start_month = end_month라면 start_day <= end_day를 항상 만족합니다.

* 각 달의 날짜 수는 1월부터 순서대로 [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 이며, 윤년은 고려하지 않습니다.

 

return 값 설명

시작 날짜와 끝 날짜가 며칠만큼 떨어져 있는지 return 해주세요.

 

예시

start_month  start_day  end_month  end_day  return 
1 2 2 2 31

 

예시 설명

시작 날짜는 12일이고, 끝 날짜는 22일입니다.

 

* 12일은 11일로부터 1일만큼 지난 날입니다.

* 22일은 11일로부터 32일만큼 지난 날입니다.

* 32 - 1 = 31입니다.

* 따라서 12일과 22일은 31일만큼 떨어져 있습니다.

 

문제소스코드

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int func_a(int month, int day){
    int month_list[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int total = 0;
    for(int i = 0; i @@@; i++)
        total +=  @@@;
    total +=  @@@;
    return total - 1;
}

int solution(int start_month, int start_day, int end_month, int end_day) {
    int start_total = func_a(start_month, start_day);
    int end_total = func_a(end_month, end_day);
    return end_total - start_total;
}

// The following is main function to output testcase.
int main() {
    int start_month = 1;
    int start_day = 2;
    int end_month = 2;
    int end_day = 2;
    int ret = solution(start_month, start_day, end_month, end_day);
    
    // Press Run button to receive output. 
    printf("Solution: return value of the function is %d .\n", ret);
}

 

정답소스코드

더보기

#include <stdio.h> 
#include <stdbool.h> 
#include <stdlib.h> 

int func_a(int month, int day){ 
    int month_list[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
    int total = 0; 
    for(int i = 0; i < month - 1; ++i) 
        total += month_list[i]; 
    total += day; 
    return total - 1; 
} 

int solution(int start_month, int start_day, int end_month, int end_day) { 
    int start_total = func_a(start_month, start_day); 
    int end_total = func_a(end_month, end_day); 
    return end_total - start_total; 
}

 

 

문제4

자연수가 들어있는 배열이 있습니다. 이 배열에서 가장 많이 등장하는 숫자의 개수는 가장 적게 등장하는 숫자 개수의 몇 배인지 구하려 합니다. 이를 위해 다음과 같이 간단히 프로그램 구조를 작성했습니다.

 

1단계. 배열에 들어있는 각 자연수의 개수를 셉니다.

2단계. 가장 많이 등장하는 수의 개수를 구합니다.

3단계. 가장 적게 등장하는 수의 개수를 구합니다.

4단계. 가장 많이 등장하는 수가 가장 적게 등장하는 수보다 몇 배 더 많은지 구합니다.

 

, 몇 배 더 많은지 구할 때는 소수 부분은 버리고 정수 부분만 구하면 됩니다.

 

자연수가 들어있는 배열 arrarr의 길이 arr_len이 매개변수로 주어질 때, 가장 많이 등장하는 숫자가 가장 적게 등장하는 숫자보다 몇 배 더 많은지 return 하도록 solution 함수를 작성하려 합니다. 위 구조를 참고하여 코드가 올바르게 동작할 수 있도록 빈칸에 주어진 func_a, func_b, func_c 함수와 매개변수를 알맞게 채워주세요.

 

매개변수 설명

자연수가 들어있는 배열 arrarr의 길이 arr_lensolution 함수의 매개변수로 주어집니다.

* arr_len3 이상 1,000 이하의 자연수입니다.

* arr에는 1 이상 1,000이하의 자연수가 들어있습니다.

 

return 값 설명

배열에서 가장 많이 등장하는 숫자가 가장 적게 등장하는 숫자보다 몇 배 이상 많은지 return 해주세요.

 

* 가장 많이 들어있는 수의 개수와 가장 적게 들어있는 수의 개수가 같은 경우에는 1return 합니다.

 

예시

arr arr_len return
[1,2,3,3,1,3,3,2,3,2] 10 2

 

예시 설명

배열에 12, 23, 35개 들어있습니다.

 

* 가장 적게 들어있는 숫자 : 1 (2)

* 가장 많이 들어있는 숫자 : 3 (5)

 

31보다 2.5배 많이 들어있으며, 소수 부분을 버리고 2return 하면 됩니다.

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int* func_a(int arr[], int arr_len){

    int* counter = (int*)malloc(sizeof(int)*1001);

    for(int i = 0; i < 1001; i++)

        counter[i] = 0;

    for(int i = 0; i < arr_len; i++)

        counter[arr[i]]++;

    return counter;

}

 

int func_b(int arr[], int arr_len) {

    int ret = 0;

    for(int i = 0; i < arr_len; i++){

        if(ret < arr[i])

            ret = arr[i];

    }

    return ret;

}

 

int func_c(int arr[], int arr_len){

    const int INF = 1001;

    int ret = INF;

    for(int i = 0; i < arr_len; i++){

        if(arr[i] != 0 && ret > arr[i])

            ret = arr[i];

    } 

    return ret;

}

 

int solution(int arr[], int arr_len) {

    int* counter = func_@@@(@@@);

    int max_cnt = func_@@@(@@@);

    int min_cnt = func_@@@(@@@);

    return max_cnt / min_cnt;

}

 

// The following is main function to output testcase.

int main() {

    int arr[10] = {1, 2, 3, 3, 1, 3, 3, 2, 3, 2};

    int arr_len = 10;

    int ret = solution(arr, arr_len);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret);

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int* func_a(int arr[], int arr_len){

    int* counter = (int*)malloc(sizeof(int)*1001);

    for(int i = 0; i < 1001; ++i)

        counter[i] = 0;

    for(int i = 0; i < arr_len; ++i)

        counter[arr[i]]++;

    return counter;

}

 

int func_b(int arr[], int arr_len) {

    int ret = 0;

    for(int i = 0; i < arr_len; ++i){

        if(ret < arr[i])

            ret = arr[i];

    }

    return ret;

}

 

int func_c(int arr[], int arr_len){

    int ret = 1001;

    for(int i = 0; i < arr_len; ++i){

        if(arr[i] != 0 && ret > arr[i])

            ret = arr[i];

    }

    return ret;

}

 

int solution(int arr[], int arr_len) {

    int* counter = func_a(arr, arr_len);

    int max_cnt = func_b(counter, 1001);

    int min_cnt = func_c(counter, 1001);

    return max_cnt / min_cnt;

}

 

 

문제5

주어진 배열의 순서를 뒤집으려고 합니다.

예를 들어 주어진 배열이 [1, 4, 2, 3]이면, 순서를 뒤집은 배열은 [3, 2, 4, 1]입니다.

 

정수가 들어있는 배열 arrarr의 길이 arr_len이 매개변수로 주어졌을 때, arr를 뒤집어서 return 하도록 solution 함수를 작성하려 합니다. 빈칸을 채워 전체 코드를 완성해주세요.

 

매개변수 설명

정수가 들어있는 배열 arrarr의 길이 arr_lensolution 함수의 매개변수로 주어집니다.

* arr_len1 이상 100 이하의 자연수입니다.

* arr의 원소는 -100 이상 100 이하의 정수입니다.

 

return 값 설명

배열 arr의 순서를 뒤집어서 return 해주세요.

 

예시

arr arr_len return
[1, 4, 2, 3] 4  [3, 2, 4, 1] 

 

예시 설명

[1, 4, 2, 3]을 뒤에서부터 읽으면 3, 2, 4, 1입니다. 따라서 [1, 4, 2, 3]의 순서를 뒤집은 결과는 [3, 2, 4, 1]이 됩니다.

 

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int* solution(int arr[], int arr_len) {

    int left = 0;

    int right = arr_len - 1;

    while(@@@){

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

        left += 1;

        right -= 1;

    }

    return arr;

}

 

// The following is main function to output testcase.

int main() {

    int arr[4] = {1, 4, 2, 3};

    int arr_len = 4;

    int* ret = solution(arr, arr_len);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is {");

    for(int i = 0; i < 4; i++){

        if (i != 0) printf(", ");

            printf("%d", ret[i]);

    }

    printf("} .\n");

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int* solution(int arr[], int arr_len) {

    int left = 0;

    int right = arr_len - 1;

    while(left < right){

        int tmp = arr[left];

        arr[left] = arr[right];

        arr[right] = tmp;

        left += 1;

        right -= 1;

    }

    return arr;

}

 

 

문제6

369 게임은 여러 명이 같이하는 게임입니다. 게임의 규칙은 아래와 같습니다.

* 1부터 시작합니다.

* 한 사람씩 차례대로 숫자를 1씩 더해가며 말합니다.

* 말해야 하는 숫자에 3, 6, 9중 하나라도 포함되어있다면 숫자를 말하는 대신 숫자에 포함된 3, 6, 9의 개수만큼 손뼉을 칩니다.

 

어떤 수 number가 매개변수로 주어질 때, 1부터 number까지 369게임을 올바르게 진행했을 경우 박수를 총 몇 번 쳤는지를 return 하도록 solution 함수를 작성하려 합니다. 빈칸을 채워 전체 코드를 완성해주세요.

 

매개변수 설명

numbersolution 함수의 매개변수로 주어집니다.

* number10 이상 1,000 이하의 자연수입니다.

 

return 값 설명

1부터 number까지 369게임을 올바르게 진행했을 경우 박수를 총 몇 번을 쳤는지 return 해주세요.

 

예시

number | return 

   40     |    22 

 

예시 설명

3, 6, 9 : 각각 한 번 (+3)

13, 16, 19 : 각각 한 번 (+3)

23, 26, 29 : 각각 한 번 (+3)

30, 31, 32, 33, ..., 38, 39 : 십의 자리 열 번 + 일의 자리 세 번 (+13)

따라서, 3 + 3 + 3 + 13 = 22번의 박수를 칩니다.

 

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int number) {

    int count = 0;

    for (int i = 1; i <= number; i++) {

        int current = i;

        int temp = count;

        while (current != 0) {

            if (@@@){

                count++;

                printf("pair");

            }

            current /= 10;

        }

        if(temp == count)

            printf("%d", i);

        printf(" ");

    }

    printf("\n");

    return count;

}

 

// The following is main function to output testcase.

int main() {

    int number = 40;

    int ret = solution(number);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret);

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int number) {

    int count = 0;

    for (int i = 1; i <= number; i++) {

        int current = i;

        while (current != 0) {

            if (current % 10 == 3 || current % 10 == 6 || current % 10 == 9)

                count++;

            current /= 10;

        }

    }

    return count;

}

 

 

문제7

A 대학에서는 수준별 영어 강의를 제공하고 있습니다. 초급 영어 강의는 토익시험에서 650점 이상 800점 미만의 성적을 취득한 학생만을 수강대상으로 하고 있습니다. 초급 영어 강의에 수강신청한 사람이 10명일 때, 이 중에서 몇명이 수강 대상에 해당하는지 확인하려합니다.

 

수강신청자들의 토익 성적이 들어있는 배열 scoresscores의 길이 scores_len이 매개변수로 주어질 때, 수강 대상자들의 인원수를 return 하도록 solution 함수를 작성했습니다. 그러나, 코드 일부분이 잘못되어있기 때문에, 몇몇 입력에 대해서는 올바르게 동작하지 않습니다. 주어진 코드에서 _**한 줄**_만 변경해서 모든 입력에 대해 올바르게 동작하도록 수정해주세요.

 

매개변수 설명

수강신청자들의 토익 성적이 들어있는 배열 scoresscores의 길이 scores_lensolution 함수의 매개변수로 주어집니다.

* scores의 원소는 500 이상 990 이하의 정수입니다.

* scores_len10입니다.

 

return 값 설명

수강 대상자들의 인원수를 return 해주세요.

 

예시

scores  scores_len  return
[650, 722, 914, 558, 714, 803, 650, 679, 669, 800] 10 6

 

 예시 설명

점수 650 722 914 558 714 803 650 679 669 800
수강대상 O O X X O X O O O X

 

650점 이상 800점 미만의 성적을 취득한 학생이 수강대상이므로, 800점을 취득한 학생은 수강대상이 아닙니다.

따라서, 6명이 수강 대상입니다.

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int scores[], int scores_len) {

    int count = 0;

    for (int i = 0; i < scores_len; i++)

        if (650 <= scores[i] && scores[i] < 800)

            count += 1;

    return count;

}

 

 

문제8

앞에서부터 읽을 때와 뒤에서부터 읽을 때 똑같은 단어 또는 문장을 팰린드롬(palindrome)이라고 합니다. 예를 들어서 racecar, noon은 팰린드롬 단어입니다.

 

소문자 알파벳, 공백(" "), 그리고 마침표(".")로 이루어진 문장이 팰린드롬 문장인지 점검하려 합니다. 문장 내에서 알파벳만 추출하였을 때에 팰린드롬 단어이면 팰린드롬 문장입니다. 예를 들어, "Never odd or even."과 같은 문장은 팰린드롬입니다.

 

소문자 알파벳, 공백(" "), 그리고 마침표(".")로 이루어진 문장 sentence가 주어질 때 팰린드롬인지 아닌지를 return 하도록 solution 함수를 작성했습니다. 그러나, 코드 일부분이 잘못되어있기 때문에, 몇몇 입력에 대해서는 올바르게 동작하지 않습니다. 주어진 코드에서 _**한 줄**_만 변경해서 모든 입력에 대해 올바르게 동작하도록 수정해주세요.

 

매개변수 설명

소문자 알파벳, 공백(" "), 그리고 마침표(".")로 이루어진 문장 sentencesolution 함수의 매개변수로 주어집니다.

 

* sentence의 길이는 1이상 100이하입니다.

* sentence에는 적어도 하나의 알파벳이 포함되어 있습니다.

* setntence의 각 문자는 소문자 알파벳, 공백(" "), 또는 마침표(".")입니다.

 

return 값 설명

주어진 문장이 팰린드롬인지 아닌지를 return 해주세요.

 

예시

sentence  return 
"never odd or even." true 
"palindrome" false 

 

예시 설명

예시 #1

알파벳과 숫자만 추출하여 소문자로 변환해보면 "neveroddoreven"이 되며 이 단어는 팰린드롬입니다.

 

예시 #2

문장의 맨 앞 문자인 "p"와 맨 뒤 문자인 "e"가 다르므로 팰린드롬이 아닙니다.

 

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

bool solution(char* sentence) {

    char *str = (char *)malloc(sizeof(char) * 103);

    int len = 0;

    for(int i = 0; i < strlen(sentence); i++){

        char ch = sentence[i];

        if(ch != ' ' || ch != '.') str[len++] = ch;

    }

    for(int i = 0; i < len / 2; i++){

        if(str[i] != str[len - 1 - i]) return false;

    }

    return true;

}

 

// The following is main function to output testcase. The main function is correct and you shall correct solution function.

int main() {

    char sentence1[19] = "never odd or even.";

    bool ret1 = solution(sentence1);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %s .\n", ret1 == true ? "true" : "false");

 

    char sentence2[19] = "palindrome";

    bool ret2 = solution(sentence2);

 

    // Press Run button to receive output.

    printf("sSolution: return value of the function is %s .\n", ret2 == true ? "true" : "false");

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

#include <string.h>

 

bool solution(char* sentence) {

    char *str = (char *)malloc(sizeof(char) * 103);

    int len = 0;

    for(int i = 0; i < strlen(sentence); i++){

        char ch = sentence[i];

        if(ch != ' ' && ch != '.') str[len++] = ch;

    }

    for(int i = 0; i < len / 2; i++){

        if(str[i] != str[len - 1 - i]) return false;

    }

    return true;

}

 

 

문제9

알파벳 문자열이 주어질 때, 연속하는 중복 문자를 삭제하려고 합니다. 예를 들어, "senteeeencccccceeee"라는 문자열이 주어진다면, "sentence"라는 결과물이 나옵니다.

 

영어 소문자 알파벳으로 이루어진 임의의 문자열 characters가 매개변수로 주어질 때, 연속하는 중복 문자들을 삭제한 결과를 return 하도록 solution 함수를 작성하였습니다. 그러나, 코드 일부분이 잘못되어있기 때문에, 코드가 올바르게 동작하지 않습니다. 주어진 코드에서 _**한 줄**_만 변경해서 모든 입력에 대해 올바르게 동작하도록 수정하세요.

 

매개변수 설명

영어 소문자 알파벳으로 이루어진 임의의 문자열 characterssolution 함수의 매개변수로 주어집니다.

* characters는 알파벳 소문자로만 이루어져있습니다.

* characters의 길이는 10 이상 100 이하입니다.

 

return 값 설명

characters에서 연속하는 중복 문자를 제거한 문자열을 return 해주세요.

 

예시

characters  return 
"senteeeencccccceeee" "sentence"

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

char* solution(char* characters) {

    char* result = malloc(sizeof(char)*strlen(characters));

    int result_len = 0;

    result[0] = characters[0];

    result_len++;

    for (int i = 0; i < strlen(characters); i++) {

        if (characters[i - 1] != characters[i]) {

            result[result_len] = characters[i];

            result_len++;

        }

    }

    result[result_len] = NULL;

    return result;

}

 

// The following is main function to output testcase. The main function is correct and you shall correct solution function.

int main() {

    char* characters = "senteeeencccccceeee";

    char* ret = solution(characters);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %s .\n", ret);

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

char* solution(char* characters) {

    char* result = malloc(sizeof(char)*strlen(characters));

    int result_len = 0;

    result[0] = characters[0];

    result_len++;

    for (int i = 1; i < strlen(characters); i++) {

        if (characters[i - 1] != characters[i]) {

            result[result_len] = characters[i];

            result_len++;

        }

    }

    result[result_len] = NULL;

    return result;

}

 

문제10

평균은 자료의 합을 자료의 개수로 나눈 값을 의미합니다. 자연수가 들어있는 배열의 평균을 구하고, 평균 이하인 숫자는 몇 개 있는지 구하려합니다.

 

예를 들어 주어진 배열이 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]이라면, 평균은 5.5이므로 배열에서 평균 이하인 값은 5개입니다.

 

자연수가 들어있는 배열 datadata의 길이 data_len이 매개변수로 주어질 때, 배열에 평균 이하인 값은 몇 개인지 return 하도록 solution 함수를 작성했습니다. 그러나, 코드 일부분이 잘못되어있기 때문에, 몇몇 입력에 대해서는 올바르게 동작하지 않습니다. 주어진 코드에서 _**한 줄**_만 변경해서 모든 입력에 대해 올바르게 동작하도록 수정하세요.

 

매개변수 설명

자연수가 들어있는 배열 datadata의 길이 data_lensolution 함수의 매개변수로 주어집니다.

* data_len10 이상 100 이하의 자연수입니다.

* data의 원소는 1 이상 1,000 이하의 자연수입니다.

 

return 값 설명

평균보다 값이 작은 자연수는 몇개인지 return 해주세요.

 

예시

data data_len return
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 10 5
 [1, 1, 1, 1, 1, 1, 1, 1, 1, 10] 10 9

 

예시 설명

예시 #1

자료의 합은 55이며, 자료의 개수는 10개입니다. 따라서 평균은 55 / 10 = 5.5입니다.

주어진 배열에서 5.5보다 작은 숫자는 총 5개입니다.

 

예시 #2

자료의 합은 19이며, 자료의 개수는 10개입니다. 따라서 평균은 19 / 10 = 1.9입니다.

주어진 배열에서 1.9보다 작은 숫자는 총 9개입니다.

 

문제소스코드

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int data[], int data_len) {

    double total = 0;

    for(int i = 0; i < data_len; i++)

        total += data[i];

    int cnt = 0;

    double average = data_len / total;

    for(int i = 0; i < data_len; i++)

        if(data[i] <= average)

            cnt += 1;

    return cnt;

}

 

// The following is main function to output testcase. The main function is correct and you shall correct solution function.

int main() {

    int data1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int data_len1 = 10;

    int ret1 = solution(data1, data_len1);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret1);

 

    int data2[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 10};

    int data_len2 = 10;

    int ret2 = solution(data2, data_len2);

 

    // Press Run button to receive output.

    printf("Solution: return value of the function is %d .\n", ret2);

}

 

정답소스코드

더보기

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

 

int solution(int data[], int data_len) {

    double total = 0;

    for(int i = 0; i < data_len; ++i)

        total += data[i];

    int cnt = 0;

    double average = total / data_len;

    for(int i = 0; i < data_len; ++i)

        if(data[i] <= average)

            cnt += 1;

    return cnt;

}