## From one dimensional array to two and back

I remember converting flat arrays to multi-dimensional arrays all the time in college. For the life of me I couldn't find much code about this topic online. I had to create my own utility functions:
`private T[,] toRectangular<T>(T[] flatArray, int width){    int height = (int)Math.Ceiling(flatArray.Length / (double)width);    T[,] result = new T[height, width];    int rowIndex, colIndex;    for (int index = 0; index < flatArray.Length; index++)    {        rowIndex = index / width;        colIndex = index % width;        result[rowIndex, colIndex] = flatArray[index];    }    return result;}private T[] toFlat<T>(T[,] rectArray){    int width = rectArray.GetUpperBound(1) + 1;    T[] result = new T[rectArray.Length];    for (int i = 0; i < result.Length; i++)    {        result[i] = rectArray[i / width, i % width];    }    return result;}private void testIt(){    int width = 4;    int[] flatStuff = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};    int[,] rectStuff = toRectangular(flatStuff, width);    int[] flatAgain = toFlat(rectStuff);}`

Labels: , , , Subscribe to Posts [Atom]