728x90
아래와 같은 방식으로 진행했다.
1. 1,4,7이라면 hand에 L 저장
2. 3,6,9라면 hand에 R 저장
3. 그 외숫자면 getnHand를 통해서 거리계산으로 L인지 R인지 저장
4. 손에 따라서 reduce를 활용해 글자를 만들어줌과 동시에 left 혹은 right 좌표를 갱신
function solution(numbers, hand) {
const cod = [[3,1],[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
let [left,right] = [[3,0],[3,2]]
const getnHand = (a,b,c) => {
const a_c = Math.abs(c[1]-a[1])+Math.abs(c[0]-a[0])
const b_c = Math.abs(c[1]-b[1])+Math.abs(c[0]-b[0])
return a_c > b_c ? 'R' : a_c===b_c ? hand==='right' ? 'R':'L' : 'L'
}
return numbers.reduce((a,c) => {
let hand
if ([1,4,7].includes(c)) hand = "L"
else if ([3,6,9].includes(c))hand = "R"
else hand = getnHand(left,right,cod[c])
if (hand==="L") left = cod[c]
else right = cod[c]
return a + hand
},"");
}
728x90
'FrontEnd > 프로그래머스' 카테고리의 다른 글
[JS] 실패율 (0) | 2023.04.24 |
---|---|
[JS] 크레인 인형뽑기 (1) | 2023.04.23 |
[JS] 두개 뽑아서 더하기 (0) | 2023.04.20 |
[JS] 신규 아이디 추천 (0) | 2023.04.20 |
[JS] 내적 (0) | 2023.04.20 |