You are viewing a single comment's thread. Return to all comments →
//Java 8
int m = matrix.size() - 1; int n = matrix.get(0).size() - 1; List> returnArr = new ArrayList<>();
for (int i = 0; i <= m; i++) { List<Integer> arr = new ArrayList<>(); for (int j = 0; j <= n; j++) { int mLevelMin = Math.min(i, Math.abs(i - m)); //lowest level in y axis int nLevelMin = Math.min(j, Math.abs(j - n)); //lowest level in x axis int level = Math.min(mLevelMin, nLevelMin); int mLevelMax = m - level; int nLevelMax = n - level; // starting of level (level, level) and end of level (mLevelMax, nLevelMax) int ringSize = 2 * (mLevelMax + nLevelMax - 2 * level); //ringsize = 2(length + breadth - 2) int actRot = r % ringSize; //finding min rotation to achive the goal int iPos = i; // (iPos, jPos) is the position of target element int jPos = j; while (actRot > 0) { if (iPos == level && jPos < nLevelMax) { //to right if (jPos + actRot > nLevelMax) { actRot -= nLevelMax - jPos; jPos = nLevelMax; } else { jPos += actRot; actRot = 0; } } else if (jPos == nLevelMax && iPos < mLevelMax) {//going down if (iPos + actRot > mLevelMax) { actRot -= mLevelMax - iPos; iPos = mLevelMax; } else { iPos += actRot; actRot = 0; } } else if (iPos == mLevelMax && jPos > level) {//to left if (jPos - actRot < level) { actRot -= jPos - level; jPos = level; } else { jPos -= actRot; actRot = 0; } } else {//going up if (iPos - actRot < level) { actRot -= iPos - level; iPos = level; } else { iPos -= actRot; actRot = 0; } } } arr.add(matrix.get(iPos).get(jPos)); } returnArr.add(arr); } for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix.get(0).size(); j++) { System.out.printf("%d ", returnArr.get(i).get(j)); } System.out.printf("%n"); }
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Layer Rotation
You are viewing a single comment's thread. Return to all comments →
//Java 8
int m = matrix.size() - 1; int n = matrix.get(0).size() - 1; List> returnArr = new ArrayList<>();