0

Return array with elements present in both arrays, currently receiving a

not all node paths return a value

error. This is my code:

string[] findKnownsMergePattern(string[] vocab, string[] wds)
{
    // TODO
    List<string> results = new List<string>();
    int xi = 0, yi = 0;
    while (xi < wds.Length && yi < vocab.Length)
    {
        int cmp = wds[xi].CompareTo(vocab[yi]);
        if (cmp == 0)
        {
            results.Add(vocab[yi++]);
        }
        else
        {
            xi++;
        }
        return results.ToArray();
    }
}

In theory I think this should work just fine, I just can't seem to figure out why I'm getting the error.

Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
Sihle
  • 33
  • 3
  • You get the error because theoretically the condition in while could be false in the first round and then you won't get to a return statement. Add a return statement below the while loop - rather throw an exception at the end - because i assume that this would be undesired behavior – Dennis Kuypers Sep 18 '18 at 18:52

1 Answers1

0

You are getting this error because you have a string[] return type to your function while you are just returning from within your while loop which could, theoretically, not execute. You need to do something like below to fix the error you are getting:

string[] findKnownsMergePattern(string[] vocab, string[] wds)
    {
        // TODO
        List<string> results = new List<string>();
        int xi = 0, yi = 0;
        while (xi < wds.Length && yi < vocab.Length)
        {
            int cmp = wds[xi].CompareTo(vocab[yi]);
            if (cmp == 0)
            {
                results.Add(vocab[yi++]);
            }
            else
            {
                xi++;
            }
         }//end the while loop
         return results.ToArray(); //now return the array
    }

Caution: In the calling code for this function, account for the resultant array being empty arrayVariable.Length == 0 to better handle your code

adityap
  • 329
  • 1
  • 10