[카카오 인턴] 키패드 누르기_swfit

hankyulee·2021년 11월 13일
0

Swift coding test 준비

목록 보기
38/57
import Foundation

func solution(_ numbers:[Int], _ hand:String) -> String {
    var leftThumb = -1
    var rightThumb = -2
    var result:[String] = []
    var memory_L:[Int] = []
    var memory_R:[Int] = []
    var memory_Current:[Int] = []

    for n in numbers{
        for (i,row) in [[1,2,3],[4,5,6],[7,8,9],[-1,0,-2]].enumerated(){
                for (j,k) in row.enumerated(){
                    if k == leftThumb{
                        leftThumb = k
                        memory_L = [i,j]
                    }
                    if k == rightThumb{
                        rightThumb = k
                        memory_R = [i,j]
                    }
                    if k == n {

                        memory_Current = [i,j]
                    }
                    //print(n,memory_L,memory_R,memory_Current)
                }
            }

        if [1,4,7].contains(n){
            result.append("L")
            memory_L = memory_Current
            leftThumb = n
        }
        else if [3,6,9].contains(n){
            result.append("R")
            memory_R = memory_Current
            rightThumb = n
        }
        else {


            if abs(memory_L[0] - memory_Current[0]) + abs(memory_L[1] - memory_Current[1]) == abs(memory_R[0] - memory_Current[0]) + abs(memory_R[1] - memory_Current[1]){
                if hand == "right"{
                    result.append("R")
                    memory_R = memory_Current
                    rightThumb = n
                }
                else {
                    result.append("L")
                    memory_L = memory_Current
                    leftThumb = n
                }
            }

            else if abs(memory_L[0] - memory_Current[0]) + abs(memory_L[1] - memory_Current[1]) > abs(memory_R[0] - memory_Current[0]) + abs(memory_R[1] - memory_Current[1]){

                result.append("R")
                rightThumb = n
                memory_R = memory_Current
            }
            else {
                result.append("L")
                leftThumb = n
                memory_L = memory_Current
                 }
        }
    }
    //print(result.joined())
    return result.joined()
}

0개의 댓글