-1
public boolean contains(int[] a,int[] b) {
int w=0;
for(int i=0;i<a.length && w<b.length;i++) {
    if(a[i]==b[w])
    w++;
    else w=0;
}
System.out.println(w);
if(w==b.length) return true;
else return false;

}


This code is failing for the scenario-contains({1, 2, 1, 2, 3}, {1, 2, 3})-for obvious reasons. However, i can't put the right code in that amends the right output. Please help me out.

bb5kb
  • 51
  • 1
  • 8
  • 4
    Hint: you need two for loops. – BobTheBuilder Aug 18 '13 at 13:13
  • I'm a little unsure about what you are trying to do; are you trying to make it so that you see if all elements in 1 array are present in another array? – Josh M Aug 18 '13 at 13:16
  • You need to describe what you are trying to do, what you have tried to accomplish it, and possible solutions you researched and attempted. Doing so will help make your question more concrete and you are more likely to get better help. – 137 Aug 18 '13 at 13:18
  • Your task is a classic alogrihtm of finding substring in a string http://stackoverflow.com/questions/1765579/fast-algorithm-for-searching-for-substrings-in-a-string – Tala Aug 18 '13 at 13:20
  • @JoshM yes, that's exactly: see if string b is substring of string a. – bb5kb Aug 18 '13 at 14:41
  • @DustinE.Thanks Dustin. I'll try to do as you told from now. – bb5kb Aug 18 '13 at 14:44

1 Answers1

0

Try this

        public static boolean contains(int[] a,int[] b) {
        String s1=  Arrays.toString(a).replaceAll("\\[|\\]","");
        String s2=  Arrays.toString(b).replaceAll("\\[|\\]","");

        if(s1.contains(s2)){
          return true;
        } else {
            return false;
        }
        }

Live Demo

Problem in your code

      for(int i=0;i<a.length && w<b.length;i++) {//a={1, 2, 1, 2, 3},b= {1, 2, 3}
        if(a[i]==b[w])// first two element are same in both arrays
            w++;// then w=2, but a[2] !=b[2]. 
        else w=0;// So w=0, but in next round it will check 
          //equality as a[3]==b[0] that's false.
       }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115