본문 바로가기

⏳ 알고리즘/JavaScript 알고리즘

프로그래머스 - LV1. 키패드 누르기(카카오 2020 인턴쉽)

문제

https://programmers.co.kr/learn/courses/30/lessons/67256?language=javascript 

 

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

[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

 

코드

function solution(numbers, hand) {
    var answer = '';
    const 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],
    }
    let cur_left = '*'
    let cur_right = '#'
    
    
    for (let i=0; i<numbers.length; i++) {
        if ([1,4,7].includes(numbers[i])) {
            answer += "L"
            cur_left = numbers[i]
        } else if ([3,6,9].includes(numbers[i])) {
            answer += "R"
            cur_right = numbers[i]
        } else {
            const l = key_dict[cur_left]
            const r = key_dict[cur_right]
            const c = key_dict[numbers[i]]
            
            const distance_left = Math.abs(l[0]-c[0]) + Math.abs(l[1]-c[1])
            const distance_right = Math.abs(r[0]-c[0]) + Math.abs(r[1]-c[1])
            
            if (distance_right < distance_left) {
                answer += "R"
                cur_right = numbers[i]
            } else if (distance_right > distance_left) {
                answer += "L"
                cur_left = numbers[i]
            } else {
                if (hand == "right") {
                    answer += "R"
                    cur_right = numbers[i]
                } else {
                    answer += "L"
                    cur_left = numbers[i]
                }
            }
        }
    }
    return answer;
}