Skip to content

Instantly share code, notes, and snippets.

@gfody
Created November 15, 2020 03:23
Show Gist options
  • Save gfody/8fe11d58d585099290bd2d59c04081ec to your computer and use it in GitHub Desktop.
Save gfody/8fe11d58d585099290bd2d59c04081ec to your computer and use it in GitHub Desktop.
Trie<T>
public class Trie<T> : Dictionary<T, Trie<T>>
{
public KeyValuePair<T, Trie<T>> Parent;
public bool ContainsParts(IEnumerable<T> parts, out int index)
{
index = 0;
Trie<T> t = this, n = null;
foreach (var p in parts)
{
if (!t.TryGetValue(p, out n)) return false;
t = n;
index++;
}
return true;
}
public Trie<T> AddParts(IEnumerable<T> parts)
{
Trie<T> t = this, n = null;
foreach (var p in parts)
{
if (!t.TryGetValue(p, out n))
{
n = new Trie<T>() { Parent = new KeyValuePair<T, Trie<T>>(p, t) };
t.Add(p, n);
}
t = n;
}
return t;
}
public IEnumerable<T> Parts()
{
var t = this;
while (t.Parent.Value != null)
{
yield return t.Parent.Key;
t = t.Parent.Value;
}
}
public IEnumerable<Trie<T>> Traverse()
{
foreach (var n in this)
{
yield return n.Value;
foreach (var c in n.Value.Traverse())
yield return c;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment