Archive/Questions

[programmers/Swift] 키패드 누르기 (2020 Kakao 인턴쉽)

Marco 2022. 5. 9. 19:04
728x90

programmers.co.kr - 코딩테스트연습 - Lv.1 - 2020 카카오 인턴쉽 - 키패드 누르기

Constraints :

  • numbers 배열의 크기는 1 이상 1,000 이하입니다.
  • numbers 배열 원소의 값은 0 이상 9 이하인 정수입니다.
  • hand는 "left" 또는 "right" 입니다.
    • "left"는 왼손잡이, "right"는 오른손잡이를 의미합니다.
  • 왼손 엄지손가락을 사용한 경우는 L, 오른손 엄지손가락을 사용한 경우는 R을 순서대로 이어붙여 문자열 형태로 return 해주세요.

 

Solution.swift :

//
//  Created by Yongwoo Marco on 2022/05/08.
//  Copyright © 2022 Yongwoo Marco Kim. All rights reserved.
//

func solution(_ numbers:[Int], _ hand:String) -> String {
    let table = [
        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)
    ]
    var left = (0, 0), right = (2, 0)
    var result = ""
    
    func pick(_ hand: String, _ next: Int) {
        if hand == "L" {
            result.append("L")
            left = table[next]!
        } else {
            result.append("R")
            right = table[next]!
        }
    }
    
    func distanceCheck(_ now: (Int, Int), end: (Int, Int)) -> Int {
        return abs(now.0 - end.0) + abs(now.1 - end.1)
    }
    
    numbers.forEach { next in
        if [1, 4, 7].contains(next) {
            pick("L", next)
        } else if [3, 6, 9].contains(next) {
            pick("R", next)
        } else {
            let leftDistance = distanceCheck(left, end: table[next]!)
            let rightDistance = distanceCheck(right, end: table[next]!)
            
            if leftDistance > rightDistance {
                pick("R", next)
            } else if leftDistance < rightDistance {
                pick("L", next)
            } else {
                hand == "left" ? pick("L", next) : pick("R", next)
            }
        }
    }
    return result
}

print(solution([1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5] , "right")) // "LRLLLRLLRRL"
print(solution([7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2], "left")) // "LRLLRRLLLRR"
print(solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], "right")) // "LLRLLRLLRL"

How I tried this :
enum 까지는 오바같아서 바로 비교해서 풀었다.

거리에 대해 고민했는데 그냥 두점거리 구하는 방법의 크기로 비교해 보았는 데 다행히 통과

문제에 관한 모든 저작권 : https://programmers.co.kr/

728x90