코딩테스트/프로그래머스

[프로그래머스][product][Counter] 📍주사위 고르기

박소민 2025. 5. 18. 15:27
주사위 고르기
 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

  • 내 풀이
    • dice의 idx로 조합을 구하고, a구성을 가정하고 b는 자동 배치
    • 각각의 구성에서 한 리스트당 1개의 값씩 선택해서 합을 구하는 방법 → product
      • itertools.product 여러 리스트에서 각각 하나씩 골라 조합을 만드는 것
    • Counter를 통해 각 합의 갯수 구하기
    • a,b 각각의 구성에서 나올수 있는 합 = Counter.keys() 를 돌면서 a가 이길 수 있는 횟수를 구함
      • == i가 j보다 큰 경우
      • i가 나올 수 있는 횟수 * j 가 나올 수 있는 횟수
    • cnt 값을 비교해 나가면서 최고 승률의 구성으로 업데이트
from collections import Counter
from itertools import combinations, product

def solution(dice):
    answer = []
    n=len(dice)
    
    idx_comb_list=[list(idx_comb) for idx_comb in combinations(range(len(dice)),n//2)]
    
    cnt=0
    for a in idx_comb_list:
        b = [i for i in range(n) if i not in a]
        teamA=[]
        teamB=[]
        
        for i in a:
            teamA.append(dice[i])
        
        for i in b:
            teamB.append(dice[i])
        
        
        sumA=[sum(prod) for prod in product(*teamA)]
        sumB=[sum(prod) for prod in product(*teamB)]
        
        counterA=Counter(sumA)
        counterB=Counter(sumB)
        
        keysA=list(sorted(counterA.keys()))
        keysB=list(sorted(counterB.keys()))
        
        tmpA=0
        for i in keysA:
            for j in keysB:
                if i<=j:
                    break
                tmpA+=counterA[i]*counterB[j]
                
        if cnt<tmpA:
            cnt=tmpA
            answer=[x+1 for x in a]
                
    return answer