Created
May 17, 2019 00:39
-
-
Save WennderSantos/ea92c37590c40a15bfbf0f273a43cebc to your computer and use it in GitHub Desktop.
Rotate a matrix NxN 90 degrees
This file contains hidden or 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 static System.Console; | |
namespace _90graus | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var length = 3; | |
var matrix = new string[length, length]; | |
for (var x = 0; x <= matrix.GetUpperBound(0); x++) | |
{ | |
for (var y = 0; y <= matrix.GetUpperBound(0); y++) | |
{ | |
matrix[x, y] = (x + y).ToString(); | |
} | |
} | |
WriteLine("Original"); | |
PrintMatrix(matrix); | |
WriteLine(""); | |
var up = matrix.GetUpperBound(0); | |
for(var y = up; y > 0; y--) | |
{ | |
for (var x = up -y; x < y; x++) | |
{ | |
var next = CalculateIndex(x, y, up); | |
var temp = matrix[next.x, next.y]; | |
matrix[next.x, next.y] = matrix[x, y]; | |
next = CalculateIndex(next.x, next.y, up); | |
var item = matrix[next.x, next.y]; | |
matrix[next.x, next.y] = temp; | |
next = CalculateIndex(next.x, next.y, up); | |
temp = matrix[next.x, next.y]; | |
matrix[next.x, next.y] = item; | |
next = CalculateIndex(next.x, next.y, up); | |
item = matrix[next.x, next.y]; | |
matrix[next.x, next.y] = temp; | |
} | |
} | |
WriteLine("Rotate 90"); | |
PrintMatrix(matrix); | |
} | |
static (int x, int y) CalculateIndex(int x, int y, int up) | |
{ | |
return (y, up - x); | |
} | |
static void PrintMatrix(string[,] matrix) | |
{ | |
for (var x = 0; x <= matrix.GetUpperBound(0); x++) | |
{ | |
for (var y = 0; y <= matrix.GetUpperBound(0); y++) | |
{ | |
Write(matrix[x, y].PadRight(3)); | |
} | |
WriteLine(""); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment