Answer the question
In order to leave comments, you need to log in
Is there an elegant algorithm to rotate a 4x4 matrix by 90 degrees?
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
I need to bring from this kind
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
in this form0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15
Answer the question
In order to leave comments, you need to log in
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = [];
for (var y=0; y<4; y++) {
for (var x=0; x<4; x++) {
b[x*4+y] = a[y*4+x];
}
}
In some cases, it makes sense not to rotate the matrix at all, but to keep the flag that it is rotated and swap xy in the algorithms.
1. You can simply write down 6 pairs of permutations:
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
swap(a,1,4);
swap(a,2,8);
swap(a,3,12);
swap(a,6,9);
swap(a,7,13);
swap(a,11,14);
var a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] ,tmp;
function pivot(a) {
var i, result = [];
for( i=0; i<60; i+=4) result.push(a[i%15]);
result.push(a[15]);
return result;
}
var b = pivot(a);
... but maybe there is a more primitive way?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question