Reputation: 3
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.
Upvotes: 0
Views: 288
Reputation: 348
arr[1].equals(arr[2])
instead arr[1] == arr[2]
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;
}
Upvotes: 1
Reputation: 49803
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).
Upvotes: 0