I am trying to find a way to check if the elements of one list appears in another list in the same order in Java. For example:
char[] list = {'A','B','B','C','B','D'};
char[] sublist = {'B','C','B'};
char[] sublist2 = {'A','B','D'};
It should return true for sublist, but return false for sublist2 (because they do not appear in the same order). I am mainly trying to use for loops with some whiles and some ifs (trying not to use some built in functions maybe other than length).
I tried this but I do not think it is correct (getting wrong answers):
public static boolean subList(char[] list, char[] sublist) {
for(int i=0; i<sublist.length; i ) {
for(int j=0; j<list.length; j ) {
if (sublist[i] == list[j]) {
break;
}
}
return true;
}
return false;
}
Is it possible to achieve this?
CodePudding user response:
This is not the most correct code but it works!
public static boolean subList(char[] list, char[] sublist) {
int subposition=0;
boolean subarray=false;
for(int i=0;i<list.length;i ) {
if(subposition<sublist.length) {
if(list[i]==sublist[subposition]) {
subposition ;
}
else if(subposition>0){
subposition=0;
i--;
}
if(subposition==sublist.length) {
subarray=true;
}
}
}
if(subarray)return true;
else return false;
}
CodePudding user response:
The following code should work:
- outer loop by list, nested loop by sublist
- create a boolean flag
found
- in the nested loop compare elements of
list
starting from current position in the list, as soon as discrepancy is detected,found
is reset to false - if upon completing the nested loop,
found
istrue
then the sublist is detected.
public static boolean subList(char[] list, char[] sublist) {
for(int i = 0; i < list.length; i ) {
boolean found = true;
for(int j = 0, k = i; j < sublist.length && found && k < list.length; j , k ) {
if (sublist[j] != list[k]) {
found = false;
}
}
if (found) return true;
}
return false;
}
Tests:
char[] list = {'A','B','B','C','B','D'};
char[] sublist = {'B','C','B'};
char[] sublist2 = {'A','B','D'};
System.out.println(subList(list, sublist)); // true
System.out.println(subList(list, sublist2)); // false
CodePudding user response:
Try this.
public static boolean subList(char[] list, char[] sublist) {
L: for (int i = 0, max = list.length - sublist.length; i <= max; i ) {
for (int j = 0, k = i; j < sublist.length; j , k )
if (sublist[j] != list[k])
continue L;
return true;
}
return false;
}
public static void main(String[] args) throws InterruptedException {
char[] list = {'A', 'B', 'B', 'C', 'B', 'D'};
char[] sublist = {'B', 'C', 'B'};
char[] sublist2 = {'A', 'B', 'D'};
System.out.println(subList(list, sublist));
System.out.println(subList(list, sublist2));
}
output:
true
false