Home > Net >  How to join indexes in an 2D array in C#
How to join indexes in an 2D array in C#

Time:12-28

Is there a efficient way to join blocks in the arrays, as shown here:

original_array = [[1,2], [4,7], [8,10], [15,20], [21,25]]

new_array = [[1,2], [4,10], [15,25]]

Basically I want to join 2 indexes of an array if the distance between them is 1.

I tried something like this but it didin't work.

                int[,] new_array = new int[500, 2];
                int new_var = 0;
                for (int k = 0; k < original_indexes; k  )
                {
                    int dista = original_array [k   1, 0] - original_array [k, 1];
                    if (dista < 10)
                    {
                        new_array[k, 0] = original_array[k, 0];
                        new_array[k, 1] = original_array[k   1, 1];
                        new_var  ;
                    }
                    else
                    {
                        new_array[k, 0] = original_array[k   new_var, 0];
                        new_array[k, 1] = original_array[k   new_var, 1];
                    }
                }

Sorry, but I don't know how to be more specific and I don't even know how to search for this.

CodePudding user response:

You can try something like this:

    using System.Linq;

    ...
 
    private static int[,] MyCombine(int[,] source) {
      List<int[]> list = new List<int[]>();

      int[] last = null;

      for (int r = 0; r < source.GetLength(0);   r) 
        if (last == null || last[1]   1 < source[r, 0]) {
          if (last != null)
            list.Add(last);

          last = new int[] { source[r, 0], source[r, 1] };
        }
        else
          last[1] = source[r, 1];
      
      if (last != null)
        list.Add(last);

      int[,] result = new int[list.Count, 2];

      for (int r = 0; r < list.Count;   r)
        for (int c = 0; c < list[r].Length;   c)
          result[r, c] = list[r][c];

      return result;
    }

Demo:

  int[,] original = new int[,] {
    { 1,  2 },
    { 4,  7 },
    { 8, 10 },
    {15, 20 },
    {21, 25 },
  };

  int[,] result = MyCombine(original);

  string report = "["   string.Join(", ", Enumerable
    .Range(0, result.GetLength(0))
    .Select(r => $"[{result[r, 0]}, {result[r, 1]}]"))   "]";

  Console.Write(report);

Outcome:

 [[1, 2], [4, 10], [15, 25]]
  • Related