Link to home
Start Free TrialLog in
Avatar of chudyksg
chudyksgFlag for United Kingdom of Great Britain and Northern Ireland

asked on

2d array rotation

how to rotate a 2d array (matrix) 90 degrees anticlockwise so:

X =
    1    2    3
    4    5    6
    7    8    9

becomes

Y =
    3    6    9
    2    5    8
    1    4    7
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

create another empty array of 3x3 dimension, and follow these steps

pick value at 1,1 and put it at 3,1
pick value at 1,2 and put it at 2,1
pick value at 1,3 and put it at 1,1
pick value at 2,1 and put it at 3,2
pick value at 2,3 and put it at 1,2
pick value at 3,1 and put it at 3,3
pick value at 3,2 and put it at 2,3
pick value at 3,3 and put it at 1,3
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sinsach
sinsach

This will rotate any matrix 90 degrees anti-clock.

/**
* To rotate the array 90 degrees anti-clock wise. This will rotate square
* and non square matrix.
* 
* @param sourceArray
* @return
*/
public int[][] antiClock90Rotation(int[][] sourceArray) {
	int[][] rotatedArray = new int[sourceArray[0].length][sourceArray.length];
	int positionFactor = rotatedArray.length - 1;
	for (int i = 0; i < rotatedArray.length; i++) {
		for (int j = 0; j < rotatedArray[i].length; j++) {
			int a = i - positionFactor;
			a = (a < 0) ? -a : a;
			rotatedArray[i][j] = sourceArray[j][a];
		}
	}
	return rotatedArray;
}

Open in new window