Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like a function to convert a single dimension array int[480000] into a 2d array of size int[800,600]. Can you please help me how this can be done?

like image 200
mouthpiec Avatar asked Jul 24 '10 05:07

mouthpiec


People also ask

What does int [] mean in C?

int. Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0 , -5 , 10. We can use int for declaring an integer variable.

How do you make an array into a number?

To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers.

What atoi does in C?

Description. The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.

How do you convert an array of strings to integers?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.


2 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;
}
like image 137
Jaroslav Jandek Avatar answered Sep 20 '22 00:09

Jaroslav Jandek


Do you really want to physically move the data or would a 800x600 'View' be sufficient?
You could use a wrapper like this:

// 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;
like image 21
Henk Holterman Avatar answered Sep 20 '22 00:09

Henk Holterman