public IList <string> FindWords(char[][] board, string[] words) { var trie = new TrieNode(); foreach (var word in words) { trie.Add(word.ToCharArray()); } var result = new HashSet <string>(); for (var i = 0; i < board.Length; i++) { for (var j = 0; j < board[i].Length; j++) { var stringBuilder = new StringBuilder(); var visited = new HashSet <Tuple <int, int> >(); if (!CheckTheTrie(trie, board, i, j, visited, stringBuilder, result)) { continue; } } } return(result.ToList()); }
public void TestTrieNodeFirstWord() { var trie = new TrieNode(); Assert.AreEqual("", trie.FirstWord()); trie.Add("table"); trie.Add("air"); trie.Add("link"); Assert.AreEqual("air", trie.FirstWord()); trie.Delete("air"); Assert.AreEqual("link", trie.FirstWord()); trie.Delete("link"); Assert.AreEqual("table", trie.FirstWord()); trie.Delete("table"); Assert.AreEqual("", trie.FirstWord()); }
void EnsureInitialized(Encoding encoding) { if (trieNode != null) { return; } TrieNode tmp = new TrieNode(); if (textTests != null) { if (encoding == null) { throw new ArgumentException("<trie-search> cannot be loaded. Text encoding is not specified."); } foreach (string text in textTests) { tmp.Add(encoding.GetBytes(text), 0); } } if (tmp.IsEmpty) { throw new ArgumentException("<trie-search> doesn't contain enough information"); } trieNode = tmp; }
public WordFilter(string[] words) { for (int index = 0; index < words.Length; index++) { string word = words[index]; for (int i = 0; i < word.Length; i++) { string form = word.Substring(i) + "\0" + word; TrieNode current = m_TrieNode; foreach (char c in form) { if (!current.TryGetValue(c, out TrieNode node)) { node = new TrieNode(); current.Add(c, node); } current = node; current.Index = index; } } } }
private void Compile() { foreach (var route in _routes) { var path = route.Path; if (path.StartsWith("/")) { path = path.Substring(1); } var parts = path.Split('/'); var methodNode = _root.Add(route.Method.ToUpperInvariant()); TrieNode current = methodNode; foreach (var part in parts) { current = current.Add(part); } if (current.Action != null) { throw new InvalidOperationException("Route already exists"); } current.Action = route.Action; } }
public void FindTestAtEndOfStream() { TrieNode n = new TrieNode(); n.Add(Encoding.UTF8.GetBytes("</pdml>"), 0); string testInput = "</packet> </pdml>"; DoTest(n, testInput, 0, 10, limit: testInput.Length); }
public AutocompleteSystem(string[] sentences, int[] times) { for (int i = 0; i < sentences.Length; ++i) { var node = root.Add(sentences[i]); node.Times = times[i]; } currentNode = root; }
public void FindTest() { TrieNode n = new TrieNode(); DoTest(n, "", 0, null); DoTest(n, "qwe", 0, null); DoTest(n, "qwe", 1, null); DoTest(n, "йцу", 0, null); DoTest(n, "йцу", 1, null); DoTest(n, "йцу", 2, null); n.Add(Encoding.UTF8.GetBytes("bar"), 0); n.Add(Encoding.UTF8.GetBytes("ba"), 0); DoTest(n, "bar", 0, 0); DoTest(n, "bba", 0, 1); DoTest(n, "bbaarr", 0, 1); DoTest(n, "йцbaук", 1, 4); DoTest(n, "йцbукar", 1, null); }
public void AddInstructions(TInstr [] instrs) { TrieNode node = root; foreach (TInstr instr in instrs) { node = node.Add(instr); ++node.Tally; ++count; } }
public void Add(T [] instrs) { TrieNode node = root; foreach (T instr in instrs) { node = node.Add(instr); ++node.Tally; ++Count; } }
public void TestTrieNode() { var root = new TrieNode(); Assert.AreEqual(1, root.NodeCount); Assert.AreEqual(0, root.WordCount); Assert.IsFalse(root.Contains("")); Assert.IsFalse(root.Contains("a")); root.Add(""); Assert.AreEqual(1, root.NodeCount); Assert.AreEqual(1, root.WordCount); Assert.IsTrue(root.Contains("")); Assert.IsFalse(root.Contains("a")); root.Add("ab"); Assert.AreEqual(3, root.NodeCount); Assert.AreEqual(2, root.WordCount); Assert.IsTrue(root.Contains("")); Assert.IsFalse(root.Contains("a")); Assert.IsFalse(root.Contains("ba")); Assert.IsTrue(root.Contains("ab")); root.Add("ac"); Assert.AreEqual(4, root.NodeCount); Assert.AreEqual(3, root.WordCount); Assert.IsTrue(root.Contains("")); Assert.IsFalse(root.Contains("a")); Assert.IsTrue(root.Contains("ab")); Assert.IsTrue(root.Contains("ac")); root.Delete("ab"); Assert.AreEqual(3, root.NodeCount); Assert.AreEqual(2, root.WordCount); Assert.IsTrue(root.Contains("")); Assert.IsFalse(root.Contains("a")); Assert.IsFalse(root.Contains("ab")); Assert.IsTrue(root.Contains("ac")); root.Delete("ac"); Assert.AreEqual(1, root.NodeCount); Assert.AreEqual(1, root.WordCount); root.Delete(""); Assert.AreEqual(1, root.NodeCount); Assert.AreEqual(0, root.WordCount); }
void addNode(TreeNode treeNode, TreeNode root, TrieNode tridNode, Dictionary <TreeNode, TrieNode> dict) { foreach (var item in treeNode.Transitions) { var node = dict[item]; tridNode.Add(item, node); addNode(item, root, node, dict); } if (treeNode != root) { string str = ""; List <char> rootChar = new List <char>(); var node = treeNode; while (node != root) { str += node.Char; var topNode = root.GetTransition(str, str.Length - 1); if (topNode != null) { foreach (var item in topNode.Transitions) { tridNode.Add(item, dict[item]); } } node = node.Parent; } } //if (treeNode != root) { // var topNode = root.GetTransition(treeNode.Char); // if (topNode != null) { // foreach (var item in topNode.Transitions) { // var node = dict[item]; // tridNode.Add(item, node); // } // } //} }
public int ambiguous(string[] dictionary) { TrieNode root = new TrieNode(); foreach (string word in dictionary) root.Add(word); int count = 0; for (int i = 0; i < dictionary.Length; i++) { for(int j = 0; j < dictionary.Length; j++) { if (i == j) continue; if (root.Add(dictionary[i] + dictionary[j])) count++; } } return count; }
public List <string> Input(char c) { if (c == '#') { currentNode.Times++; currentNode = root; current = ""; return(new List <string>()); } currentNode = currentNode.Add(c); current += c; return(Top3()); }
/// <summary> /// 添加关键字 /// </summary> /// <param name="key"></param> public void AddKey(string key) { if (string.IsNullOrEmpty(key)) { return; } TrieNode node = this; for (int i = 0; i < key.Length; i++) { char c = key[i].GetSimp(); node = node.Add(c); } node.m_end = true; }
/** Inserts a word into the trie. */ public void Insert(string word) { TrieNode node = root; for (int i = 0; i < word.Length; i++) { char ch = word[i]; if (!node.ContainsKey(ch)) { node.Add(ch, new TrieNode()); } node = node.Get(ch); } node.SetEnd(); }
static int Add(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); TrieNode obj = (TrieNode)ToLua.CheckObject(L, 1, typeof(TrieNode)); char arg0 = (char)LuaDLL.luaL_checknumber(L, 2); TrieNode o = obj.Add(arg0); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public void Insert(string s) { TrieNode current = m_TrieRoot; foreach (char c in s) { if (!current.TryGetValue(c, out TrieNode node)) { node = new TrieNode(); current.Add(c, node); } current = node; } current.IsWord = true; }
/// <summary> /// 设置关键字 /// </summary> /// <param name="keywords">关键字列表</param> public void SetKeywords(IDictionary <string, int> keywords) { var first = new TrieNode[char.MaxValue + 1]; var root = new TrieNode(); foreach (var key in keywords) { var p = key.Key; if (string.IsNullOrEmpty(p)) { continue; } var nd = first[p[0]]; if (nd == null) { nd = root.Add(p[0]); first[p[0]] = nd; } for (int i = 1; i < p.Length; i++) { nd = nd.Add(p[i]); } nd.SetResults(p, key.Value); } this._first = first; Dictionary <TrieNode, TrieNode> links = new Dictionary <TrieNode, TrieNode>(); foreach (var item in root.m_values) { TryLinks(item.Value, null, links); } foreach (var item in links) { item.Key.Merge(item.Value); } _root = root; }
public int[][] IndexPairs(string text, string[] words) { foreach (string word in words) { TrieNode current = m_TrieRoot; foreach (char c in word) { if (!current.TryGetValue(c, out TrieNode node)) { node = new TrieNode(); current.Add(c, node); } current = node; } current.WordLength = word.Length; } List <int[]> pairs = new List <int[]>(); for (int start = 0; start < text.Length; start++) { TrieNode node = m_TrieRoot; for (int i = start; i < text.Length; i++) { if (node.TryGetValue(text[i], out node)) { if (node.WordLength > 0) { pairs.Add(new[] { start, start + node.WordLength - 1 }); } } else { break; } } } return(pairs.ToArray()); }
public void Add(Suffix key, T value) { if (key.IsEmpty()) { values.Add(value); } else { int branchIndex = GetBranchIndexFromChar(key.GetFirstChar()); TrieNode node = branches[branchIndex]; if (node == null) { node = branches[branchIndex] = new TrieNode(); } node.Add(key.GetNextSuffix(), value); } }
private void Initialize(IList <string> input) { // Identify the set of characters contained in the input supportedCharacters = new SupportedCharacters(input.Cast <IEnumerable <char> >().SelectMany(cs => cs)); // Create a node-based trie var rootNode = new TrieNode(supportedCharacters); foreach (var str in input) { rootNode.Add(str); } // Shrink the trie down to an acyclic word graph by sharing common suffixes. var canonicalNodes = CreateCanonicalNodeDictionary(rootNode); // Make sure that our array representation can contain the number of nodes if (canonicalNodes.Count >= byte.MaxValue) { throw new InvalidOperationException("Too many nodes - System.Byte may be too small."); } // Initialize the array representation of the node structure trie = new byte[canonicalNodes.Count + 1, supportedCharacters.Count + 1]; // Establish a mapping between canonical nodes an array indices. var numToNode = new TrieNode[canonicalNodes.Keys.Count + 1]; canonicalNodes.Keys.CopyTo(numToNode, 1); // Leave the first row (number 0) null. var nodeToNum = new Dictionary <TrieNode, byte>(new NodeToNumComparer()); for (var i = 1; i < numToNode.Length; ++i) { nodeToNum.Add(numToNode[i], (byte)i); } // Populate the array, and let the garbage collecter handle the object refs. Fill(rootNode, nodeToNum); root = nodeToNum[rootNode]; }
/// <summary> /// 设置关键字 /// </summary> /// <param name="_keywords">关键字列表</param> public virtual void SetKeywords(ICollection <string> _keywords) { var first = new TrieNode[char.MaxValue + 1]; var root = new TrieNode(); foreach (var p in _keywords) { if (string.IsNullOrEmpty(p)) { continue; } var nd = _first[p[0]]; if (nd == null) { nd = root.Add(p[0]); first[p[0]] = nd; } for (int i = 1; i < p.Length; i++) { nd = nd.Add(p[i]); } nd.SetResults(p); } this._first = first;// root.ToArray(); Dictionary <TrieNode, TrieNode> links = new Dictionary <TrieNode, TrieNode>(); foreach (var item in root.m_values) { TryLinks(item.Value, null, links); } foreach (var item in links) { item.Key.Merge(item.Value, links); } //_root = root; }
private void Add(TValue Value, TToken[] newKey, int Index) { if (this.Children == null || !this.ContainsChild(newKey[Index])) { TrieNode newNode = new TrieNode(this.container)//(this.Container) { Parent = this, Key = newKey[Index], }; if (this.Children == null) { this.Children = CreateChildContainer(); } Children.Add(newNode.Key, newNode); if (Index < newKey.Length - 1) { newNode.Add(Value, newKey, Index + 1); } else { newNode.Value = Value; newNode.Terminal = true; } } else { if (Index < newKey.Length - 1) { TrieNode MatchingChild = GetChild(newKey[Index]); MatchingChild.Add(Value, newKey, Index + 1); } else { TrieNode matchingChild = GetChild(newKey[Index]); matchingChild.Value = Value; matchingChild.Terminal = true; } } }
public void Add(string item) { bool first = true; TrieNode current = new TrieNode(' '); foreach (char c in item.ToLower()) { if (first) { current = roots[c]; first = false; continue; } if (!current.Contains(c)) { current.Add(new TrieNode(c)); } current = current.edges[c]; } }
public static void TrieTest() { var trie = new TrieNode(); var words = new List <string> { "word", "hello", "weird", "wordo", "hell", "oath", "pea", "eat", "rain" }; foreach (var word in words) { trie.Add(word.ToCharArray()); } var extractedWords = TrieNode.GetAllWords(trie); foreach (var word in words) { if (!extractedWords.Contains(word)) { Console.WriteLine($"Word {word} wasn't extracted from trie"); } } }
/** Inserts a word into the trie. */ public void Insert(string word) { treeRoot.Add(word); }
/// <summary> /// Adds the specified lexical entry. /// </summary> /// <param name="entry">The lexical entry.</param> public void Add(PhoneticShape shape, T value) { m_root.Add(shape.GetFirst(m_dir), value, m_dir); m_numValues++; }
public static void ProcessInput() { string t = Console.ReadLine(); string p = Console.ReadLine(); string[] phrase = p.Split(' '); TrieNode root = new TrieNode(); foreach (string word in phrase) { root.Add(word, 0); } var matches = root.FindWords(t); var dictionary = new Dictionary <string, List <int> >(); foreach (var resultInfo in matches) { if (dictionary.ContainsKey(resultInfo.Word)) { dictionary[resultInfo.Word].Add(resultInfo.Start); } else { var l = new List <int> { resultInfo.Start }; dictionary.Add(resultInfo.Word, l); } } var phraseMatch = new int[phrase.Length]; for (int i = 0; i < phraseMatch.Length; i++) { phraseMatch[i] = -1; } int matchesCount = 0; int lastIndex = -1; for (int i = 0; i < phrase.Length; i++) { string word = phrase[i]; bool containingWord = dictionary.ContainsKey(word); if (!containingWord) { break; } if (dictionary.ContainsKey(word)) { var l = dictionary[word]; bool found = false; for (int j = 0; j < l.Count; j++) { if (l[j] > lastIndex) { lastIndex = l[j]; phraseMatch[i] = lastIndex; matchesCount++; found = true; break; } } if (found == false) { break; } } } if (matchesCount == phrase.Length) { Console.WriteLine("YES"); PrintMatches(phrase, phraseMatch); Console.WriteLine(LevenshteinDistance(t, p)); } else { Console.WriteLine("NO"); if (matchesCount == 0) { Console.WriteLine("0"); } else { PrintMatches(phrase, phraseMatch); } Console.WriteLine("0"); } }
public void Add(string s) { root.Add(s, 0); }