Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 24f975d

Browse files
feat: 2 / 방문 길이 /새로운 문제
1 parent 3a70cd1 commit 24f975d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎level-2/방문-길이.js‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//https://github.com/codeisneverodd/programmers-coding-test
2+
//더 좋은 풀이가 존재할 수 있습니다.
3+
//정답 1 - codeisneverodd
4+
function solution(dirs) {
5+
const move = ([x, y], dir) => {
6+
let next = [x, y];
7+
if (dir === 'U') next = [x, y + 1];
8+
if (dir === 'D') next = [x, y - 1];
9+
if (dir === 'R') next = [x + 1, y];
10+
if (dir === 'L') next = [x - 1, y];
11+
if (Math.abs(next[0]) > 5 || Math.abs(next[1]) > 5) return [x, y];
12+
return next;
13+
};
14+
15+
const isSameRoute = ([s1, e1], [s2, e2]) => {
16+
const isSamePoint = ([x1, y1], [x2, y2]) => x1 === x2 && y1 === y2;
17+
return (isSamePoint(s1, s2) && isSamePoint(e1, e2)) || (isSamePoint(s1, e2) && isSamePoint(s2, e1));
18+
};
19+
20+
const trace = {
21+
visited: [],
22+
visit(start, end) {
23+
if (start[0] === end[0] && start[1] === end[1]) return;
24+
if (!this.visited.find(route => isSameRoute(route, [start, end]))) this.visited.push([start, end]);
25+
},
26+
};
27+
28+
let current = [0, 0];
29+
30+
dirs.split('').forEach(dir => {
31+
const next = move(current, dir);
32+
trace.visit(current, next);
33+
current = next;
34+
});
35+
36+
return trace.visited.length;
37+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /