Musings
Public · Protected · Private
how to convert Matrix to Array and reverse
-
2012-07-11 02:12public static class dd { //Flattened by crawling public static IEnumerable<T> Flatten<T>(this T[,] matrix) { var rows = matrix.GetLength(0); var cols = matrix.GetLength(1); for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) yield return matrix[i, j]; } } // Buffer copy public static int[] Matrix2Array(int[,] matrix) { int[] flattened = new int[matrix.GetLength(0) * matrix.GetLength(1)]; Buffer.BlockCopy(matrix, 0, flattened, 0, matrix.GetLength(0) * matrix.GetLength(1) * sizeof(int)); return flattened; } // Buffer copy public static int[,] Array2Matrix(int[] flat, int m, int n) { //if (flat.Length != m * n) //{ // throw new ArgumentException("Invalid length"); //} int[,] matrix = new int[m, n]; Buffer.BlockCopy(flat, 0, matrix, 0, flat.Length * sizeof(int)); return matrix; } } int[,] array2D = new int[,] { { 1, 2, 3,4 }, { 4, 5, 6,7 }, { 7, 8, 9,10 } }; int[] flatByYield = dd.Flatten( array2D).ToArray(); int[,] matrixBuiltByBuffer = dd.Array2Matrix(flatByYield, 4, 3); int[] flattenedByBuffer = dd.Matrix2Array(matrixBuiltByBuffer);
This blog is frozen. No new comments or edits allowed.