Dom
Dom

Reputation: 25

Can't find unique words

Could anyone tell me what's wrong in my code? Basically I need to add only the unique words from words1 to uniques list, after I compare both words1 and words2. In the if statement, if i remove ! then it finds the matching words (opposite of what i need)

    List<string> Unique(string lines1 ,string lines2,  char[] separators)
    {
        string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
        List<string> uniques = new List<string>();

        for (int i = 0; i < words1.Length; i++)
        {
            bool match;
            for (int x = 0; x < words2.Length; x++)
            {
                if (!words1[i].Equals(words2[x]))
                {
                    match = true;
                    uniques.Add(words1[i]);
                    break;
                }
                else
                {
                    match = false;
                }
            }
        }

        return uniques;
    }

Upvotes: 1

Views: 85

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112342

Using two nested loops has a bad performance of O(n2). Use a set Union

return words1
    .Union(words2)
    .ToList();

Upvotes: 0

Anu Viswan
Anu Viswan

Reputation: 18155

You could do minor changes to your loop

    for (int i = 0; i < words1.Length; i++)
    {
        bool match=false;
        for (int x = 0; x < words2.Length; x++)
        {
            if (words1[i].Equals(words2[x]))
            {
                match = true;
                break;
            }

        }
        if(!match && uniques.Contains(words1[i]))
        { 
            uniques.Add(words1[i]);
        }
        { 
        uniques.Add(words1[i]);
        }
    }

To make your code even shorter, you could use LINQ

List<string> Unique(string lines1 ,string lines2,  char[] separators)
{    
string[] words1 = lines1.Split(separators, StringSplitOptions.RemoveEmptyEntries);
string[] words2 = lines2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return words1.Except(words2).ToList();
}

Upvotes: 5

Related Questions