프로그래머스 42841 - 숫자 야구

문제 링크

접근 및 생각

  • baseball을 보고 answer의 후보를 찾는 방법이 힘들어, 그냥 100부터 999까지 탐색해서 주어진 baseball에 알맞은 숫자를 찾는 방법으로 코드를 작성했다.

  • baseball에 적절한 숫자인지 판단해주는 함수 check

       // cmp는 비교할 숫자
      bool check(vector<vector<int>> baseball, int cmp){
          for(int i = 0; i < baseball.size(); i++){
              // temp는 baseball에서 주어진 숫자
              int S = 0, B = 0, temp = baseball[i][0];
    
              // 스트라이크 판별
              if((cmp / 100) == (temp / 100))             S++;
              if(((cmp / 10) % 10) == ((temp / 10) % 10)) S++;
              if((cmp % 10) == (temp % 10))               S++;
    
              // 볼 판별
              if((temp / 100) == ((cmp / 10) % 10) || (temp / 100) == (cmp % 10))         B++;
              if(((temp / 10) % 10) == (cmp / 100) || ((temp / 10) % 10) == (cmp % 10))   B++;
              if((temp % 10) == (cmp / 100) || (temp % 10) == ((cmp / 10) % 10))          B++;
    
              // baseball에 적절하지 않은 것이 하나라도 있으면, return false
              if(S != baseball[i][1] || B != baseball[i][2])  return false;
          }
          // baseball에 모두 적절하므로 return true
          return true;
      }
  • 100부터 999까지의 탐색 방식을 조금 특이하게 했다.

      int answer = 0;
    
      // i는 100의 자리, j는 10의 자리, k는 1의 자리
      for(int i = 1; i <= 9; i++){
          for(int j = 1; j <= 9; j++){
              for(int k = 1; k <= 9; k++){
                  // 야구게임 조건 상 각 자리의 숫자가 겹치면 안된다.
                  if(i == j || j == k || k == i)  continue;
    
                  int cmp = 100 * i + 10 * j + k;
                  if(check(baseball, cmp))  answer++;
              }
          }
      }
      return answer;

코드

#include <bits/stdc++.h>
using namespace std;

bool check(vector<vector<int>> baseball, int cmp){
    for(int i = 0; i < baseball.size(); i++){
        int S = 0, B = 0, temp = baseball[i][0];

        if((cmp / 100) == (temp / 100))             S++;
        if(((cmp / 10) % 10) == ((temp / 10) % 10)) S++;
        if((cmp % 10) == (temp % 10))               S++;
        if((temp / 100) == ((cmp / 10) % 10) || (temp / 100) == (cmp % 10))         B++;
        if(((temp / 10) % 10) == (cmp / 100) || ((temp / 10) % 10) == (cmp % 10))   B++;
        if((temp % 10) == (cmp / 100) || (temp % 10) == ((cmp / 10) % 10))          B++;

        if(S != baseball[i][1] || B != baseball[i][2])  return false;
    }
    return true;
}

int solution(vector<vector<int>> baseball) {
    int answer = 0;
    for(int i = 1; i <= 9; i++){
        for(int j = 1; j <= 9; j++){
            for(int k = 1; k <= 9; k++){
                if(i == j || j == k || k == i)  continue;
                int cmp = 100 * i + 10 * j + k;
                if(check(baseball, cmp))  answer++;
            }
        }
    }
    return answer;
}

채점 결과

+ Recent posts