Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

Rotating a rectangular array in Javascript

I am trying to make a tetris game. I am trying to work on a function that rotates a 2D variable array 90 degrees (or -90).

For example, given an array like:

"-T-",
"TTT"

It would like an output like:

"T-",
"TT",
"T-"

etc, etc.

I have tried this function:

function rotateN90(a){
    var temp = [];
    for(var x = 0; x<a[0].length; x++){
        temp.push("");
        for(var y = 0; y<a.length; y++){
            temp[x] += a[y][x];
        }
    }
    
    return temp;
}

but it does not give the desired result. While it does rotate the first T-Block example given -90 degrees once, afterwards it reverts to it's original state.

Please help!

(PS: I am using KA's processing environment, so I can't use libraries)

question from:https://stackoverflow.com/questions/65943795/rotating-a-rectangular-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code is to rotate a mxn size array to -90 degree.

function rotateN90(a){

 var temp = new Array(a[0].length); // number of columns
 var i=0;

 for (i = 0; i < temp.length; i++) { 
     temp[i] = [];
 } 

 for(i=0;i<a.length;i++){
    
     for(let j = 0; j<a[0].length;j++){

         temp[j][i]= a[i][a[i].length-1-j];
     }
 }

 return temp;
}

If your array is : [[1, 2,3],[4, 5, 6]]

It will rotate -90 degree and returned array will be [[3, 6],[2, 5],[1, 4]]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...