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]