1차원 배열 회전
function rotate(array, step = 0) {
if (step == 0) return [...array];
let temp;
let stepped;
if (step > 0) { // 시계(우측) 방향 회전
stepped = array.length - step;
temp = array.slice(0, stepped);
} else { // 반시계(좌측) 방향 회전
stepped = Math.abs(step);
temp = array.slice(0, stepped);
}
return array.slice(stepped).concat(temp);
}
const a = [1, 2, 3, 4, 5, 6];
const result = rotate(a, -1);
console.log(result);
// [6, 1, 2, 3, 4, 5]
const result2 = rotate(a, 2);
console.log(result2);
// [5, 6, 1, 2, 3, 4]
console.log(a);
// [1, 2, 3, 4, 5, 6]
2차원 배열 회전
// 회전하고 싶은 2차원 배열 array
// 회전 수 step
function rotate(array, step = 0) {
if (step == 0) return array;
const N = array.length;
const M = array[0].length;
const result = Array(M)
.fill()
.map((el) => Array(N).fill(0));
while (step % 4) {
result.forEach((rows, i) =>
rows.forEach((col, j) => {
if (step < 0) {
result[i][j] = array[j][M - i - 1];
} else {
result[i][j] = array[N - j - 1][i];
}
})
);
if (step < 0) {
step++;
} else {
step--;
}
}
return result;
}
2차원 배열 대칭
function symmetry(array) {
const [N, M] = [array[0].length, array.length];
const result = Array(N).fill().map(el=>Array(M).fill(0));
for(let i = 0; i < N; i++) {
for(let j = 0; j < M; j++) {
result[i][j] = array[j][i];
}
}
return result;
}
const a = [[1,2,3],[4,5,6],[7,8,9]];
const result = symmetry(a);
console.log(result);
// [[1,4,7],[2,5,8],[3,6,9]]'알고리즘&코테' 카테고리의 다른 글
| [알고리즘] n진법 변환 (0) | 2024.11.18 |
|---|---|
| [알고리즘] JS 순열, 조합 (0) | 2024.11.18 |
| [알고리즘 JS] 이분 탐색 (0) | 2024.11.13 |
| JS 알고리즘 공부 5회차 with. BaaaaaaaarkingDog (0) | 2024.10.23 |
| JS 알고리즘 공부 4회차 with. BaaaaaaaarkingDog (0) | 2024.10.22 |