//This Code is written by Siwat Sirichai
import java.util.Arrays;

public class ArrayUtility {
	
	/**
	 * combines a given 2D array into 1D array
	 * for example,
	 * { {1, 2}, {3, 4, 5} } -> {1, 2, 3, 4, 5}
	 * @param d
	 * @return 1D array of combine all elements from 2D array
	 */
	public static int[] merge(int[][] d) {
		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; //SUM of X(nY) = length
		int[] mergedArray = new int[length]; // Create a new array with size equal to length
		int currentIndex = 0; //Create a new variable to store the 1D Array Index
		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
			mergedArray[currentIndex] = d[i][j]; //Set the 1D array element CI to 2D's IJ
			currentIndex++; //Move the cursor to the next element
		}
		return mergedArray;
	}
	
	/** 
	 * splits a given 1D array into 2D array with n equal parts
	 * if the given array cannot be split into n equal part
	 * this method should return 2D array of size 0,0 (new int[0][0])
	 * @param d
	 * @param n number of parts for the target, 0 < n <= d.length
	 * @return 2D array
	 */
	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 (d.length%n!=0)return new int[0][0]; //Return, empty array, array can't be split into n equal parts
		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++)splittedArray[i][j] = d[i*(d.length/n)+j];//Loop for n Row and d.length/n column, the position of 2d array is row * ROW_SIZE + column, This assumption is only valid if ROW_SIZE are static (Splitted Array Are Rectangular)
		return splittedArray; //send the reference back
	}

	public static void show(String[] x) {
		System.out.println(Arrays.toString(x));
	}

	public static void show(String[][] x2d) {
		for (String[] x : x2d) {
			show(x);
		}
	}

	public static void show(int[] x) {
		System.out.println(Arrays.toString(x));
	}
	
	public static void show(int[][] x2d) {
		for (int[] x : x2d) {
			show(x);
		}
	}
}
