tags:

views:

61

answers:

3

Hi,

How do I check if two words have a common char?

ex. : "word" and "letter" have common "r"

"word" and "email" haven't any common chars

This code is wrong because if two words have 2 common chars I get 4 in the result

int numberOfCommonChars = (from c1 in word1.ToCharArray()
                           from c2 in word2.ToCharArray()
                           where c1 == c2
                           select c1).Count();
+3  A: 

Your code isn't working becasue using multiple from clauses creates a full outer join

You need to use Intersect:

int commonCount = word1.Intersect(word2).Count();

Although it doesn't show in IntelliSense, String implements IEnumerable<char>, so you don't need to call ToCharArray().

Note that this will only count each character once, so if both strings contain the same character twice, this will only count it once.

If you want to count multiple occurrences, use the following code:

var commonChars = word1.Intersect(word2);
var commonCount = commonChars.Sum(c => Math.Min(
    word1.Count(q => q == c), 
    word2.Count(q => q == c)
));
SLaks
it doesn't work properly.ex.string word1 = "wow";string word2 = "how";it gives me 2 in result
Yes; what do you expect it to give?
SLaks
I expect 1 because, they have one similar word. "How" has only one 'W'
You're forgetting that they both have an `o`.
SLaks
wOW and hOW - Two letters in common.
Brian
sorry and thank you !
A: 

Can you create an intersection of sets?

Tuomas Pelkonen
A: 
int numberOfCommonChars = (from c1 in word1.ToCharArray()
                            from c2 in word2.ToCharArray()
                            where c1 == c2
                            select c1).Distinct().Count();
Nicholas Murray
string word1 = "wonderful";string word2 = "wow";gives 2 in result
OK, is that good or bad? What is the expected result?
Nicholas Murray
1 is expected value
Computer says no!
Nicholas Murray