0

I am looking for some advice on how I can create a method that generates a 2D array based two parameters, an integer s that will dictate the number of rows of the 2D array and int x[] would be where different 1D arrays of length 20 will fill each row of the 2D array. So far this the the method that I came up with but it only fills each row with 0s only one row is filled with the input array. I basically need a to fill each row of a autogenerated 2D array with a bunch of same sized 1D arrays. please help. thx !

public class c {
   public int [][] f;

   public int [][] a(int x[], int s){
    f = new int [s][20];
    for(int j = 0; j < x.length; j++) {
        f[s-1][j] = x[j];
    }
   return f;
 }

  public void d(){
    for (int i =0; i < f.length; i++) {
        for(int j = 0; j < f[i].length; j++) {
            System.out.print(f[i][j] + " ");
        }
    System.out.println(" ");
    }
  } 
}
Sam D
  • 1
  • You are initializing only one row f[s-1][j] = x[j]; and each time a() function is called you are creating new 2D array and initializing only one row in it. – Hrudayanath Nov 12 '18 at 07:07
  • Possible duplicate of [How to convert a 1d array to 2d array?](https://stackoverflow.com/questions/5134555/how-to-convert-a-1d-array-to-2d-array) – LuCio Nov 12 '18 at 08:42

2 Answers2

0

I can see, that all you need to do is just create 2D array with given number of rows and copy given 1D array to the to the each row. This is pretty simple:

  • Create new 2D array
  • Iterate over each row and put given array into it

Example:

public static int[][] createArray(int[] arr, int totalRows) {
    int[][] res = new int[totalRows][arr.length];

    for (int row = 0; row < totalRows; row++)
        System.arraycopy(arr, 0, res[row], 0, res[row].length);

    return res;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written – WhatsThePoint Nov 12 '18 at 08:29
0

This can be achieved using stream api in java

int[][] arrInt = { { 1, 2 }, { 3, 4, 5 } };
int result[] = Arrays.stream(arrInt).flatMapToInt(Arrays::stream).toArray();
System.out.println(Arrays.toString(result));
Navin Gelot
  • 1,264
  • 3
  • 13
  • 32