Friday, January 15, 2021

Q.14: How to convert a two-dimensional array to a one-dimensional array?

 Ans.: The user will input a 2-D array (matrix) and we need to convert it to a 1-D array. We will create 1-D array column wise.

  • input: { { 1, 2, 3 }, { 4, 5, 6 } }, output: 1 4 2 5 3 6
internal static void MultiToSingle(int[,] array)
{
int index = 0;
int width = array.GetLength(0);
int height = array.GetLength(1);
int[] single = new int[width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
single[index] = array[x, y];
Console.Write(single[index] + " ");
index++;
}
}
}
This question can also be asked to form 1-D array row wise. In this case just swap the sequence of thefor loops as below. The output will be 1 2 3 4 5 6 for the input matrix mentioned above.
for (int x = 0; x < width; x++ )
{
for ( int y = 0; y < height; y++)
{
single[index] = array[x, y];
Console.Write(single[index] + " ");
index++;
}
}

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...