Duermeduerme
Duermeduerme

Reputation: 23

Create a 2d array from an ArrayList<Integer>

I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][]. This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2} {3,0}

public static int[][] convertIntegers(ArrayList<Integer> integers){
        int m = (int) Math.sqrt(integers.size());
        int[][] ret = new int[m][m];

        int cont = 0;

        for(int i=0; i<m+1 ; i++)
       {
           for(int j=0; j<m; j++)
           {
               cont = cont + 1;
               ret[i][j] = integers.get(cont);
               ;
           }
       }
       return ret;}

Upvotes: 0

Views: 56

Answers (1)

janos
janos

Reputation: 124804

Your implementation is almost ok, except for some off-by-one errors:

  • You need to increment cont after the integers.get call, not before. If you increment before, then the first element of the list will be skipped. An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j.
  • The outer loop should go until i < m instead of i < m + 1

With the errors fixed:

for (int i = 0, cont = 0; i < m; i++) {
  for (int j = 0; j < m; j++, cont++) {
    ret[i][j] = integers.get(cont);
  }
}

Btw, another way is without using cont at all, calculating the correct position using i, j and m:

for (int i = 0; i < m; i++) {
  for (int j = 0; j < m; j++) {
    ret[i][j] = integers.get(i * m + j);
  }
}

Upvotes: 3

Related Questions