https://school.programmers.co.kr/learn/courses/30/lessons/67256
- 현재 오른쪽, 왼쪽 손가락의 위치를 매번 이동후에 갱신해야한다 currLeft, currRight
- 1~9까지 정해진 위치, 손을 obj 로 config 해서, 한번에 위치를 파악할 수 있다 (되도록 확장하기 편하게 만들자. 특수적인 공식%으로 가독성을 해하지말고)
- 맨하튼 거리: Math.abs(start[0] - end[0]) + Math.abs(start[1] - end[1])
function manhattanDist(start, end) {
return Math.abs(start[0] - end[0]) + Math.abs(start[1] - end[1]);
}
function solution(numbers, hand) {
var answer = '';
let currLeft = [3, 0]; // 왼손위치
let currRight = [3, 2]; // 오른손위치
const obj = {
1: {hand: 'L', pos: [0,0]}, // LEFT
2: {hand: 'C', pos: [0,1]}, // CENTER
3: {hand: 'R', pos: [0,2]}, // RIGHT
4: {hand: 'L', pos: [1,0]},
5: {hand: 'C', pos: [1,1]},
6: {hand: 'R', pos: [1,2]},
7: {hand: 'L', pos: [2,0]},
8: {hand: 'C', pos: [2,1]},
9: {hand: 'R', pos: [2,2]},
0: {hand: 'C', pos: [3,1]},
}
for (const number of numbers) {
const target = obj[number];
let selectedHand;
// 센터
if (target.hand === 'C') {
const leftDistance = manhattanDist(currLeft, target.pos);
const rightDistance = manhattanDist(currRight, target.pos);
// 거리가 같으면 어느 손잡이인지
if (leftDistance === rightDistance) {
selectedHand = (hand === 'right') ? 'R' : 'L';
}
// 거리가 짧은 손
else {
selectedHand = (leftDistance < rightDistance) ? 'L' : 'R';
}
}
// !센터
else {
selectedHand = target.hand;
}
answer += selectedHand;
if (selectedHand === 'L') {
currLeft = target.pos;
} else {
currRight = target.pos;
}
}
return answer;
}
'알고리즘' 카테고리의 다른 글
[프로그래머스] 문자열 내 맘대로 정렬하기 (0) | 2023.05.30 |
---|---|
[프로그래머스] 햄버거 만들기 JS (0) | 2023.05.29 |
[프로그래머스] 과일장수 (런타임 에러 문제점 찾는 법) (0) | 2023.05.28 |
[프로그래머스]둘만의 암호 (0) | 2023.05.27 |
[프로그래머스] 공원산책 (0) | 2023.05.27 |