I cant seem to figure out a way to use an ArrayList
(2 or more indexes) to search within another ArrayList
. For example, if list = [4,5,6,2,3,5,6]
and searchlist = [5,6]
, index should = 1.
Anybody have any ideas?
I cant seem to figure out a way to use an ArrayList
(2 or more indexes) to search within another ArrayList
. For example, if list = [4,5,6,2,3,5,6]
and searchlist = [5,6]
, index should = 1.
Anybody have any ideas?
Use pointers to your current indices
public int search(int[] list, int[] searchList) {
int listIndex = 0;
int searchListIndex = 0;
int foundIndex = -1;
while (listIndex != list.length) {
if (list[listIndex] == searchList[searchListIndex]) {
if (searchListIndex == 0) {
foundIndex = listIndex;
}
listIndex++;
searchListIndex++;
}
else {
listIndex++;
searchListIndex = 0;
foundIndex = -1;
}
}
return foundIndex;
}
Loop through the arrays in a nested loop. Then compare all values. If all values match up, then return the index:
list = [4,5,6,2,3,5,6]
searchlist = [5,6]
limit = list.size - serachList.size - 1
#make sure list's size is greater than or equal to searchList's size
for(i = 0 to limit)
for(j = 0 to searchList.size-1)
if(list[i + j] != searchList[j]) #found mismatch, so move on
break
if(j = searchList.size-1) #found complete match
return i
List has subList and equals. That's all you need.
import java.util.*;
import java.lang.*;
import java.io.*;
class TEST
{
public static void main (String[] args) throws java.lang.Exception {
List<Integer> list1 = Arrays.asList(1,2,3,4,5);
List<Integer> list2 = Arrays.asList(2,3);
for (int i=0; i<list1.size()-list2.size(); ++i) {
if (list1.subList(i, i+list2.size()).equals(list2)) {
System.out.println("found: "+i);
return;
}
}
System.out.println("not found");
}
}
The simplest idea is to run a loop, get the first value of the searchlist and find that value in the other list. If you find the number, increment the indices of both the lists and check the values again, continue until the end of searchlist or until the end of the other list.
I am not posting the code as I would rather you try yourself first, and come back if you are stuck anywhere.