Add ArrayUtility Comments
This commit is contained in:
parent
6495910cf4
commit
bf69b7fc3b
Binary file not shown.
|
@ -11,15 +11,15 @@ public class ArrayUtility {
|
||||||
* @return 1D array of combine all elements from 2D array
|
* @return 1D array of combine all elements from 2D array
|
||||||
*/
|
*/
|
||||||
public static int[] merge(int[][] d) {
|
public static int[] merge(int[][] d) {
|
||||||
int length = 0;
|
int length = 0; //Initialize length to store the column as we will pass this to the array constructor
|
||||||
for(int i = 0;i < d.length;i++)length+=d[i].length;
|
for(int i = 0;i < d.length;i++)length+=d[i].length; //SUM of X(nY) = length
|
||||||
int[] merged_array = new int[length];
|
int[] mergedArray = new int[length]; // Create a new array with size equal to length
|
||||||
int current_index = 0;
|
int currentIndex = 0; //Create a new variable to store the 2D Array Index
|
||||||
for(int i = 0;i < d.length;i++)for(int j = 0;j < d[i].length;j++) {
|
for(int i = 0;i < d.length;i++)for(int j = 0;j < d[i].length;j++) { //Loop through every Row and In each iteration of row, loop through every column
|
||||||
merged_array[current_index] = d[i][j];
|
mergedArray[currentIndex] = d[i][j]; //Set the 2D array element CI to 3D's IJ
|
||||||
current_index++;
|
currentIndex++; //Move the cursor to the next element
|
||||||
}
|
}
|
||||||
return merged_array;
|
return mergedArray;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -32,10 +32,10 @@ public class ArrayUtility {
|
||||||
*/
|
*/
|
||||||
public static int[][] split(int[] d, int n) {
|
public static int[][] split(int[] d, int n) {
|
||||||
if(n<=0) return new int[0][0]; //Return to prevent ArithmeticException: / by zero and negative array index
|
if(n<=0) return new int[0][0]; //Return to prevent ArithmeticException: / by zero and negative array index
|
||||||
if (d.length%n!=0)return new int[0][0]; //Return, not array is not splittable
|
if (d.length%n!=0)return new int[0][0]; //Return, empty array, array can't be split into n equal parts
|
||||||
int[][] splitted_array = new int[n][d.length/n]; //Create the splitted_array array and initialize it
|
int[][] splittedArray = new int[n][d.length/n]; //Create the splitted_array array and initialize it
|
||||||
for(int i = 0;i < n;i++)for(int j = 0;j<d.length/n;j++)splitted_array[i][j] = d[j*n+i];
|
for(int i = 0;i < n;i++)for(int j = 0;j<d.length/n;j++)splittedArray[i][j] = d[j*n+i]; //Loop for n Row and d.length/n column, the position of 2d array is row * ROW_SIZE + column
|
||||||
return splitted_array;
|
return splittedArray; //send the reference back
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void show(String[] x) {
|
public static void show(String[] x) {
|
||||||
|
|
Loading…
Reference in New Issue