Skip to content

Instantly share code, notes, and snippets.

@paratechnical
Created February 1, 2015 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paratechnical/ca12ee27e344abd79ad5 to your computer and use it in GitHub Desktop.
Save paratechnical/ca12ee27e344abd79ad5 to your computer and use it in GitHub Desktop.
Gist 2 from the article Autocomplete functionality using prefix trees
/// <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