I was used to Matlab
's feature where you can make a matrix and get A[i][j]
and things like that. Now I am using Java and we can only use one dimensional array. I am suppose to modify the entries (i:for rows and j:for columns) using a nested for loop but I am not sure how to access them if they are stored in an 1D array. Can someone please help me out? How difficult is it?
int rows = 3;
int cols = 4;
int[] array = new int[rows*cols];
int[] currentRow = new int[cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
currentRow[j] = array[i*cols + j];
}
}
private int getElem(int[] arr, int i, int j){
return arr[i*colNum+j];
}
Note that in Java, you can also use a 2D array like so:
int[][] my2DArr = new int[4][3]; //creates a 2D array with 4 rows and 3 columns
int value = my2DArr[2][1]; //gets the value at row 2 and column 1
Now, if you have to use a 1D array which is representing a 2D array, you can do some simple math to find out the position of a given row, column pair if you know the number of columns and number of rows. See here: Convert a 2D array into a 1D array
I hope I'm understanding this correctly.
Say you have a 10x10 2D array and you want it to be one dimensional.
You can make array[0] to array[9] the first row of the 2D array. Then array[10] to array[19] is the second row of the 2D array.
There is probably a more efficient way of doing this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With