public class MyProgram {
// Method to convert a 2D array into a 1D array
public static int[] convertTo1D(int[][] twoDArray) {
// Determine the total number of elements in the 2D array
int totalElements = 0;
for (int i = 0; i < twoDArray.length; i++) {
totalElements += twoDArray[i].length;
}
// Create a 1D array to hold all elements
int[] oneDArray = new int[totalElements];
// Fill the 1D array with elements from the 2D array
int currentIndex = 0; // Track where to place the next element in the 1D array
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[i].length; j++) {
oneDArray[currentIndex++] = twoDArray[i][j];
}
}
return oneDArray;
}
public static void main(String[] args) {
// Test cases
int[][] testArray1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] testArray2 = {{1}, {2, 3}, {4, 5, 6}};
// Convert and display the results for the first test case
int[] result1 = convertTo1D(testArray1);
System.out.println("Result 1: ");
for (int value : result1) {
System.out.print(value + " ");
}
System.out.println(); // For better formatting in output
// Convert and display the results for the second test case
int[] result2 = convertTo1D(testArray2);
System.out.println("Result 2: ");
for (int value : result2) {
System.out.print(value + " ");
}
System.out.println(); // For better formatting in output
}
}
This program begins with defining the convertTo1D method, which computes the size of the 1D array by counting all elements within the 2D array, then creates a 1D array of that size, and finally, fills this array with elements from the 2D array.
In the main method, two test arrays (testArray1, testArray2) are defined, each having a different structure. We then call convertTo1D with these arrays and print the resulting 1D arrays to verify that the method operates as expected.