Edwin Coronado Edwin Coronado - 2 months ago 8
C# Question

Determine if string is made up of characters from a different string (Scrabble-like program)

I am writing a program in C# that goes through a list of words and determines if they can be made up by a string that a user input. Just like the Scrabble game.

For example, when the user inputs the string "vacation", my program is supposed to go through a list of words that I already have and should return true when it gets to words like "cat". So it doesn't necessarily have to user ALL the letters.

Another example could be the word "overflow", it should return true with words like "over", "flow", "low", "lover". If the input word has repeating characters by N times, the word that matches can also have that letter up to N times but no more.

I currently have something like this:

var desiredChars = "ent";
var word = "element";
bool contains = desiredChars.All(word.Contains);


However, this checks if it contains all of the letters. I want to check if it contains ONLY those letters or less but ONLY those that can be made up with letters that the user passed.

Answer

If it wasn't for the issue of possible multiple letters (for "overflow", the word "fool" is a match, but "wow" isn't, because there aren't two w characters in the letter set), this Linq code would work

string letters = "overflow";
string word = "lover";

bool match = !word.Except(letters).Any(); // unfortunately, not sufficient

So, to handle the multiple letter issue, something like this is needed:

var letterChars = letters.ToList();
bool match = word.All(i => letterChars.Remove(i));

Here, we return true only if all the letters in the word can successfully be removed from the set of letters. Note that you only need to check those words in your dictionary that start with one of the letters in your letter set.