In: Computer Science
java
1.) a method to append a 2d double array at the right of another 2d double array, return a new array.
E.g. numss1: {{1, 2}, {3, 4, 5}, {6}}, numss2: {{7}, {8, 9}}, return {{1, 2, 7}, {3, 4, 5, 8, 9}, {6}}
The required method is given below:
//method to append array
public static int[][] appendArray(int arr1[][], int arr2[][])
{
int maxCol=0;
for(int i=0; i<arr1.length; i++)
{
if(i<arr2.length)
{
if((arr1[i].length+arr2[i].length) > maxCol)
{
maxCol = arr1[i].length+arr2[i].length;
}
}
else
{
if((arr1[i].length) > maxCol)
{
maxCol = arr1[i].length;
}
}
}
int newArr[][] = new int[arr1.length][maxCol];
for (int i = 0; i < arr1.length; i++)
{
int j;
for (j = 0; j < arr1[i].length; j++)
{
newArr[i][j] = arr1[i][j];
}
if(i<arr2.length)
{
for (int k=0;k < arr2[i].length; k++)
{
newArr[i][j+k] = arr2[i][k];
}
}
}
return newArr;
}
The complete program source code including the above method for testing is given below:
public class Main
{
//method to append array
public static int[][] appendArray(int arr1[][], int arr2[][])
{
int maxCol=0;
for(int i=0; i<arr1.length; i++)
{
if(i<arr2.length)
{
if((arr1[i].length+arr2[i].length) > maxCol)
{
maxCol = arr1[i].length+arr2[i].length;
}
}
else
{
if((arr1[i].length) > maxCol)
{
maxCol = arr1[i].length;
}
}
}
int newArr[][] = new int[arr1.length][maxCol];
for (int i = 0; i < arr1.length; i++)
{
int j;
for (j = 0; j < arr1[i].length; j++)
{
newArr[i][j] = arr1[i][j];
}
if(i<arr2.length)
{
for (int k=0;k < arr2[i].length; k++)
{
newArr[i][j+k] = arr2[i][k];
}
}
}
return newArr;
}
public static void display(int arr[][])
{
System.out.println("\nThe 2D array is: ");
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
{
if(arr[i][j]!=0)
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public class Main
{
//method to append array
public static int[][] appendArray(int arr1[][], int arr2[][])
{
int maxCol=0;
for(int i=0; i<arr1.length; i++)
{
if(i<arr2.length)
{
if((arr1[i].length+arr2[i].length) > maxCol)
{
maxCol = arr1[i].length+arr2[i].length;
}
}
else
{
if((arr1[i].length) > maxCol)
{
maxCol = arr1[i].length;
}
}
}
int newArr[][] = new int[arr1.length][maxCol];
for (int i = 0; i < arr1.length; i++)
{
int j;
for (j = 0; j < arr1[i].length; j++)
{
newArr[i][j] = arr1[i][j];
}
if(i<arr2.length)
{
for (int k=0;k < arr2[i].length; k++)
{
newArr[i][j+k] = arr2[i][k];
}
}
}
return newArr;
}
public static void display(int arr[][])
{
System.out.println("\nThe 2D array is: ");
for (int i = 0; i < arr.length; i++)
{
for (int j = 0; j < arr[i].length; j++)
{
if(arr[i][j]!=0)
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
int numss1[][] = {{1, 2}, {3, 4,
5}, {6}};
int numss2[][] = {{7}, {8,
9}};
display(numss1);
display(numss2);
int newArr[][] =
appendArray(numss1, numss2);
display(newArr);
}
}
OUTPUT:
The 2D array is:
1 2
3 4 5
6
The 2D array is:
7
8 9
The 2D array is:
1 2 7
3 4 5 8 9
6