RyanEdwardHall / anagrambler

Finds all anagrams and sub-anagrams in a string
MIT License
4 stars 1 forks source link

Add search filter parameter #13

Closed mcgid closed 8 years ago

mcgid commented 8 years ago

This will let us constrain the returned results to just the ones containing a filter string.

The filtering happens in two phases: first, as we traverse the trie and encounter the first character in the filter, we remove it in the recursive search call for that character. We repeat this, until the filter is empty. At that point, any node we encounter has satisfied the first phase of the filter (since its full path contains all of the characters in the filter, though not necessarily in the correct order).

If, while traversing, we encounter a letter that is alphabetically later than the next character in the filter, then we know this node and all its descendents will not satisfy the filter (because the next character in the filter is missing from them). So at that point we abandon that branch of the trie by returning from the recursion.

After we've finished traversing the trie, we then iterate through all of the collected results, and keep only those which contain exactly the filter string -- i.e. we discard any anagrams where the characters in the filter string are not in the right order, next to each other, as a proper substring.

At that point, the list of result anagrams is returned.

I also reworked the main function to not crash if the program isn't supplied any arguments, and to use the filter if it is supplied.