Reputation: 25
Implementing a 2-dim array using a row-major 1-dim array I got till here, I do not understand how I can finish the code to implement the 2-dim array, Please Help!
public class TwoDimArray {
int[] a = null;
public TwoDimArray(int r, int c){}
public int get(int i, int j) {}
public int[] getRow(int i) {}
public int[] getCol(int j) {}
}
Upvotes: 2
Views: 481
Reputation: 23
addition to Eran & ajb answers, this how you can get the row (i) and column (j) of the matrix
Columns = number of columns
for (int i=0; i < oneDimension.length; i++)
{
int rowIndex = i / Columns;
int columnIndex = i % Columns;
}
Upvotes: 0
Reputation: 393851
I'm not sure what row-major means, but I'll assume it means that the elements are positioned in the 1-dim array by row (i.e. the first c
elements form the first row, the next c
elements form the second row, etc...).
The constructor is simple - you create an array of r*c
elements.
Getting the (i,j) element is a matter of math - find a formula that given a row index i
and a column index j
, calculates the location in the array of the (i,j) element. Hint - the formula involves multiplying the request row by the column length.
Getting a row array is straight forward, since the elements of the 1-dim array that represent a single row at contiguous. As I mentioned before, the first c
elements are the first row, etc...
Getting a column array involves finding the (i,j) element for each i (when j is constant).
Upvotes: 1
Reputation: 31699
This looks like homework, so I'm not going to give you a complete answer, but here are some thoughts that will hopefully get you started:
If you want to represent a 5x7 array (5 rows, 7 columns), you'll need to create a one-dimensional array with 35 elements (35 = 5 * 7).
The first 7 elements of a
will be row 0; thus
get(0,0)
will access a[0]
get(0,1)
will access a[1]
get(0,2)
will access a[2]
and so on.
The 7 elements for the first row will be followed by 7 elements for the next row, and then 7 for the row after that; this means that
get(0,0)
will access a[0]
get(1,0)
will access a[7]
get(2,0)
will access a[14]
and so on. I think you should be able to figure out the pattern and therefore get a good idea of how to make this work.
Upvotes: 0