6letterwordexercise/Program.cs

53 lines
1.9 KiB
C#

class Program
{
static void Main()
{
// Read all words from the input.txt file and store them in a hash set for quick lookup
var words = new List<string>(File.ReadAllLines("input.txt"));
var wordSet = new HashSet<string>(words);
// Find all combinations that form a 6-letter word
var combos = new HashSet<string>();
FindCombinations(words, new List<string>(), 0, wordSet, combos);
// Print out all found combinations
foreach (var combo in combos)
{
Console.WriteLine(combo);
}
}
static void FindCombinations(List<string> words, List<string> currentCombination, int currentLength, HashSet<string> wordSet, HashSet<string> combos)
{
// If the current combination forms a 6-letter word, add it to the result list
if (currentLength == 6)
{
string combinedWord = string.Join("", currentCombination);
if (wordSet.Contains(combinedWord))
{
string result = $"{string.Join("+", currentCombination)}={combinedWord}";
if (combos.Add(result)) // Adds to the set and checks for uniqueness
{
Console.WriteLine(result); // Echo out the found combination
}
}
return;
}
// Try adding each word to the current combination
foreach (var word in words)
{
// Skip if adding the word would exceed 6 characters
if (currentLength + word.Length > 6)
{
continue;
}
// Add the word to the current combination and recurse
currentCombination.Add(word);
FindCombinations(words, currentCombination, currentLength + word.Length, wordSet, combos);
currentCombination.RemoveAt(currentCombination.Count - 1); // Backtrack
}
}
}