Ejemplo n.º 1
0
 public void AddWord_EmptyString01()
 {
     trie = new Trie();
     Assert.AreEqual(0, trie.GetWords().Count);
     trie.AddWord("");
     Assert.AreNotEqual(0, trie.GetWords().Count);
 }
Ejemplo n.º 2
0
        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);
            }
        }
Ejemplo n.º 3
0
 public void Seed(string agarathiFileName, int minimumSuffixLength = 1)
 {
     if (!_isLoaded)
     {
         Trie = new SuffixTamilTrie<string>(minimumSuffixLength);
         BuildUpTamil(agarathiFileName, Trie);
     }
 }
Ejemplo n.º 4
0
        public void A_trie_with_some_values()
        {
            subject = new Trie<object>();

            subject.Add("polyglot", "one");
            subject.Add("polyhedron", "two");
            subject.Add("polyglottal", "three");
        }
Ejemplo n.º 5
0
 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);
     }
 }
Ejemplo n.º 6
0
 public virtual void Setup()
 {
     Trie = CreateTrie();
     for (int i = 0; i < Words40.Length; i++)
     {
         Trie.Add(Words40[i], i);
     }
 }
Ejemplo n.º 7
0
        public FileTrie(string folder, string file, int textLength = 1)
        {
            minSearchTextLength = 1;

            searchTrie = new SuffixTrie <WordPosition>(minSearchTextLength);

            LoadFiles(folder, file);
        }
Ejemplo n.º 8
0
 /// <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");
     }
 }
Ejemplo n.º 9
0
Archivo: Trie.cs Proyecto: Thaina/Towel
 /// <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);
 }
Ejemplo n.º 10
0
 public virtual void Setup()
 {
     Trie = CreateTrie();
     for (int i = 0; i < KeyWords.Length; i++)
     {
         Trie.Add(KeyWords[i], i);
     }
 }
Ejemplo n.º 11
0
        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);
        }
Ejemplo n.º 12
0
 private void BuildUpTamil(string fileName, ITrie<string> trie)
 {
     IEnumerable<string> allWordsInFile = GetTamilWordsFromFile(fileName);
     foreach (var word in allWordsInFile)
     {
         trie.Add(word, word);
     }
     _isLoaded = true;
 }
Ejemplo n.º 13
0
        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);
            }
        }
Ejemplo n.º 14
0
        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);
            }
        }
Ejemplo n.º 15
0
 /// <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 !);
 }
Ejemplo n.º 16
0
        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);
        }
Ejemplo n.º 17
0
 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();
 }
Ejemplo n.º 18
0
 public void ExhaustiveParallelAddFails()
 {
     while (true)
     {
         ITrie <int> trie = CreateTrie();
         LongPhrases40
         .AsParallel()
         .ForAll(phrase => trie.Add(phrase, phrase.GetHashCode()));
     }
 }
Ejemplo n.º 19
0
 public MainForm()
 {
     InitializeComponent();
     m_PatriciaTrie = new SuffixTrie <WordPosition>(3);
     //m_PatriciaTrie = new FakeTrie<WordPosition>();
     folderName.Text =
         Path.Combine(
             Directory.GetCurrentDirectory(),
             "texts");
 }
Ejemplo n.º 20
0
 /// <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));
 }
Ejemplo n.º 22
0
        // 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();
        }
Ejemplo n.º 23
0
        // 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();
        }
Ejemplo n.º 24
0
        // new empty branch node
        public TrieNode(ITrie trie)
        {
            this.trie = trie;
            rlp       = RlpEncoder.New(17).Encode();

            Type  = NodeType.FullNode;
            Dirty = true;

            DecodeRLP();
        }
Ejemplo n.º 25
0
        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));
 }
Ejemplo n.º 27
0
 /// <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));
 }
Ejemplo n.º 28
0
 public static void FindWords(ITrie wordTrie)
 {
     for (int i = 0; i < 100; i++)
     {
         foreach (var word in SearchWords)
         {
             wordTrie.HasWord(word);
         }
     }
 }
Ejemplo n.º 29
0
 private void ExhaustiveParallelAddThrowAggregateException()
 {
     while (true)
     {
         ITrie <int> trie = CreateTrie();
         LongPhrases40
         .AsParallel()
         .ForAll(phrase => trie.Add(phrase, phrase.GetHashCode()));
     }
 }
Ejemplo n.º 30
0
        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));
 }
Ejemplo n.º 32
0
        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));
            }
        }
Ejemplo n.º 33
0
 /// <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));
 }
Ejemplo n.º 34
0
        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.");
     }
 }
Ejemplo n.º 36
0
        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);
        }
Ejemplo n.º 37
0
        /// <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));
        }
Ejemplo n.º 38
0
        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());
                }
            }
        }
Ejemplo n.º 39
0
        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();
        }
Ejemplo n.º 42
0
        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));
            }
        }
Ejemplo n.º 43
0
        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();
        }
Ejemplo n.º 44
0
        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();
        }
Ejemplo n.º 45
0
 public void a_trie_of_objects()
 {
     subject = new Trie<object>();
 }
Ejemplo n.º 46
0
 public void SetUp()
 {
     trie = BuildSampleTrie();
 }
Ejemplo n.º 47
0
 public void TearDown()
 {
     trie = null;
 }
 public TrieStationRepository(ITrie trie)
 {
     _trie = trie;
 }
Ejemplo n.º 49
0
 /// <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);
     }
 }
Ejemplo n.º 50
0
 public SwumDataStructure()
 {
     hashOfSignaturesToSwumRecord = new Dictionary<int, SwumDataRecord>();
     trie = new PatriciaTrie<SwumDataRecord>();
 }
 public SeekAheadTrieDecoration(ITrie decorated)
     : base(decorated)
 {
 }
Ejemplo n.º 52
0
 public TamilAgarathi(string agarathiFileName= "agarathiValid.txt", int minimumSuffixLength = 1)
 {
     Trie = new SuffixTamilTrie<string>(minimumSuffixLength);
     BuildUpTamil(agarathiFileName, Trie);
 }
Ejemplo n.º 53
0
        /// <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;
        }
Ejemplo n.º 54
0
 public ByPositionTrieDecoration(ITrie decorated)
     : base(decorated)
 {
 }