Last active
March 17, 2017 14:57
-
-
Save LindaLawton/90565879a7c25da40f212e05e1fad934 to your computer and use it in GitHub Desktop.
Rotate a matrix by 90 or 180 degrees
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; | |
namespace CsharpCodeExamples | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var data = new int[,] { { 1, 1, 1, 1 }, | |
{ 2, 2, 2, 2 }, | |
{ 3, 3, 3, 3 }, | |
{ 4, 4, 4, 4 } }; | |
PrintArray(data); | |
Console.WriteLine(); | |
var rotated180 = Rotate180(data); | |
PrintArray(rotated180); | |
Console.WriteLine(); | |
var rotate90 = Rotate90(data); | |
PrintArray(rotate90); | |
Console.WriteLine(); | |
} | |
/// <summary> | |
/// Rotate matrics 90 degress clock wise. | |
/// | |
/// The idea behind this is that the first row becomes the last column and the last | |
/// row becomes the first column | |
/// </summary> | |
/// <param name="data"></param> | |
/// <returns></returns> | |
public static int[,] Rotate90(int[,] data) | |
{ | |
var data2 = new int[4, 4]; | |
int col = 0; | |
int row = 0; | |
for (int i = data.GetLength(0) - 1; i >= 0; i--) // rows backwards | |
{ | |
for (int n = 0; n < data.GetLength(1); n++) // columns | |
{ | |
data2[row, col] = data[i, n]; | |
row++; | |
} | |
col++; | |
row = 0; | |
} | |
return data2; | |
} | |
/// <summary> | |
/// Rotates the mattrics 180 degress | |
/// | |
/// The idea behind this is a simple flip the last row becomes the first row. | |
/// </summary> | |
/// <param name="data"></param> | |
/// <returns></returns> | |
public static int[,] Rotate180(int[,] data) { | |
var data2 = new int[4, 4]; | |
int col = 0; | |
int row = 0; | |
for (int i = data.GetLength(0) - 1; i >= 0; i--) // rows | |
{ | |
for (int n = 0; n < data.GetLength(1); n++) // columns | |
{ | |
data2[row, col] = data[i, n]; | |
col++; | |
} | |
row++; | |
col = 0; | |
} | |
return data2; | |
} | |
public static void PrintArray(int[,] data) { | |
for (int i = 0; i < data.GetLength(0); i++) // rows | |
{ | |
for (int n = 0; n < data.GetLength(1); n++) // columns | |
{ | |
var split = (n != data.GetLength(1) - 1) ? "," : string.Empty; | |
Console.Write(data[i,n] + split); | |
} | |
Console.WriteLine(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment