Exemplo n.º 1
0
        public void EmptyTrie()
        {
            var trie = new Trie<string, string>();

            var get = trie.Values("43").SingleOrDefault();
            Assert.Null(get);
        }
Exemplo n.º 2
0
        public void AddWithSameKey()
        {
            var trie = new Trie<bool>();

            trie.Add("a", false);
            trie.Add("a", true);
        }
Exemplo n.º 3
0
 public void AddWords()
 {
     words = new Trie();
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
     CloudBlobContainer container = blobClient.GetContainerReference("http://hudpoi459storage.blob.core.windows.net/hudson/");
     CloudBlockBlob blockBlob = container.GetBlockBlobReference("wikipedia.txt");
     try
     {
         using (var stream = blockBlob.OpenRead())
         {
             using (StreamReader sr = new StreamReader(stream))
             {
                 string line;
                 while ((line = sr.ReadLine()) != null)
                 {
                     words.Insert(line);
                 }
             }
         }
     }
     catch (OutOfMemoryException)
     {
         GC.Collect();
     }
 }
Exemplo n.º 4
0
 //    Start a pattern match at the beginning with one object.
 internal PatternMatcher(ProseRuntime runtime)
 {
     this.runtime = runtime;
     patternTrie = runtime.GlobalScope.PatternTree;
     state = MatcherState.MATCHING_OBJECT;
     currNode = patternTrie.Root;
 }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Trie trie = new Trie();
            Dictionary<string, int> dict = new Dictionary<string, int>();
            Stopwatch sw = new Stopwatch();

            sw.Start();
            List<string> wordsFromText = GetWordsFromText();
            sw.Stop();
            Console.WriteLine("Word extraction finished in {0}", sw.Elapsed);

            List<string> wordsToSearch = new List<string>();
            int numberOfWords = 100;

            int len = numberOfWords < wordsFromText.Count ? numberOfWords : wordsFromText.Count;

            for (int i = 0; i < len; i++)
			{
                wordsToSearch.Add(wordsFromText[i]);			 
			}

            AddWordsUsingTrie(trie, wordsFromText, sw);
            AddWordsUsingDict(dict, wordsFromText, sw);

            FindWordsUsingTrie(trie, wordsToSearch, sw);
            FindWordsUsingDict(dict, wordsToSearch, sw);
        }
Exemplo n.º 6
0
        public void Trie_Clone_should_work()
        {
            var trie = new Trie<char, int>();
              trie.SetValue("foo", 42);
              trie.SetValue("foobar", 13);
              trie.SetValue("fizban", 53);
              trie.SetValue("fizbang", 12);

              var cloneTrie = trie.Clone();
              cloneTrie.SetValue("fip", 17);

              int value;

              trie.TryGetValue("foo", out value).Should().BeTrue();
              value.Should().Be(42);
              trie.TryGetValue("foobar", out value).Should().BeTrue();
              value.Should().Be(13);
              trie.TryGetValue("fizban", out value).Should().BeTrue();
              value.Should().Be(53);
              trie.TryGetValue("fizbang", out value).Should().BeTrue();
              value.Should().Be(12);
              trie.TryGetValue("fip", out value).Should().BeFalse();

              cloneTrie.TryGetValue("foo", out value).Should().BeTrue();
              value.Should().Be(42);
              cloneTrie.TryGetValue("foobar", out value).Should().BeTrue();
              value.Should().Be(13);
              cloneTrie.TryGetValue("fizban", out value).Should().BeTrue();
              value.Should().Be(53);
              cloneTrie.TryGetValue("fizbang", out value).Should().BeTrue();
              value.Should().Be(12);
              cloneTrie.TryGetValue("fip", out value).Should().BeTrue();
              value.Should().Be(17);
        }
Exemplo n.º 7
0
    static void Main()
    {
        Trie<string> trie = new Trie<string>();
        StreamReader reader = new StreamReader(@"../../../text.txt");
        using (reader)
        {
            string text = reader.ReadToEnd();

            char[] separators = { ' ', '.', '!', '-', '?', '_' };
            string[] array = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < array.Length; i++)
            {
                trie.Put(array[i], i.ToString());
            }

            string word = "Conan";
            for (int i = 0; i < word.Length; i++)
            {

            }
            foreach (var item in trie.Matcher.GetPrefixMatches())
            {
                Console.WriteLine(item);
            }
            Console.WriteLine(trie.Matcher.GetExactMatch());
        }
    }
Exemplo n.º 8
0
 public EnemyInputManager(List<String> texts, Game game)
 {
     trie = new Trie<Enemy>();
     this.texts = texts;
     this.game = game;
     currentlyMatched = new List<Enemy>();
 }
Exemplo n.º 9
0
    public static void Main()
    {
        string inputText;
        StreamReader reader = new StreamReader("test.txt");

        using (reader)
        {
            inputText = reader.ReadToEnd().ToLower();
        }

        var matches = Regex.Matches(inputText, @"[a-zA-Z]+");
        HashSet<string> uniqueWords = new HashSet<string>();
        var trie = new Trie();

        for (int i = 0; i < matches.Count; i++)
        {
            uniqueWords.Add(matches[i].ToString());
            trie.Add(matches[i].ToString());
        }

        foreach (var word in uniqueWords)
        {
            Console.WriteLine("{0} -> {1} times", word, trie.GetWordOccurance(word));
        }
    }
Exemplo n.º 10
0
        public void PrefixMatchTest()
        {
            string s = @"
                In computer science, a trie, or prefix tree,
                is an ordered tree data structure that is used to
                store an associative array where the keys are strings.
                Unlike a binary search tree, no node in the tree
                stores the key associated with that node;
                instead, its position in the tree shows what key
                it is associated with. All the descendants
                of any one node have a common prefix of the string
                associated with that node, and the root is associated
                with the empty string. Values are normally not associated
                with every node, only with leaves and some inner nodes
                that happen to correspond to keys of interest.
            ";

            Trie<char, string> wordIndex = new Trie<char, string>(new LettersDomain());
            foreach (string word in s.Replace("\r", "").Replace("\n", " ").Replace("\t", "").Split(' ', ',', ';', '.'))
            {
                if (word.Length > 0)
                {
                    wordIndex.Add(word, word);
                }
            }

            ITrieEnumerator<char, string> matches = wordIndex.PrefixMatch("p");
            while (matches.MoveNext())
            {
                Console.WriteLine(matches.Current.Value);
            }
        }
Exemplo n.º 11
0
        public static void Main()
        {
            Trie<int> trie = new Trie<int>();

            using (StreamReader reader = new StreamReader("../../test.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string[] line = reader.ReadLine().Split(new char[] { ' ', '.', ',', '!', '?', ':', ';', '-' }, StringSplitOptions.RemoveEmptyEntries).ToArray();

                    foreach (var word in line)
                    {
                        if (!trie.ContainsKey(word))
                        {
                            trie.Add(word, 1);
                        }
                        else
                        {
                            trie[word]++;
                        }
                    }
                }
            }

            trie.Matcher.Next("eros");
            Console.WriteLine(trie.Matcher.GetExactMatch());
        }
Exemplo n.º 12
0
 private static Trie<string> ParseTree(IEnumerable<string> p)
 {
     var trie = new Trie<string>();
     foreach (var word in p)
         trie.Add(word, word);
     return trie;
 }
        private static Trie<int> ParseFile(string filename)
        {
            Trie<int> trie = new Trie<int>();

            Console.WriteLine("Reading file and loading content in trie:");

            using (StreamReader reader = new StreamReader(filename))
            {
                while (!reader.EndOfStream)
                {
                    reader
                        .ReadLine()
                        .Split(' ', '.', ',', '?', '!', ':')
                        .ToList()
                        .ForEach(word =>
                        {
                            if (!trie.ContainsKey(word))
                            {
                                trie.Add(word, 1);
                            }
                            else
                            {
                                trie[word] += 1;
                            }
                        });
                }
            }

            Console.WriteLine("File read and loaded into trie");

            return trie;
        }
Exemplo n.º 14
0
        public void Add_ItemExists_Throws()
        {
            Trie<string, char, int> trie = new Trie<string, char, int>();

            trie.Add("key", 5);
            trie.Add("key", 6);
        }
Exemplo n.º 15
0
        public void TrieTests_EnumerateInOrder2()
        {
            Trie<char> trie = new Trie<char>();

            List<string> items = new List<string>();

            Random r = new Random();
            for (int i = 0; i < 100000; i++)
            {
                char[] word = new char[r.Next(10) + 1];

                for (int j = 0; j < word.Length; j++)
                {
                    word[j] = (char)(97 + r.Next(26));
                }

                string sword = new string(word);

                items.Add(sword);

                trie.Insert(sword);
            }

            items.Sort();

            var actualOrder = trie.EnumerateInOrder().Select(sequence => new string(sequence.ToArray())).ToList();

            Assert.IsTrue(items.Except(actualOrder).Count() == 0);
            Assert.IsTrue(actualOrder.Except(items).Count() == 0);
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            Stopwatch _s = new Stopwatch();

            _s.Start();

            /* */
            //Trie<byte[]> _trie = new Trie<byte[]>();
            Trie<string> _trie = new Trie<string>();
            for (int i = 0; i < 1000000; i++)
            {
                //byte[] bkey = Encoding.ASCII.GetBytes("root/sub/key" + i);
                //byte[] bvalue = Encoding.ASCII.GetBytes("test_" + i);
                _trie.Add("root/sub/key" + i, "test_" + i);
            }

            //var f=_trie.Find("root/sub/key999090");
            var g = _trie.FindAll("root/sub/key0");
            // SPEED ~ 1700 msec
            //*/

            /* /
            Trie2 _trie2 = new Trie2();
            for (int i = 0; i < 1000000; i++)
            {
                _trie2.AddNodeForWord("root/sub/key" + i);
            }
            //*/

            _s.Stop();

            Console.WriteLine("hj");
            Console.ReadKey();
        }
Exemplo n.º 17
0
        public void TrieOnce()
        {
            var trie = new Trie<string, string>();
            trie.Add("123", "hello");

            var get = trie.Values("123").Single();
            Assert.Equal("hello", get);
        }
Exemplo n.º 18
0
        public void NoKey()
        {
            var trie = new Trie<string, string>();
            trie.Add("123", "hello");

            var get = trie.Values("43").SingleOrDefault();
            Assert.Null(get);
        }
Exemplo n.º 19
0
 public CategoryService(IServiceLocator serviceLocator)
     : base(serviceLocator)
 {
     _idIndex = new Dictionary<long, ICategory>();
     _nameIndex = new Dictionary<string, ICategory>();
     _labelIndex = new Trie<object>();
     _isAIndex = new Dictionary<long, List<long>>();
     _isAIndexInverse = new Dictionary<long, List<long>>();
 }
Exemplo n.º 20
0
        public void Setup()
        {
            _lastNames = SampleData.LastNames;
            _distinctCount = _lastNames.Distinct().Count();

            _trie = new Trie<string>();
            foreach (string lastName in _lastNames)
                _trie.Add(lastName, lastName);
        }
Exemplo n.º 21
0
        public void Add_KVP_NullItemIsAdded()
        {
            Trie<string, char, object> trie = new Trie<string, char, object>();

            trie.Add(new KeyValuePair<string, object>("key", null));

            Assert.AreEqual(1, trie.Count);
            Assert.AreEqual(null, trie["key"]);
        }
Exemplo n.º 22
0
        public void Add_KVP_ItemIsAdded()
        {
            Trie<string, char, int> trie = new Trie<string, char, int>();

            trie.Add(new KeyValuePair<string, int>("key", 5));

            Assert.AreEqual(1, trie.Count);
            Assert.AreEqual(5, trie["key"]);
        }
Exemplo n.º 23
0
        public void Add_ItemIsAdded()
        {
            Trie<string, char, int> trie = new Trie<string, char, int>();

            trie.Add("key", 5);

            Assert.AreEqual(1, trie.Count);
            Assert.AreEqual(5, trie["key"]);
        }
Exemplo n.º 24
0
        public void Trie_TryGetValue_should_work()
        {
            var trie = new Trie<char, int>();
              trie.SetValue("foo", 42);

              int value;
              trie.TryGetValue("foo", out value).Should().BeTrue();
              value.Should().Be(42);
        }
Exemplo n.º 25
0
        public void GetTest_Null()
        {
            Trie dictioanry = new Trie();
            dictioanry.Add("a", 100);

            var result = dictioanry.Get("b");

            Assert.IsNull(result, "result must be null");
        }
Exemplo n.º 26
0
        public void GetTest_UpperCase()
        {
            Trie dictioanry = new Trie();
            dictioanry.Add("a", 100);

            var result = dictioanry.Get("A");

            Assert.IsNotNull(result, "did not found word");
            Assert.AreEqual(1, result.Count(), "Incorrect words count");
        }
Exemplo n.º 27
0
        public void TestAddNewItem()
        {
            Trie trie = new Trie();

            int actual = trie.add("test");
            int expected = 1;

            Assert.AreEqual(expected, actual,
                "expected 0 for adding new item");
        }
 private static Trie CreateTrie()
 {
     var trie = new Trie
         {
             {"/", new TrieNode("homes/1", "Home")},
             {"/about", new TrieNode("homes/1", "Home")},
             {"/article", new TrieNode("articles/1", "Article")}
         };
     return trie;
 }
Exemplo n.º 29
0
        public void TrieTests_Contains()
        {
            Trie<char> trie = new Trie<char>();

            trie.Insert("Hello");

            Assert.IsTrue(trie.Contains("Hello"));
            Assert.IsFalse(trie.Contains("Hell"));
            Assert.IsFalse(trie.Contains("Hellop"));
        }
Exemplo n.º 30
0
        public void AddRange()
        {
            const int Count = 10;

            var trie = new Trie<bool>();

            trie.AddRange(Enumerable.Range(0, Count).Select(i => new TrieEntry<bool>(i.ToString(), false)));

            Assert.AreEqual(Count, trie.Count);
        }
Exemplo n.º 31
0
        // Reads all the input from the console
        static void ReadInput()
        {
            // Read the basic info from the console
            solveMode = Console.ReadLine() == "1";
            string[] cf   = Console.ReadLine().Split();
            int      cols = int.Parse(cf[0]);
            int      rows = int.Parse(cf[1]);

            cf = Console.ReadLine().Split();
            int targetX = int.Parse(cf[0]);
            int targetY = int.Parse(cf[1]);

            // Initialize all the arrays as arrays of length 0
            vehicleNames    = new char[0];
            vehicleLengths  = new byte[0];
            vehicleStartPos = new byte[0];
            vehicleLocs     = new byte[0];
            numHorVec       = 0;
            byte vehicleId = 0;                    // Keeps track of how many vehicles we found so far

            string[] field = new string[rows + 1]; // Temporarily store the information we read from the console so we can scan it in two directions

            // Read out the rows of vehicles and scan for horizontal vehicles
            vehicleRows = new byte[rows][];
            for (byte i = 0; i < rows; i++)
            {
                vehicleRows[i] = new byte[0];
                field[i]       = Console.ReadLine() + ".";
                byte runStart = 0;
                char runChar  = '.';
                for (byte j = 0; j < field[i].Length; j++)
                {
                    if (field[i][j] != runChar)
                    {
                        if (runChar != '.' && j - runStart > 1)
                        {
                            vehicleNames = ArrayAdd(runChar, vehicleNames);
                            if (runChar == 'x')
                            {
                                targetVehicle = vehicleId;
                            }
                            vehicleLengths  = ArrayAdd((byte)(j - runStart), vehicleLengths);
                            vehicleStartPos = ArrayAdd(runStart, vehicleStartPos);
                            vehicleRows[i]  = ArrayAdd(vehicleId, vehicleRows[i]);
                            vehicleLocs     = ArrayAdd(i, vehicleLocs);
                            vehicleId++;
                            numHorVec++;
                        }

                        runStart = j;
                        runChar  = field[i][j];
                    }
                }
            }

            // Now, scan for vertical vehicles
            if (cols != field[0].Length - 1)
            {
                throw new Exception("This testcase is bad!");   // Shoud not happen.
            }
            field[rows] = new String('.', cols);
            vehicleCols = new byte[cols][];
            for (byte i = 0; i < cols; i++)
            {
                vehicleCols[i] = new byte[0];
                byte runStart = 0;
                char runChar  = '.';
                for (byte j = 0; j < rows + 1; j++)
                {
                    if (field[j][i] != runChar)
                    {
                        if (runChar != '.' && j - runStart > 1)
                        {
                            vehicleNames = ArrayAdd(runChar, vehicleNames);
                            if (runChar == 'x')
                            {
                                targetVehicle = vehicleId;
                            }
                            vehicleLengths  = ArrayAdd((byte)(j - runStart), vehicleLengths);
                            vehicleStartPos = ArrayAdd(runStart, vehicleStartPos);
                            vehicleCols[i]  = ArrayAdd(vehicleId, vehicleCols[i]);
                            vehicleLocs     = ArrayAdd(i, vehicleLocs);
                            vehicleId++;
                        }

                        runStart = j;
                        runChar  = field[j][i];
                    }
                }
            }

            // Initialize the trie root node
            if (numHorVec == 0)
            {
                visited = new Trie(rows - vehicleLengths[0] + 1);
            }
            else
            {
                visited = new Trie(cols - vehicleLengths[0] + 1);
            }

            // Figure out what the goal is.
            if (targetVehicle < numHorVec)
            {
                goal = targetX;
                if (vehicleLocs[targetVehicle] != targetY)
                {
                    throw new Exception("This testcase is bad!");   // Shoud not happen.
                }
            }
            else
            {
                goal = targetY;
                if (vehicleLocs[targetVehicle] != targetX)
                {
                    throw new Exception("This testcase is bad!");   // Shoud not happen.
                }
            }
        }
Exemplo n.º 32
0
    static void Main(string[] args)
    {
        const int  minArraySize        = 3;
        const int  maxArraySize        = 4;
        const int  setCount            = 10;
        const bool generateRandomInput = true;

        var trie         = new Trie(File.ReadAllLines(@"..\..\textFile.txt"));
        var watch        = new Stopwatch();
        var trials       = 10000;
        var wordCountSum = 0;
        var rand         = new Random(37);

        for (int t = 0; t < trials; t++)
        {
            HashSet <Letter>[] sets;

            if (generateRandomInput)
            {
                sets = new HashSet <Letter> [setCount];
                for (int i = 0; i < setCount; i++)
                {
                    sets[i] = new HashSet <Letter>();
                    var size = minArraySize + rand.Next(maxArraySize - minArraySize + 1);
                    while (sets[i].Count < size)
                    {
                        sets[i].Add(Letter.Chars[rand.Next(Letter.Chars.Length)]);
                    }
                }
            }
            else
            {
                sets = new HashSet <Letter>[] { new HashSet <Letter>(new Letter[] { 'P', 'Q', 'R', 'S' }),
                                                new HashSet <Letter>(new Letter[] { 'A', 'B', 'C' }),
                                                new HashSet <Letter>(new Letter[] { 'T', 'U', 'V' }),
                                                new HashSet <Letter>(new Letter[] { 'M', 'N', 'O' }) };

                watch.Start();

                var wordsFound = new List <string>();

                for (int i = 0; i < sets.Length - 1; i++)
                {
                    GenWords(trie.Root, sets, i, wordsFound);
                }

                watch.Stop();

                wordCountSum += wordsFound.Count;


                if (!generateRandomInput && t == 0)
                {
                    foreach (var word in wordsFound)
                    {
                        Console.WriteLine(word);
                    }
                }
            }

            Console.WriteLine("Elapsed per trial = {0}", new TimeSpan(watch.Elapsed.Ticks / trials));
            Console.WriteLine("Average word count per trial = {0:0.0}", (float)wordCountSum / trials);
        }
    }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            var root = new Trie();

            root.Insert("andrei");
        }
Exemplo n.º 34
0
        public void GetUnknownKeyValue()
        {
            Trie trie = new Trie();

            Assert.IsNull(trie.GetValue(new byte[] { 0x01, 0x02, 0x03 }));
        }
Exemplo n.º 35
0
        public void TestPutCantResolve()
        {
            var mpt = new Trie(mptdb.GetSnapshot(), root.Hash);

            Assert.ThrowsException <InvalidOperationException>(() => mpt.Put("acf111".HexToBytes(), new byte[] { 1 }));
        }
Exemplo n.º 36
0
    private static bool trieStartsWithMethodTest1()
    {
        Trie trie = new Trie();

        return(new Trie().GetType().GetMethod("startsWith") != null);
    }
Exemplo n.º 37
0
    private static bool trieIsWordMethodTest1()
    {
        Trie trie = new Trie();

        return(new Trie().GetType().GetMethod("isWord") != null);
    }
Exemplo n.º 38
0
        private bool ReplaceStrings(IText text, IDictionary <string, string> map, out string newText)
        {
            string        s       = text.Text;
            Trie <char>   lookup  = new Trie <char>(map.Keys);
            StringBuilder builder = new StringBuilder();
            int           lastIdx = -1;

            Trie <char> .Node lastNode = lookup.Root;
            int matchIdx = -1;
            HashSet <Trie <char> .Node> badMatches = new HashSet <Trie <char> .Node>();
            bool replaced = false;

            for (int i = 0; i < s.Length + 1; i++)
            {
                if (i < s.Length)
                {
                    char chr = s[i];
                    if (lastNode.HasNext(chr))
                    {
                        // Partial match
                        Trie <char> .Node matchNode = lastNode.Children[chr];
                        if (!badMatches.Contains(matchNode))
                        {
                            lastNode = matchNode;
                            if (matchIdx == -1)
                            {
                                matchIdx = i;
                            }
                            continue;
                        }
                    }
                }

                if (lastNode.IsRoot && CheckWordSeparators(s, matchIdx, i - 1))
                {
                    // Complete match
                    string key = new string(lastNode.Cumulative.ToArray());
                    builder.Append(map[key]);  // New replacement content shouldn't be HTML encoded because it contains HTML like <a>
                    replaced = true;
                    i        = i - 1;
                    lastIdx  = i;
                }
                else
                {
                    // No match
                    if (matchIdx != -1)
                    {
                        // Backtrack to the last match start and don't consider this match
                        i        = matchIdx - 1;
                        matchIdx = -1;
                        badMatches.Add(lastNode);
                        lastNode = lookup.Root;
                        continue;
                    }

                    // Existing text content needs to be encoded since it was part of a text node
                    builder.Append(WebUtility.HtmlEncode(i < s.Length
                        ? s.Substring(lastIdx + 1, i - lastIdx)
                        : s.Substring(lastIdx + 1)));
                    lastIdx = i;
                }
                badMatches.Clear();
                matchIdx = -1;
                lastNode = lookup.Root;
            }

            newText = replaced ? builder.ToString() : string.Empty;

            return(replaced);
        }
Exemplo n.º 39
0
    /** Returns if the word is in the trie. */
    public bool Search(string word)
    {
        Trie node = searchPrefix(word);

        return(node != null && node.isEnd);
    }
Exemplo n.º 40
0
 public IntTrieTest(NodeContainerType ContainerType, int Count, int MinLength, int MaxLength, int DistinctValues)
     : base(ContainerType, Count, MinLength, MaxLength, DistinctValues)
 {
     intTrie          = new Trie <int[], int, int>(ContainerType);
     intTrie.WildCard = -999;
 }
Exemplo n.º 41
0
    private static bool trieClassTest3()
    {
        Trie trie = new Trie();

        return(trie.root.GetType() == typeof(TrieNode));
    }
Exemplo n.º 42
0
        public void TestTrie()
        {
            Trie <char, string> wordIndex = new Trie <char, string>(new LettersDomain());

            wordIndex.Add("a", "a");
            wordIndex.Add("aa", "aa");
            wordIndex.Add("ab", "ab");
            wordIndex.Add("ab", "ab2");
            wordIndex.Add("abc", "abc");
            wordIndex.Add("b", "b");
            wordIndex.Add("ba", "ba");
            wordIndex.Add("ba", "ba2");
            wordIndex.Add("ba", "ba3");
            wordIndex.Add("ba", "ba4");
            wordIndex.Add("c", "c");
            wordIndex.Add("cd", "cd");

            int max;

            //PrintTreeRecursive(wordIndex.root, -1, "");
            //Console.WriteLine(" -------------------------------- ");

            //ITrieEnumerator<char, IList<string>> iterator = wordIndex.All1;

            //Console.WriteLine(" MoveNext: -------------------------------- ");

            //while (iterator.MoveNext())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            //Console.WriteLine(" MovePrevious: -------------------------------- ");

            //while (iterator.MovePrevious())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            //Console.WriteLine(" MoveNext: -------------------------------- ");

            //while (iterator.MoveNext())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            //Console.WriteLine(" MovePrevious: -------------------------------- ");

            //int max = 6;
            //while (--max > 0 && iterator.MovePrevious())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            //Console.WriteLine(" MoveNext: -------------------------------- ");

            //max = 4;
            //while (--max > 0 && iterator.MoveNext())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            //Console.WriteLine(" MovePrevious: -------------------------------- ");

            //max = 5;
            //while (--max > 0 && iterator.MovePrevious())
            //{
            //    Console.WriteLine("{0}: {1}", new string(new List<char>(iterator.Current.Key).ToArray()), iterator.Current.Value[0]);
            //}

            Console.WriteLine(" -------------------------------- ");
            Console.WriteLine(" -------------------------------- ");

            ITrieEnumerator <char, string> iterator2 = wordIndex.All;

            while (iterator2.MoveNext())
            {
                Console.WriteLine(iterator2.Current.Value);
            }

            Console.WriteLine(" -------------------------------- ");

            while (iterator2.MovePrevious())
            {
                Console.WriteLine(iterator2.Current.Value);
            }

            Console.WriteLine(" -------------------------------- ");

            while (iterator2.MoveNext())
            {
                Console.WriteLine(iterator2.Current.Value);
            }

            Console.WriteLine(" -------------------------------- ");

            max = 6;
            while (--max > 0 && iterator2.MovePrevious())
            {
                Console.WriteLine(iterator2.Current.Value);
            }

            Console.WriteLine(" MoveNext: -------------------------------- ");

            max = 4;
            while (--max > 0 && iterator2.MoveNext())
            {
                Console.WriteLine(iterator2.Current.Value);
            }

            Console.WriteLine(" MovePrevious: -------------------------------- ");

            max = 5;
            while (--max > 0 && iterator2.MovePrevious())
            {
                Console.WriteLine(iterator2.Current.Value);
            }
        }
Exemplo n.º 43
0
    private static bool trieInsertMethodTest1()
    {
        Trie trie = new Trie();

        return(new Trie().GetType().GetMethod("insert") != null);
    }
Exemplo n.º 44
0
        private static Trie CreateRomajiToKanaMap()
        {
            string[] GetAlternatives(string input)
            {
                var results = new List <string>();

                foreach (var alias in Aliases.Union(new[] { new KeyValuePair <string, string>("c", "k") }))
                {
                    var alt  = alias.Key;
                    var roma = alias.Value;
                    if (input.StartsWith(roma))
                    {
                        results.Add(input.Replace(roma, alt));
                    }
                }
                return(results.ToArray());
            }

            var kanaTree = Trie.FromDictionary(BasicKunrei);

            foreach (var consonantPair in Consonants)
            {
                var consonant = consonantPair.Key;
                var yKana     = consonantPair.Value;
                foreach (var smallY in SmallY)
                {
                    var roma = smallY.Key;
                    var kana = smallY.Value;

                    // for example kyo -> き + ょ
                    kanaTree[consonant + roma] = yKana + kana;
                }
            }

            foreach (var symbolPair in SpecialSymbols)
            {
                kanaTree[symbolPair.Key.ToString()] = symbolPair.Value.ToString();
            }

            // things like うぃ, くぃ, etc.
            foreach (var aiueoPair in AiueoConstructions)
            {
                var consonant = aiueoPair.Key;
                var aiueoKana = aiueoPair.Value;
                foreach (var vowelPair in SmallVowels)
                {
                    var vowel = vowelPair.Key;
                    var kana  = vowelPair.Value;
                    kanaTree[consonant + vowel] = aiueoKana + kana;
                }
            }

            // different ways to write ん
            foreach (var nChar in new[] { "n", "n'", "xn" })
            {
                kanaTree[nChar] = "ん";
            }

            // c is equivalent to k, but not for chi, cha, etc. that's why we have to make a copy of k
            kanaTree.InsertSubtrie("c", kanaTree.GetSubtrie("k").Clone());

            foreach (var aliasPair in Aliases)
            {
                var source = aliasPair.Key;
                var alias  = aliasPair.Value;

                var cut        = source.Substring(0, source.Length - 1);
                var last       = source[source.Length - 1];
                var parentTree = kanaTree.GetSubtrie(cut);
                parentTree.AssignSubtrie(last.ToString(), kanaTree.GetSubtrie(alias).Clone());
            }

            foreach (var smallLetterPair in SmallLetters)
            {
                var kunreiRoma = smallLetterPair.Key;
                var kana       = smallLetterPair.Value;
                var xRoma      = $"x{kunreiRoma}";
                var xSubtree   = kanaTree.GetSubtrie(xRoma);
                xSubtree.Root.Value = kana;

                // ltu -> xtu -> っ
                var parentTree = kanaTree.GetSubtrie($"l{kunreiRoma.Substring(0, kunreiRoma.Length - 1)}");
                parentTree.AssignSubtrie(kunreiRoma[kunreiRoma.Length - 1].ToString(), xSubtree);

                // ltsu -> ltu -> っ
                var alternatives = GetAlternatives(kunreiRoma);
                foreach (var alternative in alternatives)
                {
                    foreach (var prefix in new char[] { 'l', 'x' })
                    {
                        var altParentTree = kanaTree.GetSubtrie(prefix + alternative.Substring(0, alternative.Length - 1));
                        altParentTree.AssignSubtrie(alternative[alternative.Length - 1].ToString(), kanaTree.GetSubtrie(prefix + kunreiRoma));
                    }
                }
            }

            foreach (var specialCase in SpecialCases)
            {
                kanaTree[specialCase.Key] = specialCase.Value;
            }

            Trie AddTsu(Trie tree)
            {
                var tsuTrie = new Trie();

                foreach (var entry in tree.GetEntries())
                {
                    // we have reached the bottom of this branch
                    tsuTrie[entry.Key] = $"っ{entry.Value}";
                }
                return(tsuTrie);
            }

            // have to explicitly name c here, because we made it a copy of k, not a reference
            foreach (var consonant in Consonants.Keys.Union(new[] { 'c', 'y', 'w', 'j' }))
            {
                var subtree = kanaTree.GetSubtrie(consonant.ToString());
                subtree.InsertSubtrie(consonant.ToString(), AddTsu(subtree));
            }

            // nn should not be っん
            kanaTree.GetSubtrie("n").Root.DeleteChild('n');

            return(kanaTree);
        }
Exemplo n.º 45
0
    private static bool trieIsWordMethodTest2()
    {
        Trie trie = new Trie();

        return(trie.isWord("") == false);
    }
Exemplo n.º 46
0
 public TrieInsert(Trie <Partition> trie)
 {
     _trie = trie;
 }
Exemplo n.º 47
0
    private static bool trieRemoveMethodTest1()
    {
        Trie trie = new Trie();

        return(new Trie().GetType().GetMethod("remove") != null);
    }
Exemplo n.º 48
0
        public void TestTryGetResolve()
        {
            var mpt = new Trie(mptdb.GetSnapshot(), root.Hash);

            Assert.AreEqual(Encoding.ASCII.GetBytes("existing").ToHexString(), mpt["acae".HexToBytes()].ToHexString());
        }
Exemplo n.º 49
0
 internal static void ApplyImeModeMap(Trie trie)
 {
     // in IME mode, we do not want to convert single ns
     trie["nn"] = "ん";
     trie["n "] = "ん";
 }
Exemplo n.º 50
0
 public static string ToKana(string input, bool useObsoleteKana, Trie <char, string> customKanaMapping)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 51
0
 public StateSnapshot(IStore store)
 {
     snapshot = store.GetSnapshot();
     Trie     = new Trie <StorageKey, StorageItem>(snapshot, CurrentLocalRootHash(), Settings.Default.FullState);
 }
Exemplo n.º 52
0
 public TrieWalker(Trie <TKey, TValue> trie)
 {
     _trie        = trie;
     _CurrentNode = _trie;
 }
Exemplo n.º 53
0
        private bool ReplaceStrings(IText text, IDictionary <string, string> map, out string newText)
        {
            string        s       = text.Text;
            Trie <char>   lookup  = new Trie <char>(map.Keys);
            StringBuilder builder = new StringBuilder();
            int           lastIdx = -1;

            Trie <char> .Node lastNode = lookup.Root;
            int matchIdx = -1;
            HashSet <Trie <char> .Node> badMatches = new HashSet <Trie <char> .Node>();
            bool replaced = false;

            for (int i = 0; i < s.Length + 1; i++)
            {
                if (i < s.Length)
                {
                    char chr = s[i];
                    if (lastNode.HasNext(chr))
                    {
                        // Partial match
                        Trie <char> .Node matchNode = lastNode.Children[chr];
                        if (!badMatches.Contains(matchNode))
                        {
                            lastNode = matchNode;
                            if (matchIdx == -1)
                            {
                                matchIdx = i;
                            }
                            continue;
                        }
                    }
                }

                if (lastNode.IsRoot && CheckAdditonalConditions(s, matchIdx, i - 1))
                {
                    // Complete match
                    string key = new string(lastNode.Cumulative.ToArray());
                    builder.Append(map[key]);
                    replaced = true;
                    i        = i - 1;
                    lastIdx  = i;
                }
                else
                {
                    // No match
                    if (matchIdx != -1)
                    {
                        // Backtrack to the last match start and don't consider this match
                        i        = matchIdx - 1;
                        matchIdx = -1;
                        badMatches.Add(lastNode);
                        lastNode = lookup.Root;
                        continue;
                    }
                    builder.Append(i < s.Length ? s.Substring(lastIdx + 1, i - lastIdx) : s.Substring(lastIdx + 1));
                    lastIdx = i;
                }
                badMatches.Clear();
                matchIdx = -1;
                lastNode = lookup.Root;
            }
            newText = replaced ? builder.ToString() : string.Empty;
            return(replaced);
        }
 /** Initialize your data structure here. */
 public WordDictionary()
 {
     root = new Trie();
 }
Exemplo n.º 55
0
 public TrieEntityTypeSelectorFactory(int position)
 {
     _position    = position;
     _entityTypes = new Trie <EntityType>();
 }
Exemplo n.º 56
0
    private static bool trieClassTest1()
    {
        Trie trie = new Trie();

        return(trie.GetType() == typeof(Trie));
    }
Exemplo n.º 57
0
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public bool StartsWith(string prefix)
    {
        Trie node = searchPrefix(prefix);

        return(node != null);
    }
Exemplo n.º 58
0
        public void Find_GivenNullString_ThrowsException()
        {
            var trie = new Trie();

            Assert.Throws <NullReferenceException>(() => trie.Find(null));
        }
Exemplo n.º 59
0
 [Test] public void Test_Dictionary()
 {
     Trie t = data();
     // TODO: test dictionary enumerator.
 }
Exemplo n.º 60
0
        [Test] public void Test_Type()
        {
            Trie t = new Trie();

            Assert.AreEqual("bedrock.collections.Trie", t.GetType().FullName);
        }