‡ CODING TEST STUDY ‡/º 프로그래머스
프로그래머스 [Lv1] | 모의고사
Trudy | 송연
2023. 7. 27. 16:23
세 개의 정수를 입력받은 후 크기가 큰 순서부터 출력 – 언제나 휴일 (ehpub.co.kr)
이렇게 세 개의 정수를 비교하는 코드가 있는데, 같은 수가 있을때는 더욱 복잡한 코드가 될 것 같아서 이렇게 하면 안되겠다 싶었다.
맞힌 개수를 담는 배열을 복사해서 sorting을 하면 됐구나
테스트 2개가 모두 통과돼서 기쁜 마음으로 제출을 했는데


문제의 코드는
#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; int find_index(vector<int> a, int c){ for(int i=0; i<a.size(); i++){ if(a[i] == c ) return i; } } vector<int> solution(vector<int> answers) { vector<int> answer; vector<int> hit(3); vector<int> su1 = {1, 2, 3, 4, 5}; vector<int> su2 = {2, 1, 2, 3, 2, 4, 2, 5}; vector<int> su3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; for(int i=0; i<answers.size(); i++){ if(su1[i % su1.size()] == answers[i]) hit[0]++; if(su2[i % su1.size()] == answers[i]) hit[1]++; if(su3[i % su1.size()] == answers[i]) hit[2]++; } vector<int> copy = hit; sort(copy.begin(), copy.end()); for(int i=0; i<hit.size(); i++){ cout << hit[i] <<" "; } cout << endl; for(int i=0; i<copy.size(); i++){ cout << copy[i] <<" "; } cout << endl; for(int i=2; i>=0; i--){ answer.push_back(find_index(hit, copy[i])+1); hit[ find_index(hit, copy[i]) ] = -1; cout << find_index(hit, copy[i])+1 << endl; if(copy[i] != copy[i-1]) break; } for(int i=0; i<hit.size(); i++){ cout << hit[i] <<" "; } cout << endl; for(int i=0; i<answer.size(); i++){ cout << answer[i] <<" "; } cout << endl; return answer; }
출력은 아래와 같음!
hit이 알맞게 수포자1, 수포자2, 수포자3의 맞은 개수를 나타낸다. (5 0 0)
그 다음 hit을 sort한 결과값도 알맞게 출력된 걸 확인할 수 있다 (0 0 5)
다음 줄은 find_index(hit, copy[i])+1한 값으로, 5개를 맞춘 주인이므로 1번 수포자이다. (1)
따라서 hit도 잘 바뀐것을 볼 수 있다. (-1, 0, 0)
따라서 answer 도 1로 맞다.
테스트 2도 동일하다!

제출하니까 왜 저리도 많이 틀린건지