Search code examples
javaarraysunionnested-loops

Java Union array of 2 int arrays using nested loops


I want to create a union array for two integer arrays using nested loops.

This is my attempt so far:

import java.util.Scanner ;

public class array4 {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);


        System.out.print("Enter first array size:");
        int size = input.nextInt();
        int x[] = new int[size];


        System.out.println("Enter first array elements:");
        for (int i = 0; i < size; i++) {
            x[i] = input.nextInt();


        }
        System.out.print("Enter second array size:");
        int size2 = input.nextInt();
        int y[] = new int[size2];
        for (int i = 0; i < size2; i++) {
            y[i] = input.nextInt();
        }


        System.out.println("Union");
        for (int i = 0; i < size; i++) {
            System.out.println(x[i]);
        }

        for (int i = 0; i < size2; i++) {
            for (int z = 0; z < size; z++) {
                if (y[i] != x[z]) {
                    System.out.println(y[i]);
                }
            }
        }

    }
}

Solution

  • Lets assume that we will print all numbers from second array, and only these numbers from first array which don't exist in second one. So

    1. for each element in first array
      1. test if it exist in second array (iterate over elements in second array and set some boolean flag like exists to true if x[i]==y[j])
      2. if element doesn't exist in second array print it
    2. iterate over elements from second array
      1. and print them

    Algorithm can look like

    for (int i = 0; i <= x.length; i++) {// "<=" is not mistake, 
                                         // in last iteration we print all elements 
                                         // from second array
        boolean exist = false;
        for (int j = 0; j < y.length; j++) {
            if (i < x.length) {
                if (x[i] == y[j])
                    exist = true;
            } else
                System.out.println(y[j]);
        }
        if (!exist && i < x.length)
            System.out.println(x[i]);
    }
    

    This algorithm can be probably rewritten to something simpler but I will leave it in this form for now.