Skip to content

Commit d7ea175

Browse files
committed
Add 220509 삼각 달팽이.js
1 parent 8097cb2 commit d7ea175

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

level-2/삼각-달팽이.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,24 @@ function solution(n) {
1717
}
1818
return snail.flatMap((num) => num);
1919
}
20+
21+
//정답 2 - jaewon1676
22+
function solution(n) {
23+
const answer = new Array(n).fill().map((e, i) => new Array(i + 1));
24+
// 이차원배열을 만들어준다
25+
26+
let count = 0;
27+
let x = -1; // 행 , 0행 0열부터 시작해주기 위해 x는 -1 해줍니다.
28+
let y = 0; // 열
29+
while (n > 0) {
30+
for (let i = 0; i < n; i++) answer[++x][y] = ++count; // 아래로 이동합니다.
31+
for (let i = 0; i < n - 1; i++) answer[x][++y] = ++count; // 오른쪽으로 이동합니다.
32+
for (let i = 0; i < n - 2; i++) answer[--x][--y] = ++count; // 대각선 오른쪽 위로 이동합니다.
33+
34+
n -= 3;
35+
}
36+
return answer.flatMap(e => e);
37+
// flatMap은 이차원의 여러 배열을 하나의 배열로 묶어줍니다.
38+
// ex [ [ 1 ], [ 2, 9 ], [ 3, 10, 8 ], [ 4, 5, 6, 7 ] ]
39+
// => [1, 2, 9, 3, 10, 8, 4, 5, 6, 7]
40+
}

0 commit comments

Comments
 (0)