Connecting Tech Pros Worldwide Help | Site Map

Compare 2 array

Newbie
 
Join Date: Oct 2006
Posts: 1
#1: Oct 18 '06
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..
Lives Here
 
Join Date: Sep 2006
Posts: 12,070
#2: Oct 19 '06

re: Compare 2 array


Quote:

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:

Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. public class Duplicates {
  3.     public static void main(String[] args) {
  4.         BufferedReader inFile = null;
  5.  
  6.         try {
  7.             inFile = new BufferedReader(new InputStreamReader(System.in));
  8.             System.out.print("Enter number of numbers to be entered: ");
  9.             int a = Integer.parseInt(inFile.readLine());
  10.             System.out.println("Enter the numbers one by one");
  11.             int[] array = new int[a];
  12.             for(int i = 0; i < array.length; i++) {
  13.                 array[i] = Integer.parseInt(inFile.readLine());
  14.             }
  15.             int[] temp = new int[a];
  16.             int j = 0; int count = 0;
  17.             for(int i = 0; i < array.length; i++) {
  18.                 if(!Duplicates.in(temp, array[i])) {
  19.                     temp[j++] = array[i];
  20.                     count++;
  21.                 }
  22.             }
  23.             int[] noDup = new int[count];
  24.             for(int i = 0; i < count; i++) {
  25.                 noDup[i] = temp[i];
  26.             }
  27.  
  28.  
  29.             System.out.print("\nOriginally entered: ");
  30.             for(int i = 0; i < array.length; i++) {
  31.                 System.out.print(array[i] + " ");
  32.             }
  33.             System.out.print("\nWith duplicates removed: ");
  34.             for(int i = 0; i < noDup.length; i++) {
  35.                 System.out.print(noDup[i] + " ");
  36.             }
  37.  
  38.         }
  39.         catch(Exception e) {
  40.             e.printStackTrace();
  41.         }
  42.     }
  43.     public static boolean in(int[] a, int x) {
  44.         boolean isIn = false;
  45.         for(int i = 0; i < a.length; i++) {
  46.             if(a[i] == x) {
  47.                 return true;
  48.             }
  49.         }
  50.         return isIn;
  51.     }
  52.  
  53. }
Reply