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

[No.19] 투표에 대한 후보 찾기 / cos pro 2급 c언어 기출 문제

M개발자 2021. 5. 12. 21:24
반응형

투표에 대한 후보 찾기


문제 설명

 

N명의 후보에 대해 투표한 결과가 들어있는 배열이 있습니다.

예를 들어 5명의 후보에 대해 투표를 진행한 결과를 통해 정확히 K표를 받은 후보는 몇 명인지 구하려 합니다. 

 

투표 결과가 들어있는 배열 votes와 votes의 길이 votes_len, 후보의 수 N, 표의 개수 K가 매개변수로 주어질 때, K 표를 받은 후보는 몇 명인지 return 하도록 solution 함수를 작성했습니다. 

그러나, 코드 일부분이 잘못되어있기 때문에 올바르게 동작하지 않으므로 한 줄만 변경해서 올바르게 동작하도록 수정하세요.

 


예시

 

votes votes_len N K return
[2, 5, 3, 4, 1, 5, 1, 5, 5, 3] 10 5 2 2

 


수정해야 할 코드

더보기
int solution(int votes[], int votes_len, int N, int K) {
    int counter[11] = {0};
    for(int i = 0; i < votes_len; ++i)
        counter[votes[i]] += 1;
    int answer = -1;
    for(int i = 0; i <= N; ++i)
        if(counter[i] == K)
            answer += 1;
    return answer;
}

 

수정

 

int answer = -1;
→ int answer = 0;

어떤 값을 더할 경우 초기화 값을 0으로 설정하고 

어떤 값을 곱하거나 나눌 경우 초기화 값을 1로 주어야 한다.  

 

answer는 K 표를 받은 후보가 몇 명인지 return할return 할 값으로 -1로 할 시 return 할 값의 -1된 값을 return 한다. 

 

코드 해석 및 전체 코드

 

counter[11] ) 각 후보가 받은 표의 개수를 담을 배열이다.

 

for문 1 ) 0 ~ votes_len -1까지 반복하여 votes[i]의 값을 counter 배열의 방과 같은 방에 넣는다. 

votes[0] votes[1] votes[2] votes[3] votes[4] votes[5] votes[6] votes[7] votes[8] votes[9]
2 5 3 4 1 5 1 5 5 3
counter[2]++ counter[5]++ counter[3]++ counter[4]++ counter[1]++ counter[5]++ counter[1]++ counter[5]++ counter[5]++ counter[3]++

 

answer ) K 표를 받은 후보의 인원을 return 할 변수

 

for 문 2 ) 0 ~ N까지 반복하여 counter[i]의 값과 K의 값이 같다면 answer에 1을 더한다.

K = 2

counter[0] 0  
counter[1] 2 +1
counter[2] 1  
counter[3] 2 +1
counter[4] 1  
counter[5]
4  
counter[6] 0  
...
counter[10] 0  

 

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

int solution(int votes[], int votes_len, int N, int K) {
    int counter[11] = { 0 };
    for (int i = 0; i < votes_len; ++i)
        counter[votes[i]] += 1;
    int answer = 0;
    for (int i = 0; i <= N; ++i)
        if (counter[i] == K)
            answer += 1;
    return answer;
}

int main() {
    int votes[10] = { 2, 5, 3, 4, 1, 5, 1, 5, 5, 3 };
    int votes_len = 10;
    int N = 5;
    int K = 2;
    int ret = solution(votes, votes_len, N, K);

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

cos pro 2급 기출문제

github

 

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

[2차] 문제9) 투표에 대한 후보 찾기

반응형