[프로그래머스] 실패율 (C++)

호이·2021년 11월 16일
post-thumbnail

요약

  • input: 게임의 총 stage 개수, 유저가 실패하고 있는 stage의 번호
  • output: 실패율이 높은 것부터 stage 번호를 반환.
  • 예시:
    int N = 5;
    vector<int> stages = {2, 1, 2, 6, 2, 4, 3, 3};
    vector<int> sol = {3, 4, 2, 1, 5};
    assert(solution(N, stages) == sol);

풀이

내 풀이

#include <vector>

using namespace std;

int countPassed (vector<int> vec, int findNum) {
  int count = 0;
  for (int elem : vec) {
    if (elem == findNum) {
      count++;
    }
  }
  return count;
}

void swap (float* a, float* b) {
  float temp = *a;
  *a = *b;
  *b = temp;
}

void bubbleSort(int N, vector<float>& valueVec, vector<float>& result) {
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N - 1; j++) {
      if (valueVec[j] < valueVec[j+1]) {
        swap(&result[j], &result[j+1]);
        swap(&valueVec[j], &valueVec[j+1]);
      }
    }
  }
}

vector<int> makeInt(vector<float>& floatVec) {
  vector<int> intVec(floatVec.begin(), floatVec.end());
  return intVec;
}

vector<int> solution(int N, vector<int> stages) {
  vector<float> failure, answer;
  int i = 1, passed = 0, total = stages.size();
  while (i <= N) {
    answer.push_back(i);
    passed = countPassed(stages, i);
    failure.push_back((float)passed/total);
    total -= passed;
    i++;
  }
  bubbleSort(N, failure, answer);
  return makeInt(answer);
}

int main() {
  int N = 5;
  vector<int> stages = {2, 1, 2, 6, 2, 4, 3, 3};
  vector<int> sol = {3, 4, 2, 1, 5};
  assert(solution(N, stages) == sol);
  return 0;
}
  • count, swap, bubbleSort, makeInt(float 배열을 int로 변환 후 반환) 의 기능을 하는 함수들을 바깥에 구현했다.

배운 점

  • Pair: 두 객체를 하나의 객체로 묶어주는 클래스. Pair<[Type], [Type]> 로 선언한다. 헤더는#include <utility>
  • make_pair(10, 20)로 만들 수 있다.

주절주절

  • 지금까지 배운 걸 갖가지 다 써서 풀었다. 그래서 끝까지 한번에 패스!!! 너무 재미지다!
profile
매일 부활하는 개복치

0개의 댓글