在C# Unity中统计单行随机生成字符的有效单词数量
Hey there! Let's figure out how to count the number of valid words you can make from those random consonants you're generating in Unity. First, let's break down the problem and walk through a practical solution.
First, let's recap your existing character generation code (cleaned up for clarity):
public void GenerateLettersAtStart() { for (int i = 0; i <= 6; i++) { wordRan.wordsStore.Clear(); int a = UnityEngine.Random.Range(0, consonants.Length); availablesetConsonants[i].GetComponent<TextMesh>().text = consonants[a].ToString(); // Looks like you're generating 7 consonants here (0 to 6 inclusive) } }
To count valid words from these characters, we'll need three key steps:
1. Set Up a Valid Word Dictionary
First, you need a reliable list of valid English words. Using a HashSet<string> is ideal here because checking if a word exists is lightning-fast (O(1) time complexity).
private HashSet<string> validWords; void Awake() { // Initialize with a small set of example words // For a real app, load a full word list (e.g., Oxford 3000) from a text file validWords = new HashSet<string> { "cat", "bat", "rat", "cab", "bar", "car", "tab", "tar" }; }
2. Collect Your Generated Characters
Modify your existing generation method to gather all the random characters into a list we can work with:
public void GenerateLettersAtStart() { List<char> availableChars = new List<char>(); for (int i = 0; i <= 6; i++) { wordRan.wordsStore.Clear(); int a = UnityEngine.Random.Range(0, consonants.Length); char selectedChar = consonants[a]; availablesetConsonants[i].GetComponent<TextMesh>().text = selectedChar.ToString(); availableChars.Add(selectedChar); } // Calculate and log the number of valid words int validWordCount = CountValidWords(availableChars); Debug.Log($"Total valid words: {validWordCount}"); }
3. Generate All Possible Combinations & Validate
We'll use a backtracking approach to generate every possible non-empty combination of characters, then check if each combination is a valid word. We'll also use a HashSet to avoid counting duplicate words (e.g., if you have two 'a's, "aa" only counts once).
private int CountValidWords(List<char> chars) { HashSet<string> foundValidWords = new HashSet<string>(); Backtrack(chars, new StringBuilder(), new bool[chars.Count], foundValidWords); return foundValidWords.Count; } private void Backtrack(List<char> chars, StringBuilder currentWord, bool[] usedChars, HashSet<string> foundWords) { string currentStr = currentWord.ToString(); // Only count words with 2+ characters (adjust this if you want shorter words) if (currentStr.Length >= 2 && validWords.Contains(currentStr)) { foundWords.Add(currentStr); } for (int i = 0; i < chars.Count; i++) { if (usedChars[i]) continue; // Mark this character as used usedChars[i] = true; currentWord.Append(chars[i]); // Recurse to build longer words Backtrack(chars, currentWord, usedChars, foundWords); // Backtrack: undo the last character currentWord.Length--; usedChars[i] = false; } }
Key Notes for Improvement
- Expand Your Word List: For accurate results, replace the example word set with a comprehensive English word list. You can save words in a
.txtfile (one word per line) and load it inAwake()usingFile.ReadAllLines(). - Performance Tweaks: If you're generating more than 7 characters, consider limiting the maximum word length (e.g., 5 characters) to reduce the number of combinations you need to check.
- Case Insensitivity: If your word list uses lowercase, convert all generated combinations to lowercase before checking (add
currentStr.ToLower()in the validation step).
内容的提问来源于stack exchange,提问作者Alexchandriyaa P

