Let's say I have this pattern and a large array:
String [] pattern = new String[]{"i","am","a", "pattern"};
String [] large_array = new String[]{"not","i","am","a", "pattern","pattern","i","am","a", "pattern", "whatever", "x", "y", i","am","a", "pattern",................, i","am","a", "pattern" ....};
As you can see the pattern appears multiple times in the array. The first time at index 1, the second time at index 6, etc... I want to find out at which positions the pattern begins and return it in a collection (eg list).
In this case the position array is 1,6,13, etc...
Here is my current method:
private ArrayList<Integer> getStartPositionOfPattern(String[] headerArray, String[] pattern) {
ArrayList<Integer> allPositions = new ArrayList<>();
int idxP = 0, idxH = 0;
int startPos = 0;
while (idxH < headerArray.length) {
if (pattern.length == 1) {
if (pattern[0].equals(headerArray[idxH])) {
allPositions.add(idxH);
}
} else {
if (headerArray[idxH].equals(pattern[idxP])) {
idxP++;
if (idxP == pattern.length) { //you reached end of pattern
idxP = 0; //start Pattern from begining
allPositions.add(startPos); //you can save startPosition because pattern is finished
}
} else {
idxP = 0;
startPos = idxH + 1;
if (pattern[idxP].equals(headerArray[idxH])) { //if current arrray.idxH is not pattern.idxP but array.idxH is begining of pattern
startPos = idxH;
idxP++;
}
}
}
idxH++;
}
return allPositions;
}
Is there a way to make my function more readable and faster? I believe it works correctly, but because the function is complex, I worry I might have an undetected bug.
NOTE: headerArray
is the large array.