/// <summary> /// A test harness for the LetterNode class. /// </summary> /// <param name="args"> The command line arguments passed in. </param> public static void TestLetterNode(string[] args) { if (args.Length > 0) { LetterNode node = new LetterNode(args[0]); for (int i = 1; i < args.Length; i++) { node.AddWord(args[i]); } Console.Write("Total words = " + node.LeafNodeCount()); Console.Write("Maximum word length = " + node.MaxLength()); } else { Console.Write("Usage: GhostGame " + typeof(LetterNode).FullName + " <word-list>"); } }
/// <summary> /// Add a word to the dictionary if it meets two criteria: /// <ul> /// <li> The word must be at least MIN_WORD_LENGTH letters long. /// <li> The word must not start with another valid word. /// </ul> /// The second criteria is enforced by the LetterNode class. /// </summary> /// <param name="word"> The word to add to the dictionary. </param> private void AddWord(string word) { if (word.Length >= MIN_WORD_LENGTH) { char key = Convert.ToChar(word[0]); LetterNode node = null; if (_words.ContainsKey(key)) { node = _words[key]; } if (node == null) { _words[key] = new LetterNode(word); } else { node.AddWord(word); } } }
/// <summary> /// Add a word to the tree rooted at this node. This method implements /// the Ghost rule that no word may begin with another word. That /// requires two rules: /// /// - If this node has no child nodes, the passed word begins with /// this word and must not be added. /// - If the passed word has a length of zero, this is the end of the /// word and all child nodes must be deleted. /// </summary> /// <param name="word"> The word, or substring, to add to this node. </param> public void AddWord(string word) { if (word[0] == _letter) { if (_nodes.Count > 0) { if (word.Length == 1) { _nodes.Clear(); } else { char key = Convert.ToChar(word[1]); LetterNode nextNode = null; if (_nodes.ContainsKey(key)) { nextNode = _nodes[key]; } if (nextNode == null) { _nodes[key] = new LetterNode(word.Substring(1)); } else { nextNode.AddWord(word.Substring(1)); } } } } else { throw new ArgumentException("Invalid first letter."); } }