Row Major and Column Major in 2D Array

Problem

Given a one dimensional integer array of 9 elements. Write a function to map the array into a row major 3x3 two dimensional array

Solution

If you are familiar with 3D graphics API like DirectX or OpenGL they store 4x4 transformation matrices as a linear array of 16 elements. In DirectX the format is row major but in OpenGL it is column major. Row major means the first row of the two dimensional array is stored in the one dimensional array followed by the second row and so on while column major is the opposite. The problem of converting 2 dimensional indexing into a linear indexing is very easy. Given a two dimensional coordinate (i, j) then the corresponding linear coordinate is k = n * i + j where n is the size of the array and i, j both start at 0

Code

Here is a sample C++ code to do that

class TwoDimensional
{
	private:
	int A[9];

	public:
	//Let us hardcode the values 
	//for the sake of demonstration
	TwoDimensional()
	{
		A[0] = 0;
		A[1] = 1;
		A[2] = 2;

		A[3] = 3;
		A[4] = 4;
		A[5] = 5;

		A[6] = 6;
		A[7] = 7;
		A[8] = 8;
	}

	//Do the mapping here
	int Get(int i, int j)
	{
		if (i >= 0 && i <=2 && j >=0 && j <=2)
		{
			return A[3*i + j]
		}
		else
		{
			return -1;
		}
	}
};
Tags:

Leave a Reply