-
Notifications
You must be signed in to change notification settings - Fork 0
/
Studio10_inclass
51 lines (39 loc) · 972 Bytes
/
Studio10_inclass
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
function rotate_matrix(M) {
const n = array_length(M); // M is assumed n x n.
function swap(r1, c1, r2, c2) {
const temp = M[r1][c1];
M[r1][c1] = M[r2][c2];
M[r2][c2] = temp;
}
for(let i = 0; i < n; i = i + 1){
for(let j = i; j < n; j = j + 1 ){
swap(i, j, j, i); // transpose
}
for(let j = 0; j < math_floor(n/2); j = j + 1 ){
swap(i, j, i, n-j-1); // reverse
}
}
}
const M =
[[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]];
rotate_matrix(M);
M;
// M should have become
// [[13, 9, 5, 1],
// [14, 10, 6, 2],
// [15, 11, 7, 3],
// [16, 12, 8, 4]]
/*
Indices
[[(0,0), (0,1), (0,2), (0,3)]
[(1,0), (1,1), (1,2), (1,3)]
[(2,0), (2,1), (2,2), (2,3)]
[(3,0), (3,1), (3,2), (3,3)]]
[[(0,0), (1,0), (2,0), (3,0)]
[(0,1), (1,1), (2,1), (3,1)]
[(0,2), (1,2), (2,2), (3,2)]
[(0,3), (1,3), (2,3), (3,3)]]
*/