0

Possible Duplicate:
Check whether an array is a subset of another

I have array a = { 1,4,3,5,1,2,3,6 } and array b= { 1,2,3 }.

How can I check if array b elements appear anywhere in array a? Any help will be appreciated. Thanks.

Community
  • 1
  • 1
user1172575
  • 59
  • 1
  • 7
  • 3
    It's trivial in `O(n^2)`. It is relatively easy in `O(n log n)` as well. What have you tried? – John Dvorak Nov 15 '12 at 17:47
  • 1
    Just FYI, answered here: http://stackoverflow.com/questions/1128723/in-java-how-can-i-test-if-an-array-contains-a-certain-value –  Nov 15 '12 at 17:48
  • should the elements be placed together or each element of b can be found anywhere within a? – Abhishek Bhatia Nov 15 '12 at 17:48
  • Are you allowed to modify your arrays, in particular to sort them? Are thes `int[]` arrays of primitive type, or `Integer[]` arrays containing objects? The latter would work well with `new HashSet(Arrays.asList(…)).containsAll(…)`. – MvG Nov 15 '12 at 17:52
  • @assylias, what works for `ArrayList` won't work for primitive arrays of primitive element type. – MvG Nov 15 '12 at 17:53
  • @ Abhishek Bhatia, the elements of b should be placed together and found anywhere in a. Thanks. – user1172575 Nov 15 '12 at 18:17
  • @user1172575 I'm not sure you understood the question of @AbhishekBhatia In your example the elements of `b` are not *together* in `a`. – madth3 Nov 15 '12 at 19:11

2 Answers2

5

The easiest way is obviously to use the built-in functions. However, Java only has built-in functions to do this for Collection types. If the arrays are not of primitive types, you can do this:

if (Arrays.asList(a).containsAll(Arrays.asList(b))) {
   //...
}

If it's a primitive array (int[], etc) this is still the easiest approach, you just need to convert the array into a list manually or using a third-party library. Guava has functions for this:

if ( Ints.asList(a).containsAll(Ints.asList(b)) ) {
   //...
}
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • Thanks, I converted the arrays to lists but still can't recognize the Ints.asList and this is the code. //convert our arrays to lists List alist = (List) Arrays.asList(a); List blist = (List) Arrays.asList(b); if (Ints.asList(blist).containsAll(Ints.asList(a))) { System.out.print("yes"); }else System.out.print("no"); – user1172575 Nov 15 '12 at 18:15
  • @user1172575 In a comment you said the elements of `b` should be together but this will return true even if they are not. – madth3 Nov 15 '12 at 18:30
  • @madth3, if they're not fount in b, it should return false, why it would return true even if they're not? – user1172575 Nov 15 '12 at 18:37
  • @user1172575: As I said in my answer, `Ints.asList` is a function of Guava, a very popular third-party library. – Mark Peters Nov 15 '12 at 18:47
2

Use Apache Commons Lang:

for (Object element:b) {
    if (ArrayUtils.contains(a,element) == false) return false;
}
return true;
hd1
  • 33,938
  • 5
  • 80
  • 91