Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1D array index to 2D array index

Tags:

arrays

c#

I have 2 arrays. I want to convert the index of the first array to the second. Is there a better way to do it than what I have below?

Array array1[9];
Array array2[3][3];

// Index is the index of the 1D array
public Point convert1Dto2D(int index)
{
        Point p = new Point();

        switch (index) {
            case 0:
                p.x = 0;
                p.y = 0;
                break;
            case 1:
                p.x = 0;
                p.y = 1;
                break;
            case 2:
                p.x = 0;
                p.y = 2;
                break;
            case 3:
                p.x = 1;
                p.y = 0;
                break;
            case 4:
                p.x = 1;
                p.y = 1;
                break;
            case 5:
                p.x = 1;
                p.y = 2;
                break;
            case 6:
                p.x = 2;
                p.y = 0;
                break;
            case 7:
                p.x = 2;
                p.y = 1;
                break;
            case 8:
                p.x = 2;
                p.y = 2;
                break;
        }

return p;
}
like image 920
Arizona1911 Avatar asked Mar 31 '11 03:03

Arizona1911


People also ask

How do you convert a 1D array to a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.

How is a 2D array indexed?

Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.

Are 1D arrays faster than 2D?

Unless you are talking about static arrays, 1D is faster. Clearly the 2D case loses the cache locality and uses more memory. It also introduces an extra indirection (and thus an extra pointer to follow) but the first array has the overhead of calculating the indices so these even out more or less.


1 Answers

p.x = index / 3;
p.y = index % 3;
like image 169
Sapph Avatar answered Oct 02 '22 04:10

Sapph