Created
February 1, 2015 22:01
-
-
Save paratechnical/ca12ee27e344abd79ad5 to your computer and use it in GitHub Desktop.
Gist 2 from the article Autocomplete functionality using prefix trees
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// get the autocomplete matches given the input | |
/// </summary> | |
/// <param name="query">the input</param> | |
/// <returns>the list of autocomplete matches</returns> | |
public List<string> GetMatches(string query) | |
{ | |
StringBuilder sbPrevious = new StringBuilder(); | |
char[] chars = query.ToCharArray(); | |
Node currentNode = _root; | |
Node child = null; | |
for (int counter = 0; counter < chars.Length; counter++) | |
{ | |
//form the sequence before the current char | |
if(counter < chars.Length - 1) | |
sbPrevious.Append(chars[counter]); | |
child = currentNode.GetChild(chars[counter]); | |
if (child == null) | |
break; | |
currentNode = child; | |
} | |
//clear the subsequent string storage | |
subsequentStrings.Clear(); | |
GenerateSubsequentStrings(currentNode, sbPrevious.ToString()); | |
return subsequentStrings; | |
} | |
/// <summary> | |
/// given a node and the current string generate the autocomplete matches recursively | |
/// </summary> | |
/// <param name="node">the current node</param> | |
/// <param name="subsequentString">the current sequence</param> | |
private void GenerateSubsequentStrings( Node node, | |
string subsequentString) | |
{ | |
//if there are no more nodes stop the recursion | |
if(node == null) | |
return; | |
//add the current char to the current sequence | |
subsequentString = subsequentString + node.Char; | |
//if a word ends here add the current sequence to the autocomplete list | |
if(node.AWordEndsHere) | |
subsequentStrings.Add(subsequentString); | |
//foreach child call the method recursively | |
foreach (var subnode in node.Subtree) | |
GenerateSubsequentStrings(subnode, subsequentString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment