-
Notifications
You must be signed in to change notification settings - Fork 0
/
2d-array-rotation.js
99 lines (88 loc) · 1.89 KB
/
2d-array-rotation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Rotates the given array 90 degrees clockwise.
function rotate90(a) {
const w = a.length;
const h = a[0].length;
let b = new Array(h);
for (let y=0; y<h; y++) {
b[y] = new Array(w);
for (let x=0; x<w; x++) {
b[y][x] = a[w-1-x][y];
}
}
return b;
}
// Rotates the given 2d array 180 degrees clockwise.
function rotate180(a) {
const w = a[0].length;
const h = a.length;
let b = new Array(h);
for (let y=0; y<h; y++) {
let n = h-1-y;
b[n] = new Array(w);
for (let x=0; x<w; x++) {
b[n][w-1-x] = a[y][x];
}
}
return b;
}
// Rotates the given 2d array 270 degrees clockwise.
function rotate270(a) {
const w = a.length;
const h = a[0].length;
let b = new Array(h);
for (let y=0; y<h; y++) {
b[y] = new Array(w);
for (let x=0; x<w; x++) {
b[y][x] = a[x][h-1-y];
}
}
return b;
}
//Rotates the given two-dimensional array by the given right angle in degrees.
//* Degrees must be a multiple of 90. Returns the original input if told to
// * rotate by 0 or 360 degrees.
function rotate(a, deg) {
if (deg % 90 !== 0) {
throw new Error(
'Invalid input; degrees must be a multiple of 90'
);
}
const d = ((deg % 360) + 360) % 360;
if (d === 90) {
return rotate90(a);
} else if (d === 180) {
return rotate180(a);
} else if (d === 270) {
return rotate270(a);
}
// otherwise, if it's 0 degrees
return a;
}
// Flips the given two-dimensional array horizontally.
function hflip(a) {
const h = a.length;
let b = new Array(h);
for (let y=0; y<h; y++) {
let w = a[y].length;
b[y] = new Array(w);
for (let x=0; x<w; x++) {
let n = w-1-x;
b[y][n] = a[y][x];
}
}
return b;
}
// Flips the given two-dimensional array vertically.
function vflip(a) {
const h = a.length;
let b = new Array(h);
for (let y=0; y<h; y++) {
let w = a[y].length;
let n = h-1-y;
b[n] = new Array(w);
for (let x=0; x<w; x++) {
b[n][x] = a[y][x];
}
}
return b;
}