1. 문제
https://www.acmicpc.net/problem/20436
2. 풀이과정
1. 초기 세팅
왼손으로 눌러야 하는 알파벳을 키로, 해당 알파벳의 좌표를 값으로 갖는 맵(left)을 생성한다.
오른손으로 눌러야 하는 알파벳을 키로, 해당 알파벳의 좌표를 값으로 갖는 맵(right)을 생성한다.
현재 왼손과 오른손의 초기 위치를 각각 currentLeft와 currentRight에 저장
2. 문자열 탐색 및 시간 계산
입력 문자열의 각 문자를 순회하면서 map 함수에서 해당 알파벳의 좌표를 받아온다.
현재 눌러야 할 손가락과의 거리 차이만큼 count를 증가시킨다.
그리고 현재 손가락의 좌표를 해당 문자의 좌표로 업데이트한다.
3. 자바스크립트 정답코드
const fs = require('fs');
const filepath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const input = fs.readFileSync(filepath).toString().trim().split('\n');
const [leftStart, rightStart] = input[0].trim().split(' ');
const str = input[1];
const left = new Map([
['q', { x: 0, y: 0 }], ['w', { x: 0, y: 1 }], ['e', { x: 0, y: 2 }], ['r', { x: 0, y: 3 }], ['t', { x: 0, y: 4 }],
['a', { x: 1, y: 0 }], ['s', { x: 1, y: 1 }], ['d', { x: 1, y: 2 }], ['f', { x: 1, y: 3 }], ['g', { x: 1, y: 4 }],
['z', { x: 2, y: 0 }], ['x', { x: 2, y: 1 }], ['c', { x: 2, y: 2 }], ['v', { x: 2, y: 3 }]
]);
const right = new Map([
['y', { x: 0, y: 1 }], ['u', { x: 0, y: 2 }], ['i', { x: 0, y: 3 }], ['o', { x: 0, y: 4 }], ['p', { x: 0, y: 5 }],
['h', { x: 1, y: 1 }], ['j', { x: 1, y: 2 }], ['k', { x: 1, y: 3 }], ['l', { x: 1, y: 4 }],
['b', { x: 2, y: 0 }], ['n', { x: 2, y: 1 }], ['m', { x: 2, y: 2 }]
]);
let currentLeft = left.get(leftStart);
let currentRight = right.get(rightStart);
let count = 0;
for (const char of str) {
count++;
if (left.has(char)) {
const newLeft = left.get(char);
count += Math.abs(currentLeft.x - newLeft.x) + Math.abs(currentLeft.y - newLeft.y);
currentLeft = newLeft;
} else if (right.has(char)) {
const newRight = right.get(char);
count += Math.abs(currentRight.x - newRight.x) + Math.abs(currentRight.y - newRight.y);
currentRight = newRight;
}
}
console.log(count);
'🏆 PS(Problem Solving) > Baekjoon' 카테고리의 다른 글
[Node.js] 백준 Javascript 20291 파일 정리 (0) | 2024.06.07 |
---|---|
[Node.js] 백준 Javascript 21608 상어 초등학교 (0) | 2024.06.04 |
[Node.js] 백준 Javascript 1244 스위치 켜고 끄기 (0) | 2024.06.01 |
[C++] 백준 4396 지뢰 찾기 (0) | 2024.06.01 |
[Node.js] 백준 Javascript 4396 지뢰 찾기 (0) | 2024.06.01 |