I've got a flat array of < 1000 items and I need to find the indices of a smaller tuple/array within the array. The tuple to find can be a varying length (generally between 2 and 5 items, order is important).
This is my initial naive implementation. My main concerns are:
- This seems like a CS 101 problem, so I'm pretty sure I'm overdoing it.
- Readability. I can break this down into smaller methods, but it's essentially a utility function in a much larger class. I guess I could extract it into its own class, but that feels like overkill as well. As-is, it's just too long for me to grok the whole thing in one pass.
public int[] findIndices(final Object[] toSearch, final Object[] toFind)
{
Object first = toFind[0];
List<Integer> possibleStartIndices = new ArrayList<Integer>();
int keyListSize = toFind.length;
for (int i = 0; i <= toSearch.length - keyListSize; i++)
{
if (first.equals(toSearch[i]))
{
possibleStartIndices.add(i);
}
}
int[] indices = new int[0];
for (int startIndex : possibleStartIndices)
{
int endIndex = startIndex + keyListSize;
Object[] possibleMatch = Arrays.copyOfRange(toSearch, startIndex, endIndex);
if (Arrays.equals(toFind, possibleMatch)) {
indices = toIndexArray(startIndex, endIndex);
break;
}
}
return indices;
}
private int[] toIndexArray(final int startIndex, final int endIndex)
{
int[] indices = new int[endIndex - startIndex];
for (int i = 0; i < indices.length; i++)
indices[i] = startIndex + i;
return indices;
}