0

I have a generic method

public static <T> boolean lessThanOrEqualTo(T[] arr1, T[] arr2) {

    for(int i = 0; i < arr1.length; i++) {
    T current = arr1[i];
    boolean[] track = new boolean[arr2.length];
    for(int j = 0; j < arr2.length; j++) {

        track[j] = current.equals(arr2[j]);

        if(j == arr2.length-1) {
            for(int k = 0; k < track.length; k++) {
                if(track[k] == true) {
                    System.out.println(Arrays.toString(track));
                    return true;
                }
            }
        }
    }
    System.out.println(Arrays.toString(track));
}
return false

}

I have to return true if every item in arr1 is inside arr2.

Example:

lessThanOrEqualTo({ "Bill", "Mark", "Bill", "Mark", "Bill"}, 
 {"Bill", "Alex", "Mark"});

returns true because every item of arr1 is in arr2.

How can I go about this problem?

2 Answers2

1

Here is the solution using Set

public static <T> boolean lessThanOrEqualTo(T[] arr1, T[] arr2) {
   Set<T> a = new HashSet<>(Arrays.asList(arr1));
   Set<T> b = new HashSet<>(Arrays.asList(arr2));
   a.removeAll(b);
   return a.isEmpty();
}
Ashraful Islam
  • 12,470
  • 3
  • 32
  • 53
0

one way of doing it is to use Set. in terms of speed its probably slower, but easier to understand.

public static <T> boolean lessThanOrEqualTo(T[] arr1, T[] arr2) {
  Set<T> firstSet=new HashSet<T>(Arrays.asList(arr1));
  Set<T> secondSet=new HashSet<T>(Arrays.asList(arr2));
  int countOfFirst=firstSet.size();
  firstSet.retainAll(secondSet);
  return firstSet.size() == countOfFirst;
}
nafas
  • 5,283
  • 3
  • 29
  • 57
  • This worked nicely, however, I dont understand how it's working. –  Nov 24 '15 at 17:33
  • @CodeDexter hmm, have a read through this document, hopefully it gives a notion of what set is: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html – nafas Nov 25 '15 at 09:14