상세 컨텐츠

본문 제목

[프로그래머스] 389478. 택배 상자 꺼내기 | 파이썬3, 구현

Coding Test/문제풀이

by yooputer 2025. 4. 14. 14:00

본문

 

 

프로그래머스

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

programmers.co.kr


문제 요약

1. 상자가 아래 그림과 같이 쌓여있음

    - w: 가로 상자 개수, n : 전체 상자 개수
2. num번째 상자를 꺼내려면 몇개의 상자를 꺼내야 하는가? 


해결 프로세스

1. 꺼내야하는 상자의 개수 = num번째 상자가 있는 열의 높이 - num번째 상자의 높이 + 1
👉 num번째 상자가 있는 열의 높이, num번째 상자의 높이를 구한다

 

2. num번째 상자가 있는 열의 높이 구하기

 

3. num번째 상자의 높이를 구하기
👉 num을 w로 나눈 후 올림


정답 소스코드

 

import math

def solution(n, w, num):
	# num번째 상자가 있는 열의 높이 구하기
    totalHeight = getTotalHeight(n, w, num)
    
    # num번째 상자의 높이 구하기
    numHeight = math.ceil(num / w)
    
    return totalHeight - numHeight + 1

def getTotalHeight(n, w, num):
    result = n // w
    remain = n % w
    indexN = getIndex(n, w)
    indexNum = getIndex(num, w)
    
    # remain이 0이면 모든 열의 높이 동일
    if n % w == 0:
        return result
    
    if result % 2 == 1: 
        if indexNum >= indexN:
            result = result + 1
    else:
        if indexN >= indexNum and remain > 0:
            result = result + 1
    
    return result

def getIndex(n, w):
    result = n // w
    remain = n % w
    
    if result % 2 == 1: # 홀수이면 오->왼
        return w - remain + 1
    else: # 짝수이면 왼 -> 오
        return remain

관련글 더보기