Created
December 7, 2016 05:58
-
-
Save jianminchen/e943a9e7b86d24e9f36c04f1f3502941 to your computer and use it in GitHub Desktop.
Matrix Rotation code review - make variable names meaningful
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
class Solution | |
{ | |
static void Main(String[] args) | |
{ | |
int[] ia = GetInts(Console.ReadLine(), 3); | |
int rows = ia[0]; | |
int cols = ia[1]; | |
int cnt = ia[2]; | |
int[][] mx = new int[rows][]; | |
for (int i = 0; i < rows; i++) | |
{ | |
mx[i] = GetInts(Console.ReadLine(), cols); | |
} | |
Rotate(mx, rows, cols, cnt); | |
for (int i = 0; i < rows; i++) | |
{ | |
Console.WriteLine(GetRow(mx[i])); | |
} | |
} | |
private static void Rotate(int[][] mx, int rows, int cols, int cnt) | |
{ | |
int startR = 0, startCol = 0; | |
while (rows > 1 && cols > 1) | |
{ | |
RotateOut(mx, rows, cols, startR, startCol, cnt); | |
rows -= 2; | |
cols -= 2; | |
startR++; | |
startCol++; | |
} | |
} | |
private static string GetRow(int[] xx) | |
{ | |
string res = ""; | |
foreach (int i in xx) | |
{ | |
res += i + " "; | |
} | |
return res.Trim(); | |
} | |
/* | |
* Code Review: Dec. 6, 2016 | |
* Jianmin Chen | |
* 1. Declare meaningful variable name: actualSteps | |
* 2. meaningful variable name: | |
* lastCol, lastRow, firstOneInStrip | |
*/ | |
private static void RotateOut(int[][] mx, int rows, int cols, int startR, int startCol, int steps) | |
{ | |
int actualSteps = steps % (2 * (cols + rows - 2)); | |
for (int x = 0; x < actualSteps; x++) | |
{ | |
int firstOneInStrip = mx[startR][startCol]; | |
for (int i = startCol; i < startCol + cols - 1; i++) | |
mx[startR][i] = mx[startR][i + 1]; | |
int lastCol = startCol + cols - 1; | |
for (int i = startR; i < startR + rows - 1; i++) | |
mx[i][lastCol] = mx[i + 1][lastCol]; | |
int lastRow = startR + rows - 1; | |
for (int i = startCol + cols - 1; i >= startCol + 1; i--) | |
mx[lastRow][i] = mx[lastRow][i - 1]; | |
for (int i = startR + rows - 1; i >= 1 + startR; i--) | |
mx[i][startCol] = mx[i - 1][startCol]; | |
mx[startR + 1][startCol] = firstOneInStrip; | |
} | |
} | |
static int[] GetInts(string inp, int cnt) | |
{ | |
string[] vals = inp.Split(new char[] { ' ' }); | |
int[] res = new int[cnt]; | |
for (int i = 0; i < cnt; i++) | |
{ | |
res[i] = Convert.ToInt32(vals[i]); | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment