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 3×3 two dimensional array

Solution

If you are familiar with 3D graphics API like DirectX or OpenGL they store 4×4 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

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *