0

Create Function for Convert 2d array into 1D array

But at Declaration time the size of 1D array how to give size to the new 1D array

int[] convert(int[][] input){
    int[] result;
    int z=0;
    for(int row=0;row<input.length;row++) {
        for(int col=0;col<input[row].length;col++) {
            result[z]=input[row][col];
            z++;
        }
    }
    return result;/* Error comes here For Initialization. How to initialize before Knowing size*/
}
2
  • "How to initialize before Knowing size" <- For an array not possible. Just determine the needed size before you initialize your new array. Commented Feb 7, 2018 at 13:31
  • You could iterate your 2d array beforehand, then count all lengths of all sub-arrays and add them together. Commented Feb 7, 2018 at 13:33

5 Answers 5

5

if rows and columns are balanced

int result[] = new int[input.length * input[0].length];

otherwise, you have to loop through the whole array while keeping a count of length

int len = 0;
for(int[] a : input){
    len+=a.length;
}
int[] result = new int[len];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Pavneet_Singh that's correct.Once again Thanks a lot.
i am glad that we could help, happy coding
1

You can simply compute the size this way (i.e number of rows * number of columns):

int[] result = new int[input.length * input[0].length] ;

4 Comments

This will only work if all sub arrays have the same length, i.e. if the 2d array is rectangular.
You're right, I was assuming that the 2D array was rectangular (2D meaning 2 dimensions, I wouldn't think that one was fixed and another varying).
Thanks a lot, Great. It Was working. What if the both Array have Different Size eg: int [][]y= {{10,20,30,40},{2,6,8,7,6,9}};
@DheerajThakur : In that case, see the answer from Pavneet_Singh .
0

1)If it is rectangular 2D array, compute the size this way

int array[]  = new int[input.length * input[0].length];

2)If it is not rectangular, iterate through each row and add the length of each sub-array

int size = 0;
for(int i=0;i<input.length;i++){
 size += input[i].length;
}

Comments

0

Or you could just use streams with out to have to take care of size by yourself:

int[] convert(int[][] input){    
    return Stream.of(input).flatMapToInt(x -> Arrays.stream(x)).toArray();
}

Comments

0

The below code converts / flattens 2D array to 1D (row-wise)

(MxM)- Row Wise

 private static int[] convert2Dto1DArrayMxM(int[][] input) {

    //Get total elements to calculate the length of result Array
    //Since it is MXM totalElements calculation is = rowsLength x row[0].length

    int totalElements = input.length * input[0].length;

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;
    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[0].length; col++) {
            result[resultIndex] = input[row][col];
            resultIndex++;
        }
    }
    return result;
}

(MxN)- Row Wise

private static int[] convert2Dto1DArrayMxN(int[][] input) {
    
   //Get total elements in input array to calculate the length of result Array

    int totalElements = 0;
    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[row].length; col++) {
            totalElements++;
        }
    }

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;

    for (int row = 0; row < input.length; row++) {
        for (int col = 0; col < input[row].length; col++) {
            result[resultIndex] = input[row][col];
            resultIndex++;
        }
    }

    return result;
}

(MxM)- Column Wise

 private static int[] convert2Dto1DArrayMxMColumnWise(int[][] input) {

    //Get total elements to calculate the length of result Array
    //Since it is MXM totalElements calculation is = rowsLength x row[0].length

    int totalElements = input.length * input[0].length;

    //Populate the result Array

    int[] result = new int[totalElements];
    int resultIndex = 0;
    for (int column = 0; column < input[0].length; column++) {
        for (int row = 0; row < input.length; row++) {
            result[resultIndex] = input[row][column];
            resultIndex++;
        }
    }
    return result;
}

How to use:

  public static void main(String[] args) {

     //MXM - Row Wise

    int[][] mXm = {{2, 19}, {6, 80}, {42, 10}};
    int[] mXmResult = convert2Dto1DArrayMxM(mXm);
    System.out.println(Arrays.toString(mXmResult));

    //MXN - Row Wise

    int[][] mXn = {{2, 19, 0, 1, 4, 6, 3, 2, 1, 6}, {2, 0}, {2, 0, 1, 5}};
    int[] mXnResult = convert2Dto1DArrayMxN(mXn);
    System.out.println(Arrays.toString(mXnResult));

    //MxM - Column Wise

    int[][] mXmColumnWise = {{2, 19,10}, {6, 80,9}};
    int[] mXmResultColumnWise = convert2Dto1DArrayMxMColumnWise(mXmColumnWise);
    System.out.println(Arrays.toString(mXmResultColumnWise));
}

Sample output for the above main()

MxM - Row Wise [2, 19, 6, 80, 42, 10]

MxN - Row Wise [2, 19, 0, 1, 4, 6, 3, 2, 1, 6, 2, 0, 2, 0, 1, 5]

MxM - Column Wise [2, 6, 19, 80, 10, 9]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.