Skip to content

Instantly share code, notes, and snippets.

@xgenvn
Created January 15, 2019 05:48
Show Gist options
  • Select an option

  • Save xgenvn/77bb45901c5fa39522436fb6826e926b to your computer and use it in GitHub Desktop.

Select an option

Save xgenvn/77bb45901c5fa39522436fb6826e926b to your computer and use it in GitHub Desktop.
C# Array 1D-2D conversion
private static T[,] Make2DArray<T>(T[] input, int height, int width)
{
T[,] output = new T[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
output[i, j] = input[i * width + j];
}
}
return output;
}
private static T[] Make1DArray<T>(T[,] input)
{
var rowCount = input.GetLength(0);
var colCount = input.GetLength(1);
T[] output = new T[rowCount * colCount];
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < colCount; j++)
{
output[i * rowCount + j] = input[i, j];
}
}
return output;
}
[Test]
public void ShouldReturn2DArrayFrom1DArray()
{
var test1DArray = new byte[]
{
0, 1, 0,
1, 0, 1,
1, 1, 0
};
var return2DArray = Make2DArray(test1DArray, 3, 3);
Assert.IsTrue(test1DArray.SequenceEqual(Make1DArray(return2DArray)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment