Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rows and columns if arrays is only 1D using for loops

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?

like image 871
Amani Lama Avatar asked Mar 30 '13 19:03

Amani Lama


4 Answers

 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];
     }
 }
like image 128
Rob G Avatar answered Oct 21 '22 10:10

Rob G


private int getElem(int[] arr, int i, int j){
  return arr[i*colNum+j];
}
like image 35
gkiko Avatar answered Oct 21 '22 08:10

gkiko


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

like image 30
CodeGuy Avatar answered Oct 21 '22 10:10

CodeGuy


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.

like image 1
Steven Morad Avatar answered Oct 21 '22 10:10

Steven Morad