Trying to convert int [] to int [,] using C #

I need a function to convert a single array of dimensions int [480000] into a 2d array of size int [800,600]. Could you help me how can this be done?

+5
source share
4 answers
public static T[,] Convert<T>(this T[] source, int rows, int columns)
{
  int i = 0;
  T[,] result = new T[rows, columns];

  for (int row = 0; row < rows; row++)
    for (int col = 0; col < columns; col++)
      result[row, col] = source[i++];
  return result;
}
+5
source

Do you really want to physically move the data, or is 800x600 View enough?
You can use the wrapper as follows:

// error checking omitted
class MatrixWrapper<T>
{
    private T[] _data;
    private int _columns;

    public MatrixWrapper(T[] data, int rows, int columns)
    {
        _data = data;
        _columns = columns;
        // validate rows * columns == length
    }

    public T this[int r, int c]
    {
        get { return _data[Index(r, c)]; }
        set { _data[Index(r, c)] = value; }
    }

    private int Index(int r, int c)
    {
        return r * _columns + c;
    }
}

And you use it like:

        double[] data = new double[4800];
        var wrapper = new MatrixWrapper<double>(data, 80, 60);
        wrapper[2, 2] = 2.0;
+5
source
for (int i = 0; i < 800; ++i) {
    for (int j = 0; j < 600; ++j) {
        m[i, j] = a[600*i + j];
    }
}

i + 800*j.

+1

UPD ( , )

private static T[,] create2DimArray<T>(T[] array, int n)
        {
            if (n <= 0)
                throw new ArgumentException("Array M dimension cannot be less or equals zero","m");
            if (array == null)
                throw new ArgumentNullException("array", "Array cannot be null");
            if (array.Length == 0)
                throw new ArgumentException("Array cannot be empty", "array");

            int m = array.Length % n == 0 ? array.Length / n : array.Length / n + 1;
            var newArr = new T[m,n];
            for (int i = 0; i < arr.Length; i++)
            {
                int k = i / n;
                int l = i % n;
                newArr[k, l] = array[i];
            }

            return newArr;
        }

1000000 33 . 1 for.

+1

All Articles