코드짜는 노인네

[프로그래머스] (카카오 인턴) 키패드 누르기 - 문제해결과정 본문

코딩 테스트

[프로그래머스] (카카오 인턴) 키패드 누르기 - 문제해결과정

ikohong 2022. 9. 9. 20:52
728x90
반응형

[프로그래머스] (카카오 인턴) 키패드 누르기 - 문제해결과정


문제 : 
- 전화 키패드를 왼손과 오른손 엄지손가락만으로 번호를 누를 때 해당 번호를 어떤 손의 엄지손가락이 누르는지 확인하는 문제
조건 : 
0. 맨 처음 왼손 엄지손가락은 '*' 키패드에 오른손 엄지손가락은 '#' 키패드 위치에서 시작
1. 엄지손가락은 상하좌우 4가지 방향으로만 이동할 수 있으며 키패드 이동 한 칸은 거리로 1에 해당합니다.
2. 왼쪽 열의 3개의 숫자 1, 4, 7을 입력할 때는 왼손 엄지손가락을 사용합니다.
3. 오른쪽 열의 3개의 숫자 3, 6, 9를 입력할 때는 오른손 엄지손가락을 사용합니다.
4. 가운데 열의 4개의 숫자 2, 5, 8, 0을 입력할 때는 두 엄지손가락의 현재 키패드의 위치에서 더 가까운 엄지손가락을 사용합니다.
    4-1. 만약 두 엄지손가락의 거리가 같다면, 오른손잡이는 오른손 엄지손가락, 왼손잡이는 왼손 엄지손가락을 사용합니다.
EX >
numbers = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5]
hand = "right"
answer = "LRLLLRLLRRL"

나의 문제 해결 과정 (에러과정)


숫자 키패드는 '0,1,2,3,4,5,6,7,8,9,*,#'이 있습니다. 일단 문제의 조건을 자세히 보지 않고, 단순하게 먼저 생각을 했습니다. '왼손잡이','오른손잡이' 상관없이 '3,6,9'는 오른손 엄지손가락으로 터치, '1,4,7'은 왼손 엄지손가락으로 터치를 하며, '0,2,5,8'의 숫자는 오른손잡이일 경우, 오른손 엄지손가락이 터치, 왼손잡이 일 경우, 왼손 엄지손가락이 터치하도록 코드를 작성했습니다.

if hand == "right":
    for i in numbers:
        if i == 3 or i == 6 or i == 9 or i == 2 or i == 5 or i == 8 or i == 0:
            answer += "R"
        else:
            answer += "L"

if hand == "left":
    for i in numbers:
        if i == 1 or i == 4 or i == 7 or i == 2 or i == 5 or i == 8 or i == 0:
            answer += "L"
        else:
            answer += "R"

당연히 위의 코드를 실행하게 되면, 원하는 결과값을 가질수가 없습니다. 여기서부터 조건에 따라 코드를 작성하기 시작했습니다.

Right_hand = ""
Left_hand = ""

if hand == "right":
    for i in numbers:
        if i == 3 or i == 6 or i == 9:
            answer += "R"
            Right_hand = i
        elif i == 1 or i == 4 or i == 7:
            answer += "L"
            Left_hand = i
        else:
            if i == 2:
                if Left_hand == 1 and Right_hand != 3:
                    answer += "L"
                else:
                    answer += "R"
            elif i == 5:
                if Left_hand == 4 and Right_hand != 6:
                    answer += "L"
                else:
                    answer += "R"
            elif i == 8:
                if Left_hand == 7 and Right_hand != 9:
                    answer += "L"
                else:
                    answer += "R"
            elif i == 0:
                if Left_hand == 7 and Right_hand != 9:
                    answer += "L"
                else:
                    answer += "R"
            
if hand == "left":
    for i in numbers:
        if i == 1 or i == 4 or i == 7:
            answer += "L"
            Left_hand = i
        elif i == 3 or i == 6 or i == 9:
            answer += "R"
            Right_hand = i
        else:
            if i == 2:
                if Right_hand == 3 and Left_hand != 1:
                    answer += "R"
                else:
                    answer += "L"
            elif i == 5:
                if Right_hand == 6 and Left_hand != 4:
                    answer += "R"
                else:
                    answer += "L"
            elif i == 8:
                if Right_hand == 9 and Left_hand != 7:
                    answer += "R"
                else:
                    answer += "L"
            elif i == 0:
                if Left_hand == 9 and Right_hand != 7:
                    answer += "R"
                else:
                    answer += "L"

여기서 생각을 한것은 중간번호 '0,2,5,8'번호를 누를때 조건을 추가해야된다고 생각을 했습니다. 해당 번호를 눌러야 될 경우, 해당번호의 상하좌우에 손가락이 있는지 확인을 해야되었기에, 변수 'Right_hand','Left_hand'를 만들어서, 키패드 번호를 입력할때 마다, 해당 조건에 맞는 엄지손가락의 위치에 따라, 변수에 번호를 넣어서 왼손 엄지손가락, 오른손 엄지손가락의 위치를 파악할 수 있도록 했습니다. 그리고, 가운데줄 번호를 입력 할 때 마다 손가락의 위치에 따른 조건을 작성해서 왼손 엄지손가락 혹은 오른손 엄지 손가락을 누르도록 조건을 달았습니다. 허나, 이렇게 했을경우, 문제에 조건을 완벽하게 만족시킬수 없어서, 원하는 기댓값이 나오지 않고, 이상한 결과값이 나와 다른 방법을 찾아야 했습니다.

import math

# 2차원 배열로 키패드 위치 파악
def phone_number_index(number):
    phone_numbers = [[1,2,3],[4,5,6],[7,8,9],["*",0,"#"]]
    for i in range(0, len(phone_numbers)):
        for j in range(0, len(phone_numbers[i])):
            if phone_numbers[i][j] == number:
                return [i,j]
                
Left_hand = [3,0]
Right_hand = [3,2]

# 왼손, 오른손 엄지손가락과 numbers 가운데줄 번호의 거리 구하는 메소드
def center_Length(left,right,center):
    if left == [] or right == []:
        return None
    
    left_x_location = left[0]
    left_y_location = left[1]
    
    right_x_location = right[0]
    right_y_location = right[1]
    
    center_x_location = center[0]
    center_y_location = center[1]
    
    l_c_x = abs(left_x_location - center_x_location)
    l_c_y = abs(left_y_location - center_y_location)
    
    r_c_x = abs(right_x_location - center_x_location)
    r_c_y = abs(right_y_location - center_y_location)
    
    l_c_length = math.sqrt(l_c_x+l_c_y)
    r_c_length = math.sqrt(r_c_x+r_c_y)

    if l_c_length < r_c_length:
        return "left"
    elif l_c_length > r_c_length:
        return "right"
    else:
        return "same"

그래서 생각을 한것이 '키패드'를 2차원 배열로 만들어서 해당 키패드로 손가락이 이동했을 경우, 해당값이 있는 배열의 'index'를 return해, 해당 숫자의 위치를 파악할 수 있도록 코드를 작성했습니다. 그리고 조건을 보면, '맨 처음 왼손 엄지손가락은 '*' 키패드에 오른손 엄지손가락은 '#' 키패드 위치에서 시작'이라는 조건이 있어 'Left_hand = [3,0]','Right_hand = [3,2]'로 지정을 해놓았습니다. 그리고, 'numbers'에서 가운데줄 숫자가 나왔을 경우, 현재 위치하고 있는 왼손,오른손의 엄지손가락의 위치와, 가운데줄의 숫자 위치의 거리를 계산해서, 거리에 따라 'left','right','same'으로 리턴하도록 만들었습니다.

반응형

최종 코드 결과물


import math

def solution(numbers, hand):

    answer = ""

    def phone_number_index(number):
        phone_numbers = [[1,2,3],[4,5,6],[7,8,9],["*",0,"#"]] 
        for i in range(0, len(phone_numbers)):
            for j in range(0, len(phone_numbers[i])):
                if phone_numbers[i][j] == number:
                    return [i,j]

    def center_Length(left,right,center):
        if left == [] or right == []:
            return None

        left_x_location = left[0]
        left_y_location = left[1]

        right_x_location = right[0]
        right_y_location = right[1]

        center_x_location = center[0]
        center_y_location = center[1]

        l_c_x = abs(left_x_location - center_x_location)
        l_c_y = abs(left_y_location - center_y_location)

        r_c_x = abs(right_x_location - center_x_location)
        r_c_y = abs(right_y_location - center_y_location)

        l_c_length = math.sqrt(l_c_x+l_c_y)
        r_c_length = math.sqrt(r_c_x+r_c_y)

        if l_c_length < r_c_length:
            return "left"
        elif l_c_length > r_c_length:
            return "right"
        else:
            return "same"

    Left_hand = [3,0]
    Right_hand = [3,2]

    if hand == "right":
        for i in numbers:
            if i == 3 or i == 6 or i == 9:
                answer += "R"
                Right_hand = phone_number_index(i)
            elif i == 1 or i == 4 or i == 7:
                answer += "L"
                Left_hand = phone_number_index(i)
            else:
                if Right_hand == i:
                    answer += "R"
                elif Left_hand == i:
                    answer += "L"
                else:
                    center_position = phone_number_index(i)
                    center_result = center_Length(Left_hand,Right_hand,center_position)
                    if center_result == "left" or Left_hand == phone_number_index(i):
                        answer += "L"
                        Left_hand = phone_number_index(i)
                    else:
                        answer += "R"
                        Right_hand = phone_number_index(i)

    if hand == "left":
        for i in numbers:
            if i == 3 or i == 6 or i == 9:
                answer += "R"
                Right_hand = phone_number_index(i)
            elif i == 1 or i == 4 or i == 7:
                answer += "L"
                Left_hand = phone_number_index(i)
            else:
                center_position = phone_number_index(i)
                center_result = center_Length(Left_hand,Right_hand,center_position)
                if center_result == "right" or Right_hand == phone_number_index(i):
                    answer += "R"
                    Right_hand = phone_number_index(i)
                else:
                    answer += "L"
                    Left_hand = phone_number_index(i)

    return answer

 

 

변수 'hand'에서 오른손잡이인지, 왼손잡이 인지를 먼저 파악을 한 다음, '1,4,7'은 왼손 엄지손가락, '3,6,9'는 오른손 엄지손가락, '0,2,5,8'은 입력전 왼손, 오른손의 엄지손가락과의 거리를 계산한 다음, 거리에 따라 어떤 손가락으로 누를지 결정할 수 있도록 조건을 달았습니다. 테스트는 통과했지만, 코드를 좀 더 간결하게 만들수 있었을꺼 같다는 아쉬움이 남네요. 언제가 코드를 작성하고, 통과한 다음, 다른분들의 풀이를 보면, '내가 지금까지 뭐했나..'라는 생각을 항상 하게 되네요. 좀 더 깔끔하고, 코드를 작성하는데, 시간을 단축시킬수 있도록 노력을 해야겠습니다.

728x90
반응형
Comments