728x90
[Swift] 프로그래머스 키패드 누르기(lv. 1)
1. 문제
https://school.programmers.co.kr/learn/courses/30/lessons/67256
2. 접근
문제를 잘 읽어보면 왼쪽의 1, 4, 7은 왼손으로, 오른쪽의 3, 6, 9는 오른손으로 필히 누르게 되어 있다.
그렇다면, 2, 5, 8, 0을 누를 때의 규칙만 잘 정해주면 된다.
2, 5, 8, 0을 눌러야 할 때는 양손 중에 "그 버튼과 현재 가까이 있는 위치의 손으로 누른다"라고 하였다.
그러면 현재 위치를 계속 저장해 주면서 그 위치를 계속 비교해 가야 한다는 것을 생각해 볼 수 있다.
키패드를 행렬과 같이 생각해서 0행 0열부터 2행 3열까지 있다고 해보면, 현재 왼손 오른손의 위치는 각각 (0, 3), (2, 3)이다.
numbers의 원소가 1, 4, 7로 등장할 경우와 3, 6, 9로 나오는 경우, 그리고 그 이외의 경우로 나누어서 분기 처리를 했다.
만약 2, 5, 8, 0일 경우, 각각에 맞게 rightOrLeft 함수로 L 또는 R이 들어가도록 만들었다. tempPosition도 각각 위치에 맞게 설정할 수 있도록 하였다.
조금 그냥 구현에만 초점을 맞추다보니 중복된 부분이 너무 많이 보인다.
바꾸려고 했지만, 구현을 예전에는 이렇게도 했구나 :) 하는 생각을 할 수 있을 거 같아서 그냥 냅 뒀다...
3. 코드
import Foundation
func solution(_ numbers:[Int], _ hand:String) -> String {
var leftHandPosition = [0, 3]
var rightHandPosition = [2, 3]
var answer = [Character]()
for i in numbers {
if i == 1 || i == 4 || i == 7 {
answer.append("L")
leftHandPosition = [0, i / 3]
} else if i == 3 || i == 6 || i == 9 {
answer.append("R")
rightHandPosition = [2, i / 3 - 1]
} else {
var tempPosition = [Int]()
switch i {
case 2:
tempPosition = [1, 0]
answer.append(rightOrLeft(tempPosition, leftHandPosition, rightHandPosition, hand))
if answer.last == "L" {
leftHandPosition = tempPosition
} else {
rightHandPosition = tempPosition
}
case 5:
tempPosition = [1, 1]
answer.append(rightOrLeft(tempPosition, leftHandPosition, rightHandPosition, hand))
if answer.last == "L" {
leftHandPosition = tempPosition
} else {
rightHandPosition = tempPosition
}
case 8:
tempPosition = [1, 2]
answer.append(rightOrLeft(tempPosition, leftHandPosition, rightHandPosition, hand))
if answer.last == "L" {
leftHandPosition = tempPosition
} else {
rightHandPosition = tempPosition
}
case 0:
tempPosition = [1, 3]
answer.append(rightOrLeft(tempPosition, leftHandPosition, rightHandPosition, hand))
if answer.last == "L" {
leftHandPosition = tempPosition
} else {
rightHandPosition = tempPosition
}
default:
break
}
}
}
return String(answer)
}
func rightOrLeft(_ tempPosition: [Int], _ left: [Int], _ right: [Int], _ hand: String) -> Character {
let leftDistance = abs(tempPosition[0] - left[0]) + abs(tempPosition[1] - left[1])
let rightDistance = abs(tempPosition[0] - right[0]) + abs(tempPosition[1] - right[1])
if leftDistance > rightDistance {
return "R"
} else if leftDistance < rightDistance {
return "L"
} else {
if hand == "right" {
return "R"
} else {
return "L"
}
}
}
728x90
'Problem Solving' 카테고리의 다른 글
[Swift] 프로그래머스 기사단원의 무기(lv. 1) (0) | 2023.02.15 |
---|---|
[Swift] 프로그래머스 크레인 인형뽑기 게임(lv. 1) (0) | 2023.02.14 |
[Swift] 프로그래머스 숫자 짝꿍(lv. 1) (0) | 2023.02.10 |
[Swift] 프로그래머스 명예의 전당 (1)(lv. 1) (0) | 2023.02.09 |
[Swift] 프로그래머스 체육복(lv. 1) (0) | 2023.02.08 |
댓글