게임 캐릭터를 4가지 명령어를 통해 움직이려 합니다. 명령어는 다음과 같습니다.
U: 위쪽으로 한 칸 가기
D: 아래쪽으로 한 칸 가기
R: 오른쪽으로 한 칸 가기
L: 왼쪽으로 한 칸 가기
캐릭터는 좌표평면의 (0, 0) 위치에서 시작합니다. 좌표평면의 경계는 왼쪽 위(-5, 5), 왼쪽 아래(-5, -5), 오른쪽 위(5, 5), 오른쪽 아래(5, -5)로 이루어져 있습니다.
명령어가 매개변수 dirs로 주어질 때, 게임 캐릭터가 처음 걸어본 길의 길이를 구하여 return 하는 solution 함수를 완성해 주세요.
function solution(dirs) {
let arr = Array.from(Array(5), () => Array(5).fill(0));
let count = 1;
let current = [0, 0];
for (let x of dirs) {
if (x === 'U') {
current[0]++;
} else if (x === 'D') {
current[0]--;
} else if (x === 'R') {
current[1]++;
} else {
current[1]--;
}
if (current[0] > 5) {
current[0]--;
}
if (current[1] > 5) {
current[1]--;
}
let tmp = current.slice();
console.log(tmp);
if (
Math.abs(tmp[0]) <= 5 &&
Math.abs(tmp[1]) <= 5 &&
!arr[tmp[0]][tmp[1]]
) {
arr[tmp[0]][tmp[1]] = 1;
count++;
}
}
return count;
}
function solution(dirs) {
let move = { L: [-1, 0], R: [1, 0], U: [0, 1], D: [0, -1] };
// 움직이는 명령은 객체를 이용했다.
let now = [0, 0]; // current
let route = new Set();
for (let dir of dirs) {
let nx = now[0] + move[dir][0]; // nextX
let ny = now[1] + move[dir][1]; // nextY
if (nx > 5 || nx < -5 || ny > 5 || ny < -5) continue;
// route.add(`${now[0]}, ${now[1]} - ${nx}, ${ny}`); 이렇게 했는데 안됐다.
// 이상하게 []형태로 넣으면 겹치는게 제거가 안된다.
route.add('' + now[0] + now[1] + nx + ny);
route.add('' + nx + ny + now[0] + now[1]);
// 두개다 통과가 되어야 확실히 겹치지 않는 루트이기 떄문인가..?
now = [nx, ny];
}
console.log(route);
return route.size/2 ;
}