Computer Science/자료구조

[6.11] 프로그래머스 코딩테스트 연습 - 키패드 누르기 (15/100)

토마토. 2021. 6. 10. 23:14

코딩테스트 연습 - 키패드 누르기 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 키패드 누르기

[1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] "right" "LRLLLRLLRRL" [7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2] "left" "LRLLRRLLLRR" [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] "right" "LLRLLRLLRL"

programmers.co.kr

풀었다!!

def solution(numbers, hand):

    import math
    answer = ''
    right_loca = '#'
    left_loca = '*'
    distance = {1:(0,3), 2 : (1,3), 3: (2,3), 4:(0,2), 5:(1,2), 6:(2,2), 7:(0,1), 8:(1,1), 9:(2,1), 0:(1,0), '*':(0,0), '#':(2,0)}
    for i in numbers:
      if i in [1, 4, 7]:
        
        answer += 'L'
        left_loca = i
      elif i in [3, 6, 9]:
        
        answer += 'R'
        right_loca = i
  
      else:
        dist_left = math.sqrt((distance[left_loca][0]-distance[i][0])**2 + (distance[left_loca][1]-distance[i][1])**2)
        dist_right = math.sqrt((distance[right_loca][0]-distance[i][0])**2 + (distance[right_loca][1]-distance[i][1])**2)

        if int(dist_left) != dist_left:
          dist_left = int(dist_left) + 1
        if int(dist_right) != dist_right:
          dist_right = int(dist_right) + 1



        #사실 루트 2랑 직선 2랑 똑같다. 
        # 2 -> 0 ~ 17
        # 5 -> 
        if dist_left > dist_right:
          
          answer += 'R'
          right_loca = i
        elif dist_left < dist_right:
          
          answer += 'L'
          left_loca = i
        else:
          if hand == "right":
            
            answer += 'R'
            right_loca = i
          else:
            
            answer += 'L'
            left_loca = i
    return answer

다른 사람 풀이 보기

def solution(numbers, hand):
    answer = ''
    key_dict = {1:(0,0),2:(0,1),3:(0,2),
                4:(1,0),5:(1,1),6:(1,2),
                7:(2,0),8:(2,1),9:(2,2),
                '*':(3,0),0:(3,1),'#':(3,2)}

    left = [1,4,7]
    right = [3,6,9]
    lhand = '*'
    rhand = '#'
    for i in numbers:
        if i in left:
            answer += 'L'
            lhand = i
        elif i in right:
            answer += 'R'
            rhand = i
        else:
            curPos = key_dict[i]
            lPos = key_dict[lhand]
            rPos = key_dict[rhand]
            ldist = abs(curPos[0]-lPos[0]) + abs(curPos[1]-lPos[1])
            rdist = abs(curPos[0]-rPos[0]) + abs(curPos[1]-rPos[1])

            if ldist < rdist:
                answer += 'L'
                lhand = i
            elif ldist > rdist:
                answer += 'R'
                rhand = i
            else:
                if hand == 'left':
                    answer += 'L'
                    lhand = i
                else:
                    answer += 'R'
                    rhand = i

    return answer