one line of code at a time

주사위 던지기로 중복순열, 순열, 중복조합, 조합 코드 짜기 본문

자료구조 || 알고리즘

주사위 던지기로 중복순열, 순열, 중복조합, 조합 코드 짜기

oloc 2024. 8. 8. 22:49

중복순열

N = 2 # 주사위 던지는 회수
numbers = [0 for _ in range(N)]

# 중복 순열
def dice1(cnt):
    if cnt == N:
        print(numbers)
        return

    for diceNum in range(1, 6+1):
        numbers[cnt] = diceNum
        dice1(cnt+1)

dice1(0)

 

순열

N = 3 # 주사위 던지는 회수
numbers = [0 for _ in range(N)]
isSelected = [False for _ in range(6+1)]

# 순열
def dice2(cnt):
    if cnt == N:
        print(numbers)
        return

    for diceNum in range(1, 6+1):
        if isSelected[diceNum]: # 이미 나온 주사위 눈과 중복되는지 체크
            continue

        numbers[cnt] = diceNum
        isSelected[diceNum] = True
        dice2(cnt+1)
        isSelected[diceNum] = False

dice2(0)

 

중복 조합

N = 2 # 주사위 던지는 회수
numbers = [0 for _ in range(N)]

# 중복조합
def dice3(cnt, start):
    if cnt == N:
        print(numbers)
        return

    for diceNum in range(start, 6+1):
        numbers[cnt] = diceNum
        dice3(cnt+1, diceNum)

dice3(0, 1)

 

조합

N = 2 # 주사위 던지는 회수
numbers = [0 for _ in range(N)]

# 조합
def dice4(cnt, start):
    if cnt == N:
        print(numbers)
        return

    for diceNum in range(start, 6+1):
        numbers[cnt] = diceNum
        dice4(cnt+1, diceNum+1)

dice4(0, 1)

'자료구조 || 알고리즘' 카테고리의 다른 글

Top 5 Graph Algorithms for Interview  (0) 2024.09.23
quick sort  (1) 2024.09.23
Graph + DFS  (0) 2024.08.18
Heap  (0) 2024.08.01
투포인터 알고리즘  (0) 2024.06.23