public void AddWord_EmptyString01() { trie = new Trie(); Assert.AreEqual(0, trie.GetWords().Count); trie.AddWord(""); Assert.AreNotEqual(0, trie.GetWords().Count); }
private static void LookUp(string searchString, ITrie<int> trie) { Console.WriteLine("----------------------------------------"); Console.WriteLine("Look-up for string '{0}'", searchString); var stopWatch = new Stopwatch(); stopWatch.Start(); int[] result = trie.Retrieve(searchString).ToArray(); stopWatch.Stop(); string matchesText = String.Join(",", result); int matchesCount = result.Count(); if (matchesCount == 0) { Console.WriteLine("No matches found.\tTime: {0}", stopWatch.Elapsed); } else { Console.WriteLine(" {0} matches found. \tTime: {1}\tLines: {2}", matchesCount, stopWatch.Elapsed, matchesText); } }
public void Seed(string agarathiFileName, int minimumSuffixLength = 1) { if (!_isLoaded) { Trie = new SuffixTamilTrie<string>(minimumSuffixLength); BuildUpTamil(agarathiFileName, Trie); } }
public void A_trie_with_some_values() { subject = new Trie<object>(); subject.Add("polyglot", "one"); subject.Add("polyhedron", "two"); subject.Add("polyglottal", "three"); }
private static void BuildUp(string fileName, ITrie<int> trie) { IEnumerable<WordAndLine> allWordsInFile = GetWordsFromFile(fileName); foreach (WordAndLine wordAndLine in allWordsInFile) { trie.Add(wordAndLine.Word, wordAndLine.Line); } }
public virtual void Setup() { Trie = CreateTrie(); for (int i = 0; i < Words40.Length; i++) { Trie.Add(Words40[i], i); } }
public FileTrie(string folder, string file, int textLength = 1) { minSearchTextLength = 1; searchTrie = new SuffixTrie <WordPosition>(minSearchTextLength); LoadFiles(folder, file); }
/// <summary>Removes a value.</summary> /// <typeparam name="T">The type of value.</typeparam> /// <typeparam name="TData">The type of the data.</typeparam> /// <param name="trie">The trie to remove the value from.</param> /// <param name="stepper">The keys to store the value relative to.</param> public static void Remove <T, TData>(this ITrie <T, TData> trie, Action <Action <T> > stepper) { var(success, exception) = trie.TryRemove(stepper); if (!success) { throw exception ?? new ArgumentException($"{nameof(Remove)} failed but the {nameof(exception)} is null"); } }
/// <summary>Gets a value.</summary> /// <typeparam name="T">The type of value.</typeparam> /// <typeparam name="K">The type of the keys.</typeparam> /// <param name="trie">The trie to get the value from.</param> /// <param name="stepper">The keys of the relative value.</param> /// <returns>The value.</returns> public static T Get <K, T>(this ITrie <K, T> trie, Stepper <K> stepper) { if (!trie.TryGet(stepper, out T value, out Exception exception)) { throw exception; } return(value); }
public virtual void Setup() { Trie = CreateTrie(); for (int i = 0; i < KeyWords.Length; i++) { Trie.Add(KeyWords[i], i); } }
private static IEnumerable <string> GetPossibleSolutionsForHint(ITrie wordTrie, char?[,] characterMatrix, Hint hint) { List <string> possibleSolutions = new List <string>(); //string hintString = string.Empty; //if (hint.IsOcrCandidate) //{ // IEnumerable<string> hintCharacters = ocrProcessor.GetCharactersFromImage(hint.OcrCandidate); // hintString = string.Join("", hintCharacters); //} //Node currentNode = wordTrie.Prefix(hintString); //HintLocation startingPoint = GetStartingPoint(characterMatrix, hintString); //if (startingPoint.IsFoundInMatrix) //{ //} int matrixRows = characterMatrix.GetLength(0); int matrixCols = characterMatrix.GetLength(1); for (int rows = 0; rows < matrixRows; rows++) { for (int cols = 0; cols < matrixCols; cols++) { string currentValue = characterMatrix[rows, cols].ToString(); Move initialMove = new Move(currentValue, 1, new Location(rows, cols)); Queue <Move> moveQueue = new Queue <Move>(); moveQueue.Enqueue(initialMove); while (moveQueue.Count > 0) { Move currentMove = moveQueue.Dequeue(); currentMove.Parent?.VisitChild(currentMove); if (wordTrie.WordExists(currentMove.Value)) { if (currentMove.Depth == hint.HintSize && wordTrie.IsFullWord(currentMove.Value)) { possibleSolutions.Add(currentMove.Value); SqueezeMatrix(characterMatrix, currentMove.GetTraversedLocations()); continue; } IEnumerable <Move> availableMoves = GetAvailableMoves(currentMove, characterMatrix); foreach (Move availableMove in availableMoves) { currentMove.AddChild(availableMove); moveQueue.Enqueue(availableMove); } } } } } return(possibleSolutions); }
private void BuildUpTamil(string fileName, ITrie<string> trie) { IEnumerable<string> allWordsInFile = GetTamilWordsFromFile(fileName); foreach (var word in allWordsInFile) { trie.Add(word, word); } _isLoaded = true; }
private static void BuildTrie(string filePath, ITrie <int> trie) { IEnumerable <PairStringInt> words = ReadFile(filePath); foreach (var word in words) { trie.Add(word.Word, word.Line); } }
private static void BuildUp(string fileName, ITrie <int> trie) { IEnumerable <WordAndLine> allWordsInFile = GetWordsFromFile(fileName); foreach (WordAndLine wordAndLine in allWordsInFile) { trie.Add(wordAndLine.Word, wordAndLine.Line); } }
/// <summary>Gets a value.</summary> /// <typeparam name="T">The type of value.</typeparam> /// <typeparam name="TData">The type of the data.</typeparam> /// <param name="trie">The trie to get the value from.</param> /// <param name="stepper">The keys of the relative value.</param> /// <returns>The value.</returns> public static TData Get <T, TData>(this ITrie <T, TData> trie, Action <Action <T> > stepper) { var(success, value, exception) = trie.TryGet(stepper); if (!success) { throw exception ?? new ArgumentException($"{nameof(Get)} failed but the {nameof(exception)} is null"); } return(value !); }
public static ITrie Set(this ITrie trie, IImmutableDictionary <byte[], IValue> values) { foreach (var pair in values) { trie = trie.Set(pair.Key, pair.Value); } return(trie); }
public Level(string chosenLevel, IPlayer player, IWordOperator wordOperator, ITrieFactory trieFactory, IWriter writer, IReader reader) { this.player = player; this.writer = writer; this.reader = reader; this.chosenLevel = chosenLevel; this.wordOperator = wordOperator; trieFromDictionary = trieFactory.CreateTrieFromDictionary(); }
public void ExhaustiveParallelAddFails() { while (true) { ITrie <int> trie = CreateTrie(); LongPhrases40 .AsParallel() .ForAll(phrase => trie.Add(phrase, phrase.GetHashCode())); } }
public MainForm() { InitializeComponent(); m_PatriciaTrie = new SuffixTrie <WordPosition>(3); //m_PatriciaTrie = new FakeTrie<WordPosition>(); folderName.Text = Path.Combine( Directory.GetCurrentDirectory(), "texts"); }
/// <summary> /// Constructs a trie containing the given string and having the given child at the given label. /// If s contains any characters other than lower-case English letters, /// throws an ArgumentException. /// If childLabel is not a lower-case English letter, throws an ArgumentException. /// </summary> /// <param name="s">The string to include.</param> /// <param name="hasEmpty">Indicates whether this trie should contain the empty string.</param> /// <param name="childLabel">The label of the child.</param> /// <param name="child">The child labeled childLabel.</param> public TrieWithManyChildren(string s, bool hasEmpty, char childLabel, ITrie child) { if (childLabel < 'a' || childLabel > 'z') { throw new ArgumentException(); } _hasEmptyString = hasEmpty; _children[childLabel - 'a'] = child; Add(s); }
public TrieWithOneChild(string s, bool isEmpty) { if (s == "" || s[0] < 'a' || s[0] > 'z') { throw new ArgumentException(); } _hasEmptyString = isEmpty; _label = s[0]; _child = new TrieWithNoChildren().Add(s.Substring(1)); }
// new extension node public TrieNode(ITrie trie, TrieKey key, TrieNode next) { this.trie = trie; rlp = new RlpEncoder(key, next.Hash).Encode(); Type = NodeType.ShortNode; Dirty = true; DecodeRLP(); }
// new leaf node public TrieNode(ITrie trie, TrieKey key, byte[] value) { this.trie = trie; rlp = new RlpEncoder(key, value).Encode(); Type = NodeType.ValueNode; Dirty = true; DecodeRLP(); }
// new empty branch node public TrieNode(ITrie trie) { this.trie = trie; rlp = RlpEncoder.New(17).Encode(); Type = NodeType.FullNode; Dirty = true; DecodeRLP(); }
public void TrieContractContains1() { ITrie <String, char, String> trie = this.GetInstance(); trie.Add("test", "a"); trie.Add("testing", "b"); Assert.IsTrue(trie.ContainsKey("test")); Assert.IsTrue(trie.ContainsKey("testing")); }
/// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="b"></param> public TrieWithOneChild(string s, bool b) { if (s == "" || s[0] < 'a' || s[0] > 'z') { throw new ArgumentException(); } _contains = b; _label = s[0]; _child = new TrieWithNoChildren().Add(s.Substring(1)); }
/// <summary> /// constructor /// </summary> /// <param name="child"></param> /// <param name="check"></param> public TrieWithOneChildren(string child, bool check) { if (child == "" || child[0] < 'a' || child[0] > 'z') { throw new ArgumentException(); } _check = check; _label = child[0]; _child = new TrieWithNoChildren().Add(child.Substring(1)); }
public static void FindWords(ITrie wordTrie) { for (int i = 0; i < 100; i++) { foreach (var word in SearchWords) { wordTrie.HasWord(word); } } }
private void ExhaustiveParallelAddThrowAggregateException() { while (true) { ITrie <int> trie = CreateTrie(); LongPhrases40 .AsParallel() .ForAll(phrase => trie.Add(phrase, phrase.GetHashCode())); } }
public void TrieContractAdd2() { ITrie <String, char, String> trie = this.GetInstance(); trie.Add("test", "a"); trie.Add("testing", "b"); Assert.AreEqual("a", trie["test"]); Assert.AreEqual("b", trie["testing"]); }
public TrieWithOneChild(string x, bool empty) { if (empty || x[0] > 'z' || x[0] < 'a') { throw new Exception(); } _empty = empty; _label = x[0]; _child = new TrieWithNoChildren().Add(x.Substring(1)); }
protected void VerifyPresence(ITrie trie, List <string> items) { List <string> allEntries = trie.GetAllEntries(); Assert.AreEqual(items.Count, allEntries.Count); foreach (string s in items) { Assert.IsTrue(allEntries.Contains(s)); } }
/// <summary> /// Constructs a trie containing the given string. /// If s contains any characters other than lower-case English letters, /// throws an ArgumentException. /// </summary> /// <param name="s">The word to add</param> /// <param name="word">Whether this trie is a word</param> public TrieWithOneChild(string s, bool word) { if (s == "" || s[0] < 'a' || s[0] > 'z') { throw new ArgumentException(); } _isWord = word; _childLabel = s[0]; _child = new TrieWithNoChildren(); _child = _child.Add(s.Substring(1)); }
public static List <int> Evaluate(Population pop, ITrie dictionary, string encryptedSentence) { List <int> fitness = new List <int>(); foreach (var individual in pop.Individuals) { fitness.Add(Fitness(individual, dictionary, encryptedSentence)); } return(fitness); }
public AutoCompleteProvider(ITrie <string> trie, INodeFactory <string> nodeFactory) { if ((_Trie = trie) == null) { throw new ArgumentNullException($"{nameof(trie)} is null."); } if ((_NodeFactory = nodeFactory) == null) { throw new ArgumentNullException($"{nameof(nodeFactory)} is null."); } }
public void VerifyContains(string[] data, ITrie trie) { List <string> items = new List <string>(data); foreach (string s in items) { trie.Add(s); } VerifyPresence(trie, items); }
/// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="hasEmpty"></param> /// <param name="childLabel"></param> /// <param name="child"></param> public TrieWithOneChild(string s, bool hasEmpty) { if (s == "" || !(s[0] >= 'a' && s[0] <= 'z')) { throw new ArgumentException(); } _hasEmptyString = hasEmpty; _label = s[0]; _onlyChild = new TrieWithNoChildren().Add(s.Substring(1)); }
private static void ReadWordsFromText(StreamReader reader, ITrie trie) { while (!reader.EndOfStream) { var line = reader.ReadLine(); var matches = Regex.Matches(line, @"\w+"); foreach (var match in matches) { trie.AddWord(match.ToString()); } } }
public void Clear() { lock (hashOfSignaturesToSwumRecord) { hashOfSignaturesToSwumRecord.Clear(); } lock (trie) { trie = new PatriciaTrie<SwumDataRecord>(); //and let garbage collector deal with previous trie } }
private static void GetCountOfAllUniqueWords(ICollection<string> wordsForSearcing, ITrie trie) { Console.Write("Searching words... "); sw.Start(); foreach (var word in wordsForSearcing) { trie.WordCount(word); // return the number of words } sw.Stop(); Console.WriteLine("\rSearching words -> Unique words: {0} | Elapsed time: {1}\n", wordsForSearcing.Count, sw.Elapsed); sw.Reset(); }
private static void AddWordsToTrie(ICollection<string> words, ITrie trie) { Console.Write("Adding words to trie... "); sw.Start(); foreach (var word in words) { trie.AddWord(word); } sw.Stop(); Console.WriteLine("\rAdding words to trie -> Elapsed time: {1}\n", words.Count, sw.Elapsed); sw.Reset(); }
public virtual void Setup() { Trie = CreateTrie(); for (int i = 0; i < Words40.Length; i++) { var q = new Queue<int>(); q.Enqueue(i); Trie.Add( Words40[i].ToCharArray(), q, (existing, insert) => existing == null ? insert : existing.Concat(insert)); } }
private static void AddWordsToTrie(ICollection<string> words, ITrie trie) { Console.WriteLine("Adding words to trie... "); Console.WriteLine(new string('-', 30)); Timer.Start(); foreach (var word in words) { trie.Add(word); } Timer.Stop(); Console.WriteLine("Added words to trie {0} -> Elapsed time: {1}", words.Count, Timer.Elapsed); Console.WriteLine(new string('-', 30)); Timer.Reset(); }
private static void GetCountOfAllUniqueWords(ICollection<string> wordsToBeSearched, ITrie trie) { Console.WriteLine("Searching for words... "); Console.WriteLine(new string('-', 30)); Timer.Start(); foreach (var word in wordsToBeSearched) { trie.WordCount(word); // return the number of words } Timer.Stop(); Console.WriteLine("Searched words -> Unique words: {0} | Elapsed time: {1}", wordsToBeSearched.Count, Timer.Elapsed); Console.WriteLine(new string('-', 30)); Timer.Reset(); }
public void a_trie_of_objects() { subject = new Trie<object>(); }
public void SetUp() { trie = BuildSampleTrie(); }
public void TearDown() { trie = null; }
public TrieStationRepository(ITrie trie) { _trie = trie; }
/// <summary> /// Reads the dictionary. /// </summary> private void GetDictionary() { try { using (StreamReader input = File.OpenText(_dictionaryFile)) { for (int i = 0; i < _dictionarySize; i++) { trie = trie.Add(input.ReadLine()); _wordsRead++; } } } catch (Exception ex) { MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public SwumDataStructure() { hashOfSignaturesToSwumRecord = new Dictionary<int, SwumDataRecord>(); trie = new PatriciaTrie<SwumDataRecord>(); }
public SeekAheadTrieDecoration(ITrie decorated) : base(decorated) { }
public TamilAgarathi(string agarathiFileName= "agarathiValid.txt", int minimumSuffixLength = 1) { Trie = new SuffixTamilTrie<string>(minimumSuffixLength); BuildUpTamil(agarathiFileName, Trie); }
/// <summary> /// Finds all permutations of chars that form multiword /// anagrams when the first word is prefixed by wordPrefix. /// For each of these permutations, adds the words in phrasePrefix /// appended by the permutation to StringSet, with the word order /// reversed. /// </summary> /// <param name="phrasePrefix">The phrase to prefix /// each anagram with.</param> /// <param name="wordPrefix">The string to include as /// the prefix for the first word in each anagram.</param> /// <param name="chars">The characters for which to find /// anagrams.</param> private ImmutableTrie FindAnagrams(ITrie lastWord, Queue<char> chars) { if (lastWord == null) return null; ImmutableTrie[] tries = new ImmutableTrie[_map.CharacterCount]; bool nonNull = false; if (chars.Count == 0) { if (lastWord.IsEmpty()) { Key k = new Key(chars, _map); ImmutableTrie result = null; if (_dictionary.TryGetValue(k, out result)) { tries[_map.GetLocation(' ')] = result; } else { tries[_map.GetLocation(' ')] = new ImmutableTrie(new ImmutableTrie[0], true, _map); _dictionary.Add(k, tries[_map.GetLocation(' ')]); } if(tries[_map.GetLocation(' ')] != null) nonNull = true; } else //if (prefix.Length == 0) return null; //_anagrams.Add(""); } else { if (lastWord.IsEmpty()) { //char x = chars.Dequeue(); tries[_map.GetLocation(' ')] = FindAnagrams(trie, chars); if (tries[_map.GetLocation(' ')] != null) nonNull = true; //chars.Enqueue(x); //tries[_map.GetLocation(' ')] = new ImmutableTrie(new ImmutableTrie[0], true, _map); } char c = 'Z'; for (int i = 0; i < chars.Count; i++) { //if (c == chars.Peek()) // continue; c = chars.Dequeue(); tries[_map.GetLocation(c)] = FindAnagrams(lastWord.Continuations(c), chars); if (tries[_map.GetLocation(c)] != null) nonNull = true; chars.Enqueue(c); } } if(nonNull) return new ImmutableTrie(tries, false, _map); return null; }
public ByPositionTrieDecoration(ITrie decorated) : base(decorated) { }