Computer Science Canada

Rotating 2D Array

Author:  CyCLoBoT [ Tue Nov 25, 2003 4:48 pm ]
Post subject:  Rotating 2D Array

I need help with rotating a 2D array 90 degrees clockwise. This is what i mean:

2D Array (mxm)

01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16

it will come out as

13 09 05 01
14 10 06 02
15 11 07 03
16 12 08 04

Here's another example where the array is not a square(mxn)

01 02 03 04
05 06 07 08
09 10 11 12

you'd get

09 05 01
10 06 02
11 07 03
12 08 04

Thanks

Author:  Office of the Registar [ Sat Nov 29, 2003 8:13 pm ]
Post subject: 

just do it brute force method
1) first create an 2D array with new bounds (that is if row = column, then the new 2D array should have the same number of rows and column, otherwise row is then the new column, and column is then the new row)
2)
next just convert each element into the new array via a for loop

i think this is it

int row = 4;
int column = 4;
int [] [] array = new int [row] [column];
int count = 0;
for (int i = 0 ; i < row ; i++)
for (int j = 0 ; j < column ; j++)
array [i] [j] = count++;
int [] [] newarray = new int [column] [row];
for (int i = 0 ; i < column ; i++)
{
int x = row - 1;
for (int j = 0 ; j < row ; j++)
{
newarray [i] [j] = array [x--] [i];
}
}

that's a start if its wrong tho.

Author:  Office of the Registar [ Sat Nov 29, 2003 8:27 pm ]
Post subject: 

oops
for (int i = 0 ; i < row ; i++)
for (int j = 0 ; j < column ; j++)
array [i] [j] = count++;
that was just for testing

Author:  CooKieLord [ Mon Nov 12, 2007 3:47 pm ]
Post subject:  Re: Rotating 2D Array

What if the contents of the matrix is not given. It could change depending on the input. I'm a little short on time so I can't test it, but from the looks of that code, it wouldn't work. Correct me if I'm wrong.

Also, how would one go about solving this recursively? Would it be better do it that way?

When I get more time, I'll show you my progress.

P.S. Forgive me for bumping a 4 year old thread.

Author:  Clayton [ Mon Nov 12, 2007 3:59 pm ]
Post subject:  RE:Rotating 2D Array

/me dies a lot inside.

This thread is, as you so rightly stated... 4 years old!

-bits and This thread is locked


: