2

I wrote a rotate function, but I'm not satisfied with it:

var pixels=['011','110','000'];
var result=new Array();
result=['000','000','000'];
var r = {x:1,y:1}; //rotating point
var clock = true; //clock or counter-clock rotation


for ( y=0; y<(pixels.length); y++ ){
  for ( x=0; x<(pixels.length); x++ ){
    var newx=0,newy=0;
    if ( clock ){
      if ( x< r.x && y< r.y ) {newx=x+2;newy=y  ;}//top left
      if ( x==r.x && y< r.y ) {newx=x+1;newy=y+1;}//top
      if ( x> r.x && y< r.y ) {newx=x  ;newy=y+2;}//top right
      if ( x< r.x && y==r.y ) {newx=x+1;newy=y-1;}//left
      if ( x==r.x && y==r.y ) {newx=x  ;newy=y  ;}//center
      if ( x> r.x && y==r.y ) {newx=x-1;newy=y+1;}//right
      if ( x< r.x && y> r.y ) {newx=x  ;newy=y-2;}//bottom left
      if ( x==r.x && y> r.y ) {newx=x-1;newy=y-1;}//bottom
      if ( x> r.x && y> r.y ) {newx=x-2;newy=y  ;}//bottom right
    } else {
      if ( x< r.x && y< r.y ) {newx=x  ;newy=y+2;}//top left
      if ( x==r.x && y< r.y ) {newx=x-1;newy=y+1;}//top
      if ( x> r.x && y< r.y ) {newx=x-2;newy=y  ;}//top right
      if ( x< r.x && y==r.y ) {newx=x+1;newy=y+1;}//left
      if ( x==r.x && y==r.y ) {newx=x  ;newy=y  ;}//center
      if ( x> r.x && y==r.y ) {newx=x-1;newy=y-1;}//right
      if ( x< r.x && y> r.y ) {newx=x+2;newy=y  ;}//bottom left
      if ( x==r.x && y> r.y ) {newx=x+1;newy=y-1;}//bottom
      if ( x> r.x && y> r.y ) {newx=x  ;newy=y-2;}//bottom right
    }
    //inject(result,newx,newy,pixels[y][x])
  }
}

does someone now how to write a cleaner code for this rotate (clock and counter-clock) function ?

ideotop
  • 184
  • 6

1 Answers1

1

You could try the suggestions in How to Rotate a 2D Array of Integers but then you would probably have to use an array of arrays, instead of an array of strings (which might make more sense anyway).

Community
  • 1
  • 1
Tyler
  • 21,762
  • 11
  • 61
  • 90