Given two arrays as parameters (x and y) and find the starting index where the first occurrence of y in x. I am wondering what the simplest or the fastest implementation would be.
Example:
when x = {1,2,4,2,3,4,5,6}
y = {2,3}
result
starting index should be 3
Update: Since my code is wrong I removed it from the question.
Here is a simple (yet fairly efficient) implementation that finds all occurances of the array, not just the first one:
Example:
Output:
The method first loops through the
xarray to find all occurances of the first item in theyarray, and place the index of those in theindexarray. Then it goes on to reduce the matches by checking which of those also match the second item in theyarray. When all items in theyarray is checked, theindexarray contains only the full matches.Edit:
An alternative implementation would be to remove the
ToArraycall from the statement in the loop, making it just:This would totally change how the method works. Instead of looping through the items level by level, it would return an enumerator with nested expressions, deferring the search to the time when the enumerator was iterated. That means that you could get only the first match if you wanted:
This would not find all matches and then return the first, it would just search until the first was found and then return it.