Compare 2 array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hoho2san
    New Member
    • Oct 2006
    • 1

    #1

    Compare 2 array

    Hi..can anybody give coding for:

    user input number of random number to generate.
    then, add it to array.

    the output like this:

    array A = [ 1 2 2 3 4 5 6 2 2]

    array B = [ 1 2 3 4 5 6 ]

    *the repeat number in array A will not be display again in array B

    now im still doing coding for it..
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by hoho2san
    Hi..can anybody give coding for:

    user input number of random number to generate.
    then, add it to array.

    the output like this:

    array A = [ 1 2 2 3 4 5 6 2 2]

    array B = [ 1 2 3 4 5 6 ]

    *the repeat number in array A will not be display again in array B

    now im still doing coding for it..
    Here is a solution with an amazing number of for loops:

    Code:
    import java.io.*;
    public class Duplicates {
    	public static void main(String[] args) {
    		BufferedReader inFile = null;
    
    		try {
    			inFile = new BufferedReader(new InputStreamReader(System.in));
    			System.out.print("Enter number of numbers to be entered: ");
    			int a = Integer.parseInt(inFile.readLine());
    			System.out.println("Enter the numbers one by one");
    			int[] array = new int[a];
    			for(int i = 0; i < array.length; i++) {
    				array[i] = Integer.parseInt(inFile.readLine());
    			}
    			int[] temp = new int[a];
    			int j = 0; int count = 0;
    			for(int i = 0; i < array.length; i++) {
    				if(!Duplicates.in(temp, array[i])) {
    					temp[j++] = array[i];
    					count++;
    				}
    			}
    			int[] noDup = new int[count];
    			for(int i = 0; i < count; i++) {
    				noDup[i] = temp[i];
    			}
    
    
    			System.out.print("\nOriginally entered: ");
    			for(int i = 0; i < array.length; i++) {
    				System.out.print(array[i] + " ");
    			}
    			System.out.print("\nWith duplicates removed: ");
    			for(int i = 0; i < noDup.length; i++) {
    				System.out.print(noDup[i] + " ");
    			}
    
    		}
    		catch(Exception e) {
    			e.printStackTrace();
    		}
    	}
    	public static boolean in(int[] a, int x) {
    		boolean isIn = false;
    		for(int i = 0; i < a.length; i++) {
    			if(a[i] == x) {
    				return true;
    			}
    		}
    		return isIn;
    	}
    
    }

    Comment

    Working...