/// <summary> /// 构建 Trie 树 /// </summary> /// <param name="value">参与构建 Trie 树的字符串</param> public void Build(string value) { if (string.IsNullOrEmpty(value)) throw new ArgumentNullException("value"); TrieNode nNode = null; TrieNode cNode = m_root; var cChildNodes = cNode.ChildNodes; foreach (var curItem in value) { if (cChildNodes == null) cChildNodes = new Dictionary<char, TrieNode>(); if (cChildNodes.Count == 0 || !cChildNodes.TryGetValue(curItem, out nNode)) { nNode = new TrieNode(); cChildNodes.Add(curItem, nNode); } cNode.ChildNodes = cChildNodes; cNode = nNode; cChildNodes = cNode.ChildNodes; } cNode.IsSegment = true; }
// inserts the word intro trie // O(word.Length) public void Insert(string word) { // calculate wordLen so its not done everytime word.length is called int wordLen = word.Length; if (wordLen < Constants.MIN_WORD_LENGTH) return; TrieNode current = this; for (int i = 0; i < wordLen; ++i) { // process ith letter of word char c = word [i]; // index of letter int index = c - 'A'; UnityEngine.Debug.Assert (index >= 0 && index < 26, "Trying to add invalid word: " + word + " at letter: " + c); TrieNode child = null; if (!current.childExists (index, ref child)) { child = new TrieNode (c); current.insertChild (index, child); } // child letter exists // time to process next letter (which is represented by child) current = child; } // when control reaches here, end of word has been reached current.eow = true; }
private static void IncrementOccuranceCountTrie( TrieNode start, MatchCollection allWords) { foreach (var word in allWords) { start.AddOccuranceIfExists(start, word.ToString()); } }
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); TrieNode start = new TrieNode(); var allWords = SetInputText(); List<string> wordsToSearch = new List<string>(); for (int i = 0; i < 50; i++) { wordsToSearch.Add(allWords[i].ToString()); } sw.Start(); AddWordsInTrie(start, wordsToSearch); IncrementOccuranceCountTrie(start, allWords); sw.Stop(); Console.WriteLine("Searched words count trie: "); foreach (var word in wordsToSearch) { Console.WriteLine("{0}: {1}", word, start.CountWords(start, word)); } Console.WriteLine(); Console.WriteLine("Time elapsed: {0}", sw.Elapsed); }
public void CreateTrie(string[] words, TrieNode start = null) { foreach (string word in words) { this.Add(word, start); } }
private static void AddWordsForSearchInTrie(TrieNode start, List<string> words) { foreach (var item in words) { start.AddWord(start, item.ToString()); } }
static void Main(string[] args) { TrieNode root = new TrieNode(null, '?'); Console.WriteLine("FileName:"); string fileName = Console.ReadLine(); Book book = new Book(fileName, ref root); book.cleanText(); List<TrieNode> nodes = new List<TrieNode>(); root.GetTopCounts(ref nodes); foreach (TrieNode node in nodes) { if (node._word_count != 0) { if (PrimeCalculator.isPrime(node._word_count)) { Console.WriteLine("{0} - {1} times Prime", node.ToString(), node._word_count); } else { Console.WriteLine("{0} - {1} times", node.ToString(), node._word_count); } } } Console.ReadLine(); }
public Trie(Alphabet alphabet) { _charToIndex = alphabet._charToIndex; _indexToChar = alphabet._indexToChar; R = alphabet.R; root = new TrieNode(); }
static void Main() { Stopwatch sw = new Stopwatch(); TrieNode start = new TrieNode(); Dictionary<string, int> wordsInDictionary = new Dictionary<string, int>(); var allWords = SetInputText(); List<string> wordsToSearch = new List<string>(); // change number to increase searched words count for (int i = 0; i < 50; i++) { wordsToSearch.Add("text"); } AddWordsForSearchInDictionary(sw, wordsToSearch, wordsInDictionary); AddWordsForSearchInTrie(sw, start, wordsToSearch); IncrementOccuranceCountTrie(sw, start, allWords); IncrementOccuranceCountDictionary(sw, wordsInDictionary, allWords); Console.WriteLine("Searched words count trie: "); foreach (var word in wordsToSearch) { Console.WriteLine("{0}: {1}", word, start.CountWords(start, word)); } Console.WriteLine("\nSearched words count dictionary: "); foreach (var item in wordsInDictionary) { Console.WriteLine("{0}: {1}", item.Key, item.Value); } }
//adds a value into a unbalanced tree //return true if its a new node private bool AddX(int[] value) { int valueIndex = 0; //root is null, use first element if (root == null && valueIndex < value.Length) { root = new TrieNode(value[valueIndex]); } TrieNode current = root; while (valueIndex < value.Length) { if (current.Value > value[valueIndex]) { if (current.Left == null) { //add new left node current.Left = new TrieNode(value[valueIndex]); valueIndex++; } current = current.Left; } else if (current.Value < value[valueIndex]) { if (current.Right == null) { //add new right node current.Right = new TrieNode(value[valueIndex]); valueIndex++; } current = current.Right; } else { //same value, consume lement valueIndex++; //if this was the last element and it was center, then the value already existed if (valueIndex >= value.Length) { return true; } //move center or create if (current.Center == null) { current.Center = new TrieNode(value[valueIndex]); } current = current.Center; } } return false; }
public virtual TrieNode GetNodeForSegment(TrieNode parent, string segment) { if (parent == null) { return new RootNode(this); } var chars = segment.ToCharArray(); var start = chars[0]; var end = chars[chars.Length - 1]; if (start == '(' && end == ')') { return new RegExNode(parent, segment, this); } if (start == '{' && end == '}' && chars.Count(c => c == '{' || c == '}') == 2) { return this.GetCaptureNode(parent, segment); } if (segment.StartsWith("^(") && (segment.EndsWith(")") || segment.EndsWith(")$"))) { return new GreedyRegExCaptureNode(parent, segment, this); } return new LiteralNode(parent, segment, this); }
public void AddWordTest() { TrieNode node = new TrieNode(); node.AddWord("test", 100); Assert.AreEqual(1, node.Words.Count(), "Incorrect words count"); }
public void ConstructorTest() { TrieNode node = new TrieNode(); Assert.IsNotNull(node, "node must have a value"); Assert.IsNotNull(node.Leaves, "node.Childs must have a value"); Assert.IsNotNull(node.Words, "node.Words must have a value "); }
// collect all keys under a node private void CollectAllKeys(TrieNode node, string s, IList<string> strs) { if(node == None) return; if(node.isWord) strs.Add(s); for(var i = 0; i < R; i++){ CollectAllKeys(node.next(i), s+IndexToChar(i), ret); } }
public void Load(string[] words) { rootTree = new TrieNode(); foreach (var word in words) { AddWord(word); AddReversedWord(word); } }
private static void AddWordsForSearchInTrie(Stopwatch sw, TrieNode start, List<string> words) { sw.Start(); foreach (var item in words) { start.AddWord(start, item.ToString()); } sw.Stop(); Console.WriteLine("Time to populate the trie: {0}\n", sw.Elapsed); }
public void AddWordTest_WordsLimit() { TrieNode node = new TrieNode(); for (int i = 1; i < 12; i++) { node.AddWord("test" + i, i); } Assert.AreEqual(10, node.Words.Count(), "Incorrect words count"); }
private static List<TrieNode> AddRootToTrieNodes(TrieNode root) { var topNodes = new List<TrieNode>(); for (var i = 0; i < Words.WordsToFind.Count; i++) { topNodes.Add(root); } return topNodes; }
private static TrieNode FillTrie() { var result = new TrieNode(root, 'c'); var words = hugeText.Split(new char[] { ' ', '.', ',', '!', '?' }).ToList(); foreach (var word in words) { result.AddWord(word); } return result; }
private static TrieNode AddWordsToTrieNode(IEnumerable<string> words) { var root = new TrieNode(null, '?'); foreach (var word in words) { root.AddWord(word); } return root; }
private static void IncrementOccuranceCountTrie(Stopwatch sw, TrieNode start, MatchCollection allWords) { sw.Restart(); foreach (var word in allWords) { start.AddOccuranceIfExists(start, word.ToString()); } sw.Stop(); Console.WriteLine("Adding searched words count trie for: {0}", sw.Elapsed); }
private bool StartsWith(string word, TrieNode root, int index) { if(index == word.Length -1){ return true; } else if(!root.children.ContainsKey(word[index+1])){ return false; } else{ return StartsWith(word, root.children[word[index+1]], index+1); } }
private bool Search(string word, TrieNode root, int index) { if(index == word.Length -1 && root.children.ContainsKey((char)0)){ return true; } else if(index == word.Length -1 || !root.children.ContainsKey(word[index+1])){ return false; } else{ return Search(word, root.children[word[index+1]], index+1); } }
public void TestaddSameChar() { TrieNode root_node = new TrieNode(' ', null); root_node.add('a'); TrieNode node = root_node.add('a'); string actual = node.getWord(); string expected = "a"; Assert.AreEqual(expected, actual, "expected :" + expected + " did not match actual :" + actual); }
public Console(ILineColorProvider colorProvider, ILinePrefixProvider logPrefixProvider, ILogger logger) : base(colorProvider, logger) { if (!DesignMode) { this.logPrefixProvider = logPrefixProvider; commandQueue = new Queue<string>(CommandQueueSize); commandTrie = new TrieNode<char>(); commands = new SortedList<string, ConsoleCommand>(); AddCommand(new StringFunc(this, "help", Console_Help, 255, "Print help")); listener = Utils.CreateThread(ConsoleListenerProc, "ConsoleListener"); } Initialized = true; }
// creates trie and returns root node public static TrieNode createTrie(string[] words) { TrieNode root_node = new TrieNode(' ', null); foreach (string word in words) { TrieNode start_node = root_node; foreach (char c in word.ToCharArray()) { start_node = start_node.add(c); } ++start_node.word_count; } return root_node; }
public void TestaddnewChar() { TrieNode node = new TrieNode(' ', null); node = node.add('a'); node = node.add('b'); string actual = node.getWord(); string expected = "ab"; Assert.AreEqual(expected, actual, "expected :" + expected + " did not match actual :" + actual); Assert.AreEqual(0, node.word_count, "expected :" + expected + " did not match actual :" + actual); }
public void TestgetWord() { TrieNode node = new TrieNode(' ', null); foreach (char c in "cat".ToArray()) { node = node.add(c); } string actual = node.getWord(); string expected = "cat"; Assert.AreEqual(expected, actual, "expected :" + expected + " did not match actual :" + actual); }
/// <summary>The get node.</summary> /// <param name="word">The word.</param> /// <param name="start">The start.</param> /// <returns>The <see cref="TrieNode"/>.</returns> private TrieNode GetNode(string word, TrieNode start = null) { TrieNode current = start ?? this.Root; foreach (char c in word) { if (current?.Children?.ContainsKey(c) == false) { return null; } current = current?.Children?[c]; } return current; }
public void AddWord(string word) { var node = root; for (var i = 0; i < word.Length; ++i) { TrieNode nextNode; var index = word[i] - 'a'; nextNode = node.Children[index]; if (nextNode == null) { nextNode = new TrieNode(); node.Children[index] = nextNode; } node = nextNode; } node.IsEnd = true; }
/** Initialize your data structure here. */ public MapSum() { Root = new TrieNode(); }
public Trie() { root = TrieNode.Empty(); }
public TrieNode() { EndsHere = false; ChildNodes = new TrieNode[26]; }
/** Returns if the word is in the trie. */ public bool Search(string word) { TrieNode node = searchPrefix(word); return(node != null && node.isCompleteWord); }
public Trie() { _root = new TrieNode <T>(null, '\0'); }
public Trie() { this.root = new TrieNode(); }
public bool Search(string word) { TrieNode result = this.GetTrieNode(word); return(result != null && result.EndsWord); }
/** Returns if the word is in the trie. */ public bool Search(string word) { TrieNode node = SearchPrefix(word); return(node != null && node.IsEnd()); }
public TrieNode Search(string word) { return(string.IsNullOrEmpty(word) ? TrieNode.Empty() : Search(root, word[0], word.Remove(0, 1))); }
/** Returns if there is any word in the trie that starts with the given prefix. */ public bool StartsWith(string prefix) { TrieNode node = SearchPrefix(prefix); return(node != null); }
public void Put(char ch, TrieNode node) { links[ch - 'a'] = node; }
public Trie() { Root = new TrieNode(); }
private void ResetWords() { currentMSGScript.EmptyMsg(); DeleteWords(); curNode = words.getRoot(); }
public void _Test_storage_failed_case(string historicallyFailingCase) { string[] lines = historicallyFailingCase.Split(Environment.NewLine); int storageCount = lines.Length - 2; IDb memDb = new MemDb(); StateTree tree = new StateTree(memDb); Address address = new Address(Bytes.FromHexString(lines[0])); int accountIndex = int.Parse(lines[1]); UInt256[] indexes = new UInt256[storageCount]; for (int j = 0; j < storageCount; j++) { indexes[j] = UInt256.Parse(lines[j + 2].Replace("storage: ", string.Empty)); } AddressWithStorage addressWithStorage = new AddressWithStorage(); addressWithStorage.StorageCells = new StorageCell[storageCount]; addressWithStorage.Address = address; StorageTree storageTree = new StorageTree(memDb); for (int j = 0; j < storageCount; j++) { UInt256 index = UInt256.Parse(lines[j + 2].Replace("storage: ", string.Empty)); StorageCell storageCell = new StorageCell(address, index); addressWithStorage.StorageCells[j] = storageCell; byte[] rawKey = new byte[32]; addressWithStorage.StorageCells[j].Index.ToBigEndian(rawKey); TestContext.WriteLine($"Set {Keccak.Compute(rawKey).Bytes.ToHexString()}"); storageTree.Set(addressWithStorage.StorageCells[j].Index, new byte[] { 1 }); storageTree.UpdateRootHash(); storageTree.Commit(); } Account account = Build.An.Account.WithBalance((UInt256)accountIndex).WithStorageRoot(storageTree.RootHash).TestObject; tree.Set(addressWithStorage.Address, account); tree.UpdateRootHash(); tree.Commit(); TreeDumper treeDumper = new TreeDumper(); tree.Accept(treeDumper, tree.RootHash, true); TestContext.WriteLine(treeDumper.ToString()); AccountProofCollector collector = new AccountProofCollector(address, indexes); tree.Accept(collector, tree.RootHash, true); AccountProof accountProof = collector.BuildResult(); accountProof.Address.Should().Be(address); accountProof.Balance.Should().Be((UInt256)accountIndex); accountProof.Nonce.Should().Be(0); accountProof.CodeHash.Should().Be(Keccak.OfAnEmptyString); if (accountIndex != 0) { accountProof.StorageRoot.Should().NotBe(Keccak.EmptyTreeHash); } accountProof.StorageProofs.Length.Should().Be(accountIndex); for (int j = 0; j < accountProof.StorageProofs.Length; j++) { TrieNode node = new TrieNode(NodeType.Unknown, accountProof.StorageProofs[j].Proof.Last()); node.ResolveNode(null); if (node.Value.Length != 1) { TestContext.WriteLine($"{j}"); // throw new InvalidDataException($"{j}"); } } }
private void setNode(char c, TrieNode node) { children[getCharIndex(c)] = node; }
public CaptureNode(TrieNode parent, string segment, ITrieNodeFactory nodeFactory) : base(parent, segment, nodeFactory) { _parameterName = RouteDefinitionSegment.Trim('{', '}'); }
public bool StartsWith(string prefix) { TrieNode result = this.GetTrieNode(prefix); return(result != null); }
/** Initialize your data structure here. */ public Trie() { header = new TrieNode(); }
// will print out word if found in Boggle 2D array public void SearchWord(TrieNode root, char[,] boggle, int row, int column, bool[,] visited, String str) { if (root.isLeaf == true) { Console.WriteLine(str); } if (isSafe(row, column, visited)) { visited[row, column] = true; for (int child = 0; child < SIZE; child++) { if (root.children[child] != null) { char c = (char)(child + 'A'); if (isSafe(row + 1, column + 1, visited) && boggle[row + 1, column + 1] == c) { SearchWord(root.children[child], boggle, row + 1, column + 1, visited, str + c); } if (isSafe(row, column + 1, visited) && boggle[row, column + 1] == c) { SearchWord(root.children[child], boggle, row, column + 1, visited, str + c); } if (isSafe(row - 1, column + 1, visited) && boggle[row - 1, column + 1] == c) { SearchWord(root.children[child], boggle, row - 1, column + 1, visited, str + c); } if (isSafe(row + 1, column, visited) && boggle[row + 1, column] == c) { SearchWord(root.children[child], boggle, row + 1, column, visited, str + c); } if (isSafe(row + 1, column - 1, visited) && boggle[row + 1, column - 1] == c) { SearchWord(root.children[child], boggle, row + 1, column - 1, visited, str + c); } if (isSafe(row, column - 1, visited) && boggle[row, column - 1] == c) { SearchWord(root.children[child], boggle, row, column - 1, visited, str + c); } if (isSafe(row - 1, column - 1, visited) && boggle[row - 1, column - 1] == c) { SearchWord(root.children[child], boggle, row - 1, column - 1, visited, str + c); } if (isSafe(row - 1, column, visited) && boggle[row - 1, column] == c) { SearchWord(root.children[child], boggle, row - 1, column, visited, str + c); } } } visited[row, column] = false; } }
/// <summary> /// 设置关键字 /// </summary> /// <param name="keywords">关键字列表</param> public virtual void SetKeywords(ICollection <string> keywords) { _keywords = keywords.ToArray(); var length = CreateDict(keywords); var root = new TrieNode(); for (Int32 i = 0; i < _keywords.Length; i++) { var p = _keywords[i]; var nd = root; for (Int32 j = 0; j < p.Length; j++) { nd = nd.Add((char)_dict[p[j]]); } nd.SetResults(i); } List <TrieNode> nodes = new List <TrieNode>(); // Find failure functions //ArrayList nodes = new ArrayList(); // level 1 nodes - fail to root node foreach (TrieNode nd in root.m_values.Values) { nd.Failure = root; foreach (TrieNode trans in nd.m_values.Values) { nodes.Add(trans); } } // other nodes - using BFS while (nodes.Count != 0) { List <TrieNode> newNodes = new List <TrieNode>(); //ArrayList newNodes = new ArrayList(); foreach (TrieNode nd in nodes) { TrieNode r = nd.Parent.Failure; char c = nd.Char; while (r != null && !r.m_values.ContainsKey(c)) { r = r.Failure; } if (r == null) { nd.Failure = root; } else { nd.Failure = r.m_values[c]; foreach (var result in nd.Failure.Results) { nd.SetResults(result); } } // add child nodes to BFS list foreach (TrieNode child in nd.m_values.Values) { newNodes.Add(child); } } nodes = newNodes; } root.Failure = root; foreach (var item in root.m_values.Values) { TryLinks(item); } build(root, length); }
/// <summary> /// Adds an item to the <see cref="Trie{TValue}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="Trie{TValue}"/>.</param> /// <exception cref="T:System.ArgumentException">An element with the same charKey already exists in the <see cref="Trie{TValue}"/>.</exception> public void Add(TrieNode <TValue> item) { Add(item.Key, item.Value); }
public Trie() { Root = new TrieNode(); CharSet = new HashSet <char>(); }
/// <summary> /// Called when [page publish]. /// </summary> /// <param name="key">The key.</param> /// <param name="currentPage">The current page.</param> /// <param name="metadata">The metadata.</param> internal static void OnPagePublish(string key, IPage currentPage, IMetadataDictionary metadata) { using (IDocumentSession session = DocumentStore.OpenSession()) { var trie = session.Load <Trie>(TrieId); if (trie.RootNode == null) { trie.RootNode = new TrieNode { PageId = key.Replace("/draft", "") }; } else { TrieNode[] nodes = trie.RootNode.Flatten(n => n.Children).ToArray(); TrieNode parentNode = currentPage.Parent != null ? nodes.SingleOrDefault(n => n.PageId.CompareToIgnoreDraftId(currentPage.Parent.Id)) : null; TrieNode currentNode = nodes.SingleOrDefault(n => n.PageId.CompareToIgnoreDraftId(key)); if (currentNode != null) { if (parentNode != null) { currentPage.Metadata.Slug = Slug.CreateSlug(currentPage); currentPage.Metadata.Url = currentPage.Metadata.Slug.Insert(0, VirtualPathUtility.AppendTrailingSlash(parentNode.Url ?? "")); // the currentPage has been moved so we are moving the node and rewrites the url for all child pages and the current node if (parentNode.ParentId != currentPage.Parent.Id) { trie.MoveTo(parentNode, currentNode); IEnumerable <string> ids = currentNode.Flatten(x => x.Children).Select(x => x.PageId); IDictionary <string, IPage> pages = session.Load <IPage>(ids); // TODO handle null values foreach (var page in pages.Values) { page.Metadata.Url = trie.Get(page.Id).Url; } } currentNode.Url = currentPage.Metadata.Url; } } else if (parentNode != null) { if (parentNode.Children.All(n => n.PageId != key.Replace("/draft", ""))) { currentPage.Metadata.Slug = Slug.CreateSlug(currentPage); currentPage.Metadata.Url = currentPage.Metadata.Slug.Insert(0, VirtualPathUtility.AppendTrailingSlash(parentNode.Url ?? "")); parentNode.Children.Add(new TrieNode { PageId = key.Replace("/draft", ""), ParentId = parentNode.PageId, Url = currentPage.Metadata.Url }); } } } // Clean up any existing draft for this page if (session.Advanced.Exists(key + "/draft")) { var draft = session.Load <IPage>(key + "/draft"); session.Delete(draft); } session.SaveChanges(); } }
public bool Next(T instr, out TrieNode node) { return(Successors.TryGetValue(instr, out node)); }
public static List <string> Solve(string s) { int n = s.Length; bool[] can2 = new bool[n]; bool[] can3 = new bool[n]; for (int i = 0; i < n; i++) { can2[i] = false; can3[i] = false; } can2[n - 2] = true; can3[n - 3] = true; for (int i = n - 1; i >= 5; i--) { if (can2[i] == true) { can3[i - 3] = true; if (Compare(s, i - 2, i, 2)) { can2[i - 2] = true; } } if (can3[i] == true) { can2[i - 2] = true; if (Compare(s, i - 3, i, 3)) { can3[i - 3] = true; } } } TrieNode trie = new TrieNode(); for (int i = 5; i < n; i++) { if (can2[i]) { Add(s, i, 2, trie); } if (can3[i]) { Add(s, i, 3, trie); } } List <string> list = new List <string>(); StringBuilder sb = new StringBuilder(); trie.Visit(sb, list); return(list); }
public Trie(IEqualityComparer <T> hasher) { this.root = new TrieNode(hasher); }
public CaptureNode(TrieNode parent, string segment, TrieNodeFactory nodeFactory) : base(parent, segment, nodeFactory) { this.ExtractParameterName(); }
public void Chaotic_test() { const int accountsCount = 100; CryptoRandom random = new CryptoRandom(); List <AddressWithStorage> addressesWithStorage = new List <AddressWithStorage>(); for (int i = 0; i < accountsCount; i++) { AddressWithStorage addressWithStorage = new AddressWithStorage(); addressWithStorage.StorageCells = new StorageCell[i]; byte[] addressBytes = random.GenerateRandomBytes(20); addressWithStorage.Address = new Address(addressBytes); for (int j = 0; j < i; j++) { byte[] storageIndex = random.GenerateRandomBytes(32); UInt256.CreateFromBigEndian(out UInt256 index, storageIndex); StorageCell storageCell = new StorageCell(addressWithStorage.Address, index); addressWithStorage.StorageCells[j] = storageCell; } addressesWithStorage.Add(addressWithStorage); } IDb memDb = new MemDb(); StateTree tree = new StateTree(memDb); for (int i = 0; i < accountsCount; i++) { Account account = Build.An.Account.WithBalance((UInt256)i).TestObject; StorageTree storageTree = new StorageTree(memDb); for (int j = 0; j < i; j++) { storageTree.Set(addressesWithStorage[i].StorageCells[j].Index, new byte[1] { 1 }); } storageTree.UpdateRootHash(); storageTree.Commit(); account = account.WithChangedStorageRoot(storageTree.RootHash); tree.Set(addressesWithStorage[i].Address, account); } tree.UpdateRootHash(); tree.Commit(); for (int i = 0; i < accountsCount; i++) { AccountProofCollector collector = new AccountProofCollector(addressesWithStorage[i].Address, addressesWithStorage[i].StorageCells.Select(sc => sc.Index).ToArray()); tree.Accept(collector, tree.RootHash, true); AccountProof accountProof = collector.BuildResult(); accountProof.Address.Should().Be(addressesWithStorage[i].Address); accountProof.Balance.Should().Be((UInt256)i); accountProof.Nonce.Should().Be(0); accountProof.CodeHash.Should().Be(Keccak.OfAnEmptyString); if (i != 0) { accountProof.StorageRoot.Should().NotBe(Keccak.EmptyTreeHash); } accountProof.StorageProofs.Length.Should().Be(i); for (int j = 0; j < i; j++) { byte[] indexBytes = new byte[32]; addressesWithStorage[i].StorageCells[j].Index.ToBigEndian(indexBytes.AsSpan()); accountProof.StorageProofs[j].Key.ToHexString().Should().Be(indexBytes.ToHexString(), $"{i} {j}"); TrieNode node = new TrieNode(NodeType.Unknown, accountProof.StorageProofs[j].Proof.Last()); node.ResolveNode(null); // TestContext.Write($"|[{i},{j}]"); if (node.Value.Length != 1) { TestContext.WriteLine(); TestContext.WriteLine(addressesWithStorage[i].Address); TestContext.WriteLine(i); foreach (StorageCell storageCell in addressesWithStorage[i].StorageCells) { TestContext.WriteLine("storage: " + storageCell.Index); } } node.Value.Should().BeEquivalentTo(new byte[] { 1 }); } } }
private void SetKeywords() { var root = new TrieNode(); List <TrieNode> allNode = new List <TrieNode>(); allNode.Add(root); Dictionary <int, List <TrieNode> > allNodeLayers = new Dictionary <int, List <TrieNode> >(); for (int i = 0; i < _keywords.Length; i++) { var p = _keywords[i]; var nd = root; for (int j = 0; j < p.Length; j++) { nd = nd.Add((char)p[j]); if (nd.Layer == 0) { nd.Layer = j + 1; List <TrieNode> trieNodes; if (allNodeLayers.TryGetValue(nd.Layer, out trieNodes) == false) { trieNodes = new List <TrieNode>(); allNodeLayers[nd.Layer] = trieNodes; } trieNodes.Add(nd); } } nd.SetResults(i); } foreach (var trieNodes in allNodeLayers) { foreach (var nd in trieNodes.Value) { allNode.Add(nd); } } allNodeLayers = null; List <TrieNode> nodes = new List <TrieNode>(); // Find failure functions // level 1 nodes - fail to root node foreach (TrieNode nd in root.m_values.Values) { nd.Failure = root; foreach (TrieNode trans in nd.m_values.Values) { nodes.Add(trans); } } // other nodes - using BFS while (nodes.Count != 0) { List <TrieNode> newNodes = new List <TrieNode>(); foreach (TrieNode nd in nodes) { TrieNode r = nd.Parent.Failure; char c = nd.Char; while (r != null && !r.m_values.ContainsKey(c)) { r = r.Failure; } if (r == null) { nd.Failure = root; } else { nd.Failure = r.m_values[c]; foreach (var result in nd.Failure.Results) { nd.SetResults(result); } } // add child nodes to BFS list foreach (TrieNode child in nd.m_values.Values) { newNodes.Add(child); } } nodes = newNodes; } root.Failure = root; for (int i = 0; i < allNode.Count; i++) { allNode[i].Index = i; } var allNode2 = new List <TrieNode2>(); for (int i = 0; i < allNode.Count; i++) { allNode2.Add(new TrieNode2()); } for (int i = 0; i < allNode2.Count; i++) { var oldNode = allNode[i]; var newNode = allNode2[i]; foreach (var item in oldNode.m_values) { var key = item.Key; var index = item.Value.Index; newNode.Add(key, allNode2[index]); } foreach (var item in oldNode.Results) { newNode.SetResults(item); } if (oldNode.Failure != root) { foreach (var item in oldNode.Failure.m_values) { var key = item.Key; var index = item.Value.Index; if (newNode.HasKey(key) == false) { newNode.Add(key, allNode2[index]); } } foreach (var item in oldNode.Failure.Results) { newNode.SetResults(item); } } } allNode.Clear(); allNode = null; root = null; TrieNode2[] first = new TrieNode2[char.MaxValue + 1]; foreach (var item in allNode2[0].m_values) { first[item.Key] = item.Value; } _first = first; }
public ContactTrie() { root = new TrieNode(); }