Reputation:
I want to create a multi-dimensional array from a single dimensional array in java.
my single dimenstional array is like
int[] grid = {5, 3, 1, 2, 0, 4, 1, 1, 3 };
I want to create a matrix of 3x3 diminsions at runtime as there are 9 elements in this array. Can anyone suggest some good idea for this. Can anyone suggest me what should I do in below code so that it can give me arraylist of 3 arrays or if someone can suggust me some better idea to perform this correctly. I know there is error in my below code.
ArrayList<int[]> matrix = new ArrayList<>();
int[] tempArray = new int[n];
int j = 0;
for(int i=0 ; i<=grid.length; i++){
if((i+1) / 3 == 0){
matrix.add(tempArray);
j=0;
}else{
tempArray[j] = grid[i];
j++;
}
}
Thanks
Upvotes: 1
Views: 1064
Reputation: 599
public class sample {
public static void main(String args[])
{
int[] grid = {5, 3, 1, 2, 0, 4, 1, 1, 3 };
int i=0,j=0;
int count=-1;int k;
int[][] arr=new int[3][3];
for(i=0;i<3;i++)
{
count++;
for(j=0;j<3;j++)
{
if(count == 0)
{
k=j;
arr[i][j]=grid[k];
}
if(count == 1)
{
k=j+3;
arr[i][j]=grid[k];
}
if(count == 2)
{
k=j+6;
arr[i][j]=grid[k];
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println(" ");
}
}
}
Upvotes: 0
Reputation: 193824
Java does multi-dimensional arrays natively; you don't need to create your own using arrays in an ArrayList
.
Something like this should give you what you want:
int[] grid = {5, 3, 1, 2, 0, 4, 1, 1, 3 };
int [][] matrix = new int[3][3];
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
matrix[x][y] = grid[x + y * 3];
}
}
Upvotes: 4
Reputation: 106508
Your iteration steps too far off of the array; grid.length
gives you the value 9, and the highest index is 8 - change your ending condition to be strictly less than the length.
You also don't reinitialize a new array when you're ready to put it into the ArrayList
. I would suggest that, after you add the matrix, you create a new instance of tempArray
:
matrix.add(tempArray);
tempArray = new int[n];
j++;
Don't reset j
to 0 when you're ready to re-add some elements to your ArrayList
- this puts it right back where it started. Same issue with incrementing i
automatically - you'll have to be aware that i
may have advanced further than you intended it to.
Lastly, I would advise on using the modulus operator instead of dividing it that way - modulo works in the same manner, and would be easier to read.
if(i % 3 == 0) { // Analogous to adding one and dividing by 3.
Upvotes: 0