[Algorithm๐Ÿงฌ] ํ‚คํŒจ๋“œ ๋ˆ„๋ฅด๊ธฐ

7815 ๋‹จ์–ด algorithmalgorithm

๋ฌธ์ œ / ํ’€์ด.py

์ฝ”ํ…Œ๋ฅผ ์‘์‹œํ•ด์„œ ๊ทธ ๋‚  ํ’€์—ˆ๋˜ ๋‹จ ํ•œ๋ฌธ์ œ๋ผ...... ๊ธฐ์–ตํ•˜๊ณ  ์žˆ์—ˆ๋‹ค. ๊ทธ ๋•Œ๋Š” ๊ฑฐ๋ฆฌ ๊ณ„์‚ฐ์„ ๊ฐ™์€ ์„ธ๋กœ ์ค„์— ์žˆ์œผ๋ฉด... ์•„๋‹ˆ๋ฉด.. ์ด๋Ÿฐ ์‹์œผ๋กœ ๋ถ„๊ธฐ๋ฅผ ๋” ๋ณต์žกํ•˜๊ฒŒ ํ–ˆ์—ˆ๋Š”๋ฐ, ์ด๋ฒˆ์—” ์ข€ ๋” ๊น”๋”ํ•˜๊ฒŒ ํ•œ ๊ฒƒ ๊ฐ™๋‹ค.

# ์–ด๋–ค ์†์œผ๋กœ ์„ ํƒํ• ์ง€ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜.
def which_hand(left_loca, right_loca, end, main_hand):
    # ๊ฑฐ๋ฆฌ๊ฐ€ ์งง์€์ชฝ์„ ๋ฐ˜ํ™˜ํ•˜๊ณ 
    if distance(left_loca, end) < distance(right_loca, end):
        return "L"
    elif distance(left_loca, end) > distance(right_loca, end):
        return "R"
    # ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ™์œผ๋ฉด, ์ฃผ ์‚ฌ์šฉ ์†์„ ๋ฐ˜ํ™˜.
    else:
        if main_hand == "left":
            return "L"
        else:
            return "R"

# ํ˜„์žฌ ์œ„์น˜์™€ ๋ˆŒ๋Ÿฌ์•ผ ํ•  ์œ„์น˜๋ฅผ ๋„ฃ์œผ๋ฉด ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐํ•ด์ฃผ๋Š” ํ•จ์ˆ˜.
def distance(start, end):
    # 1 2 3 ์ด x์ถ• 0 1 2 ๋กœ
    # 1 4 7 ์ด y์ถ• 0 1 2 3 ์œผ๋กœ ๋งตํ•‘.
    start_x = (start+2) % 3
    start_y = int((start - 1) / 3)
    
    end_x = (end+2) % 3
    end_y = int((end-1) / 3)
    
    # ๊ฑฐ๋ฆฌ๊ฐ€ ์นธ ๊ธฐ์ค€์ด๋ฏ€๋กœ ์ด๋ ‡๊ฒŒ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ๋‹ค.
    dist = abs(start_x - end_x) + abs(start_y - end_y)
    return dist
    
    
def solution(numbers, hand):
    answer = ''
    left_loca = 10
    right_loca = 12
    
    for num in numbers:
        if num == 0:
            num = 11
        
        # 1, 4, 7 ์ด๋ฉด left
        if num % 3 == 1:
            left_loca = num
            answer += "L"
        
        # 3, 6, 9 ์ด๋ฉด right
        elif num % 3 == 0:
            right_loca = num
            answer += "R"
            
        # 2, 5, 8, 0 ์ด๋ฉด ๊ณ„์‚ฐ ํ›„์— ๊ฒฐ์ •.
        else:
            this_hand = which_hand(left_loca, right_loca, num, hand)
            # ์†์˜ ์œ„์น˜๊ฐ€ ์›€์ง์—ฌ์•ผํ•ด์„œ ์•„๋ž˜ ์‹๋„ ์ถ”๊ฐ€.
            if this_hand == "L":
                left_loca = num
            else:
                right_loca = num
            answer += this_hand
    
    
    return answer

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ