K
K
krll-k2015-08-29 20:00:25
JavaScript
krll-k, 2015-08-29 20:00:25

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 form
0 4 8 12
1 5 9 13
2 6 10 14
3 7 11 15

I can use two loops and conditions, but is there a more primitive way?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Aves, 2015-08-29
@krll-k

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];
    }
}

M
maaGames, 2015-08-29
@maaGames

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.

S
Sergey Sokolov, 2015-08-29
@sergiks

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);

2. You can step with an increment of 4 and take the remainder of the division by 15:
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);

X
xmoonlight, 2015-08-29
@xmoonlight

... but maybe there is a more primitive way?

Yes, there is faster, but it is not at all more primitive ..
What you can see right away:
1. the main diagonal is preserved -> we calculate with copying the main diagonal elements
2. the positions of the elements in X and Y are interchanged -> so you can only calculate OVER ( well, or UNDER) the main diagonal!
Bottom line: growth> 50%
...... everything seems to be)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question