0

The problem is: Check to see if the array arr2 is contained within the arr1 in the same order. The arr2 could be contained anywhere with in arr1.

public boolean contains(String[] arr1, String[] arr2)
{
   int length  = 0;
   if(arr2.length > arr1.length)
      return false;
   for(int i = 0; i < arr2.length; i++)
   {
      if(arr2[i] == arr1[i])
          length++;
   }
   if(length == arr2.length)
      return true;
   else
      return false;
}

TESTER: contains({"1", "2", "3"}, {"1", "2"}) → true

RUN: TRUE

TESTER: contains({"1", "2", "3"}, {"2", "3"}) → true

RUN: FALSE

TESTER: contains({"1", "2", "3"}, {"2", "1"}) → false

RUN: TRUE

TESTER: contains({"MARY", "A", "LITTLE", "LAMB"}, {"A", "LITTLE", "LAMB"}) → true

RUN: FALSE

TESTER: contains({"MARY", "A", "LITTLE", "LAMB"}, {"MARY", "A", "LITTLE", "LAMB"}) → true

RUN: TRUE

.

I don't know where I'm going wrong. Thanks for help.

2
  • Hint: you need a nested for loop. Commented Dec 9, 2014 at 1:00
  • @mdnghtblue: Actually, you don't, though it can certainly be done that way. Commented Dec 9, 2014 at 1:02

2 Answers 2

1
  • use arr[1].equals(arr[2]) instead arr[1] == arr[2]
  • should judge in the loop not before loop

I modify the code like it:

public static boolean contains(String[] arr1, String[] arr2) {
    int length = 0;

    for (int i = 0; i < arr1.length; i++) {
        if (arr2[length].equals(arr1[i])) {
            length++;
        } else {
            length = 0;
        }
        if (length == arr2.length)
            return true;
    }
    return false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are only comparing both arrays from the beginning; you need to also consider the cases when you start comparing at a different location in arr1. For example, you would get TRUE in the second example if you started comparing at the second element of arr1 (same for the fourth example).

1 Comment

So how do I start comparing at the second element of arr1? I tried at the if statement to do if(arr2[i] == arr1[i] || arr2[i] == arr1[i+1]) but it doens't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.