백준 | 숫자 야구

jeonghens·2024년 11월 29일

알고리즘: BOJ

목록 보기
94/125

백준 숫자 야구


# 정답

import sys
from itertools import permutations


n = int(sys.stdin.readline().strip())
questions = [sys.stdin.readline().strip().split() for _ in range(n)]

nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
possible_nums = [''.join(perm) for perm in permutations(nums, 3)]

for question in questions:
    ques_num, ques_strike, ques_ball = question
    ques_strike, ques_ball = int(ques_strike), int(ques_ball)

    next_possible_nums = []
    for num in possible_nums:
        strike, ball = 0, 0
        
        for i in range(3):
            if question[0][i] == num[i]:
                strike += 1
            elif question[0][i] in num:
                ball += 1
        
        if strike == ques_strike and ball == ques_ball:
            next_possible_nums.append(num)

    possible_nums = next_possible_nums

print(len(possible_nums))

아래와 같이 리스트를 순회하면서 원소를 제거하면 인덱스가 변동되어 일부 원소가 스킵되거나 예상치 못한 동작을 하게 된다.

for question in questions:
    for num in possible_nums:
        strike, ball = 0, 0
        
        for i in range(3):
            if question[0][i] == num[i]:
                strike += 1
            elif question[0][i] in num:
                ball += 1
        
        if strike == question[1] and ball == question[2]:
            continue
        else:
            possible_nums.remove(num)
profile
알고리즘이나 SQL 문제 풀이를 올리고 있습니다. 피드백 환영합니다!

0개의 댓글