1

I tried to find subarray in an array. It works for only one subarray but I want that if there are more than one subarray, it returns last one's index. For example, for [3,4,1,2,0,1,2,5,6] and [1,2] should return 5.

public int FindArray(int[] array, int[] subArray)
    {
        //throw new NotImplementedException();
    int y=0;
    int index=0;
    bool find= false;
    for(int x=0;x< array.Length && y< subArray.Length;)
    {
        if(array[x]!= subArray[y])
        {
            if(find==true)
            {               
                y=0;
                index=x;
            }
            else
            {
                x++;                
                y=0;
                index=x;    
            }
        }
        else
        {
            find=true;
            x++;        
            y++;
        }
    }

    if(y==subArray.Length)
            return index;
    else
            return -1;
    }
}
phoenixx
  • 13
  • 2
  • 6
  • 1
    Start searching from the end of the array, e.g. `for (int x = array.Length - 1; x >= 0 ...)` – p.s.w.g Mar 13 '19 at 20:01
  • I tried(and wrote x-- instead of x++) but then it goes infinite loop at if(find==true) because it never decrease x. But it works without x++ before. – phoenixx Mar 13 '19 at 20:30

1 Answers1

0
public int FindLast(int[] haystack, int[] needle)
{
    // iterate backwards, stop if the rest of the array is shorter than needle (i >= needle.Length)
    for (var i = haystack.Length - 1; i >= needle.Length - 1; i--)
    {
        var found = true;
        // also iterate backwards through needle, stop if elements do not match (!found)
        for (var j = needle.Length - 1; j >= 0 && found; j--)
        {
            // compare needle's element with corresponding element of haystack
            found = haystack[i - (needle.Length - 1 - j)] == needle[j];
        }
        if (found)
            // result was found, i is now the index of the last found element, so subtract needle's length - 1
            return i - (needle.Length - 1);
    }
    // not found, return -1
    return -1;
}

As a runnable fiddle: https://dotnetfiddle.net/TfjPuY

Christoph Herold
  • 1,799
  • 13
  • 18