-->

Combining two single dimensional arrays in a 2D ar

2020-08-09 05:11发布

问题:

I am having two 1D arrays. I want to convert these 2 arrays as single 2D array.

My code is:

public Static void Main()
{
int[] arrayRow;
int[] arrayCol;
  for (int i = 0; i < row; i++)
  {
   for (int j = 0; j < column; j++)
     {
       int[,] myArray = new int[row,column];
       myArray[i,j] = arrayRow[i]; // not possible -- your suggestions           
     }
   }
for (int i = 0; i < row; i++)
  {
   for (int j = 0; j < column; j++)
     {
       Console.Write(myArray[i,j]);         
     }
   }
}

I need to save arrayRow[] and arrayCol[] in myArray[,].

For example,

if we have arrayRow[]={1,2,3} and arrayCol[]={4,5,6} then myArray[,]={(1,4),(2,5),(3,6)}

Note: arrayRow and arrayCol may have different lengths. In such cases the element that have no pair should be stored in the new single dimensional array result[].

回答1:

Didn't tryed this, and I'm just guessing what you want to acomplish, but here it is:

int[] arrayRow;
int[] arrayCol;

int[,] myArray = new int[Math.Max(arrayRow.Length, arrayCol.Length), 2];

for (int i = 0; i < arrayRow.Length; i++)
  myArray[i, 0] = arrayRow[i];

for (int i = 0; i < arrayCol.Length; i++)
  myArray[i, 1] = arrayCol[i];


回答2:

Your arrayRow[] and arrayCol[] will be just two lines of a two-dimensional array (if you didn't mean jagged one).

So the code to unite two arrays into one is just:

public static T[,] Union<T>(T[] first, T[] second) //where T : struct
{
    T[,] result = new T[2, Math.Max(first.Length, second.Length)];
    int firstArrayLength = first.Length * Marshal.SizeOf(typeof(T));
    Buffer.BlockCopy(first, 0, result, 0, firstArrayLength);
    Buffer.BlockCopy(second, 0, result, firstArrayLength, second.Length * Marshal.SizeOf(typeof(T)));
    return result;
}

As it have been mentinoned, BlockCopy is cooler than for cycle.


If you do mean that you need a jagged array (like int[][]), that the solutiona will be way more simplier:

public static T[][] UnionJagged<T>(T[] first, T[] second)
{
    return new T[2][] { first, second };
}

Which transforms into even simplier if we add multiple-array-as-parameters functionality:

public static T[][] UnionJagged<T>(params T[][] arrays)
{
    return arrays;
}

static void Main()
{
    int[] a = new int[] { 10, 2, 3 };
    int[] b = new int[] { -1, 2, -3 };
    int[] c = new int[] { 1, -2, 3 };
    int[][] jaggedThing = UnionJagged(a, b, c);
}


回答3:

More performant / another way:

public static void ConvertFlatArrayToMatrix(int[] array, int[,] matrix, int dimension) {
        for(int i = 0; i < array.Length; i++) {
            int r = Mathf.FloorToInt(i / dimension);
            int c = i % dimension;

            matrix[c,r] = array[i];
        }
    }

This will just push the result into a 2d array you pass in.

Keep in mind, I'm not checking length or protecting against anything here, this is just the concept and the bare minimum to get the job done.