I have created a scrabble game with a computer opponent. If a blank tile is found in the computer’s rack during the word generation if needs to be swapped out for every letter in the alphabet. I have my current solution to solve this problem below, but was wondering if there is a better more efficient way to accomplish this task.
if (str.Contains("*"))
{
char c = 'A';
String made = "";
while(c < 'Z')
{
made = str.ReplaceFirst("*", c.ToString());
if (!made.Contains("*"))
{
wordsMade.Add(made);
if (theGame.theTrie.Search(made) == Trie.SearchResults.Found)
{
validWords.Add(made);
}
}
else
{
char ch = 'A';
String made2 = "";
while (ch < 'Z')
{
made2 = made.ReplaceFirst("*", c.ToString());
wordsMade.Add(made2);
if (theGame.theTrie.Search(made2) == Trie.SearchResults.Found)
{
validWords.Add(made2);
}
ch++;
}
}
c++;
}
There’s a lot of duplicated code here that can be refactored.
This routine is duplicated, and can be put into a separate method:
To something like this
This loop construct is also duplicated:
Combining the previous refactor with this one, with a slick lambda, would yield something like this:
Or even just: