My code
class Union {
//Search Function
static boolean search(int A[], int i) {
for (int k = 0; k < A.length; k++) {
if (A[k] == i) {
return true;
}
}
return false;
}
//union
static void union(int A[][], int B[][]) {
int i = 0;
int count = 0;
int C[] = new int[A.length + B.length];
for (; i < A.length; i++) {
if (!(search(B, A[i]))) {
C[count] = A[i];
count++;
}
}
for (; i < (A.length + B.length); i++) {
C[count] = B[i - A.length];
count++;
}
System.out.println("This is Union Of 2 D Array ");
System.out.println();
for (int k = 0; k < count; k++) {
System.out.println(C[k]);
}
System.out.println();
}
public static void main(String... s) {
union(new int[]{1, 1, 1, 4,}, new int[]{1, 4, 4, 4, 1, 2});
}
}
I am using this output to find union of 2d array .but output which i am getting is wrong . i don't want 2 use any predefined interface and method in java . my answer should be {1,2,4}
Example
A= {1,2,3,3}
B={2,3,1,1}
c={1,2,3}
This is what you are looking for:
import java.util.Arrays;
public class Union
{
public static void main(String[] args)
{
int[] A = {1, 2, 3, 3};
int[] B = {2, 3, 1, 1};
System.out.println(Arrays.toString(unionArrays(A, B)));
}
/* Union of multiple arrays */
public static int[] unionArrays(int[]... arrays)
{
int maxSize = 0;
int counter = 0;
for(int[] array : arrays) maxSize += array.length;
int[] accumulator = new int[maxSize];
for(int[] array : arrays)
for(int i : array)
if(!isDuplicated(accumulator, counter, i))
accumulator[counter++] = i;
int[] result = new int[counter];
for(int i = 0; i < counter; i++) result[i] = accumulator[i];
return result;
}
public static boolean isDuplicated(int[] array, int counter, int value)
{
for(int i = 0; i < counter; i++) if(array[i] == value) return true;
return false;
}
}
OUTPUT:
[1, 2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With