-2

I have been given an exercise involving two arrays. For example:

String [] array1 = { "Tv","Iphone","Pc" };
String [] array2 ={"Tv" , "Pc"}

(In reality, these arrays may contain some hundred elements coming from files.)

  1. I need to find all elements / the element ? of the first array that do / does not exist in the second array. I was thinking of using a for loop or StringTokenizer. I need to resolve this exercise using only arrays.

  2. How can I add some raw int the second array to say that i missed this data.

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Junior Fulcrum
  • 153
  • 1
  • 1
  • 7

2 Answers2

0
// Variables
String [] array1 = {"a", "b", "c", "d"};
String [] array2 = {"a", "c", "e"};
String [] distinct = new String[array1.length];
int i, j, k = 0;
boolean match;

// Search
for (i = 0; i < array1.length; i++) {
    match = false;
    for (j = 0; j < array2.length; j++) {
        if (array1[i].equals(array2[j])) { match = true; break; }
    }
    if (!match) { distinct[k] = array1[i]; k++; }
}

// Output
for (i = 0; i < k; i++) {
    System.out.println(distinct[i]); // b, d
}
0

Given these two arrays as an example:

    String[] arr1 = new String[] {"A", "B", "C", "D", "E"};
    String[] arr2 = new String[] {"A", "C", "D"};

Well, using only arrays, I would do something like this:

First, make a method to see if an array contains some value:

public boolean aContainsB(String[] a, String b) {
    for (String s : a) if (s.equals(b)) return true;
    return false;
}

Then, create a new array that is as large as the largest one. It will hold the values that are not in the array. It can potentially be every letter, I am assuming.

    String[] notFound = new String[Math.max(arr1.length, arr2.length)];

Then, loop through the first array, and if the current value is not in the second array, append it to the not found array.

    int i = 0;
    for (String s : arr1) if (!aContainsB(arr2, s)) notFound[i++] = s;

At the end of this, i will contain how many values are not present in the second array, and you can loop through the notFound array i times to print it out.

    System.out.println("There are " + i + " elements in arr1 that are not in arr2, they are:");
    for (int j = 0; j < i; j++) {
        System.out.println("The String: " + notFound[j]);
    }

The output will be:

There are 2 elements in arr1 that are not in arr2, they are:
The String: B
The String: E
Steven Jeffries
  • 3,522
  • 2
  • 20
  • 35