public static void Run() { string[] strings = new string[] { "AAGGG", "ACTTT", "AGGCT", "GCCAC", "TCCGC" }; PrefixTree tree = new PrefixTree(strings); tree.PrintTree(); }
public void AddTwoChildrenTest() { var tree = new PrefixTree("978", 3, "International ISBN Agency", new[] { new RangeRule(0, 4, 1), new RangeRule(11, 22, 2) }); //First child bool addResult = tree.AddChild("0", 1, "English language", new[] { new RangeRule(00, 12, 2), new RangeRule(229, 368, 3) }); addResult.Should().BeTrue(); //Second child addResult = tree.AddChild("1", 1, "English language", new[] { new RangeRule(000, 009, 3), //TODO: Check this range new RangeRule(01, 06, 2) }); addResult.Should().BeTrue(); }
DefaultWordDictionary() { Dictionary = new PrefixTree<PhraseSequence>( DictionaryData.Instance.Entries .Select(e => new PhraseSequence(new PhraseSequenceElement(e.ID, 0))) ); }
public void GivenString_Put_ShoulGeneratePrefixTree() { var tree = new PrefixTree(new TrieTreeNode()); bool result = tree.Insert("apple"); Assert.IsTrue(result); }
public void PrefixTree_ExactMatch() { PrefixTree tree = new PrefixTree(); tree.Insert("PATRIK"); Assert.IsFalse(tree.IsExactMatch("PAT")); Assert.IsTrue(tree.IsExactMatch("PATRIK")); }
public void PrefixTree_ExactMatchWorksWithWrongCase() { PrefixTree tree = new PrefixTree(); tree.Insert("PATRIK"); Assert.IsFalse(tree.IsExactMatch("pat")); Assert.IsTrue(tree.IsExactMatch("patrik")); }
public void GivenValidInputString_StartWith_ShouldReturnTrue() { var tree = new PrefixTree(new TrieTreeNode()); tree.Insert("apple"); var result = tree.StartWith("app"); Assert.IsTrue(result); }
public void GivenString_Get_ShouldReturnTrue() { var tree = new PrefixTree(new TrieTreeNode()); tree.Insert("apple"); var result = tree.Search("apple"); Assert.IsTrue(result); }
public void GivenValidInputStringButInvalidSearch_Search_ShouldReturnFalse() { var tree = new PrefixTree(new TrieTreeNode()); tree.Insert("apple"); var result = tree.Search("app"); Assert.IsFalse(result); }
public void PrefixTree_CountMatchesNumberOfWordsInTree() { PrefixTree tree = new PrefixTree(); tree.Insert("CART"); tree.Insert("DINO"); tree.Insert("TAR"); tree.Insert("PEN"); Assert.AreEqual(4, tree.Count); }
public void PrefixTree_PartialMatchWorksWithWrongCase() { PrefixTree tree = new PrefixTree(); tree.Insert("PATRIK"); Assert.IsTrue(tree.IsPartialMatch("p")); Assert.IsTrue(tree.IsPartialMatch("pat")); Assert.IsFalse(tree.IsPartialMatch("pad")); Assert.IsFalse(tree.IsPartialMatch("t")); }
/// <summary> /// Encrypts the specified message. /// </summary> /// <param name="message">The message.</param> /// <returns>An encrypted string</returns> public string Encrypt(string message) { this.Initialize(); foreach (var c in message) { if (!this.blockTree.Nodes.ContainsKey(c)) { throw new ArgumentException(string.Format("Character {0} is not in the alphabet.", c)); } } StringBuilder result = new StringBuilder(); string remaining = message; while (remaining.Length > 0) { // Find the next new block in the block tree int currentIndex = 0; PrefixTree currentNode = this.blockTree; while (currentIndex < remaining.Length && currentNode.Nodes.ContainsKey(remaining[currentIndex])) { currentNode = currentNode.Nodes[remaining[currentIndex]]; ++currentIndex; } // Add the next encrypted block to the result result.Append(currentNode.Number.ToString().PadLeft(this.blockCodeSize, '0')); // Check if new block has been found if (currentIndex <= remaining.Length - 1) { if (!currentNode.Nodes.ContainsKey(remaining[currentIndex])) { // Add new block to the table PrefixTree newNode = this.nodePool.GetNode(); newNode.Number = this.nextBlockIndex++; currentNode.Nodes[remaining[currentIndex]] = newNode; // Update current block length if ((this.nextBlockIndex - 1).ToString().Length > this.blockCodeSize) { ++this.blockCodeSize; } } } // Update remaining part of the message remaining = remaining.Substring(currentIndex); } return(result.ToString()); }
// END CUT HERE // BEGIN CUT HERE public static void Main() { PrefixTree ___test = new PrefixTree(); ___test.run_test(-1); try { } catch (Exception e) { //Console.WriteLine(e.StackTrace); Console.WriteLine(e.ToString()); } }
/// <summary> /// Заполняет префиксное дерево из базы данных. /// </summary> /// <param name="prefixTree"></param> public void FillPrefixTree(ref PrefixTree prefixTree) { using (var context = new MyDbContext()) { List <string> itemsIncome = context.Incomes.Select(x => x.Name).ToList(); foreach (string item in itemsIncome) { prefixTree.Add(item); } } }
// END CUT HERE // BEGIN CUT HERE public static void Main() { PrefixTree ___test = new PrefixTree(); ___test.run_test(-1); try { } catch(Exception e) { //Console.WriteLine(e.StackTrace); Console.WriteLine(e.ToString()); } }
public void PrefixTree_PartialMatch() { PrefixTree tree = new PrefixTree(); tree.Insert("PATRIK"); Assert.IsTrue(tree.IsPartialMatch("P")); Assert.IsTrue(tree.IsPartialMatch("PAT")); Assert.IsFalse(tree.IsPartialMatch("PAD")); Assert.IsFalse(tree.IsPartialMatch("T")); Assert.IsFalse(tree.IsPartialMatch("")); }
// Constructor public MainPage() { InitializeComponent(); // PrefixTree takes a few seconds to create, so do it here dictionary = new PrefixTree(); dictionary.CreateDictionaryHash(); gb = new GameBoard(); gb.Roll(); }
/// <summary> /// Initializes a new instance of the <see cref="NodePool"/> class. /// </summary> /// <param name="capacity">The initial capacity.</param> public NodePool(int capacity) { this.nodePool = new List <PrefixTree>(capacity); for (int i = 0; i < this.nodePool.Capacity; ++i) { PrefixTree node = new PrefixTree(); node.Nodes = new Dictionary <char, PrefixTree>(); this.nodePool.Add(node); } this.nextFreeNode = 0; }
public void TestMethod4() { PrefixTree T = new PrefixTree(); T.AddValue("abracadabra"); T.AddValue("abbar"); T.AddValue("abce"); T.AddValue("sort"); T.AddValue("sortset"); bool b = T.ContainsValue("set"); Assert.AreEqual(b, false); }
public void SearchReturnsAllAvailableSubset(string searchString, string[] expected) { var trie = new PrefixTree(); foreach (string word in MemoryDictionary) { trie.Add(word); } var results = trie.Search(searchString); Assert.IsFalse(results.Except(expected).Any()); Assert.IsFalse(expected.Except(results).Any()); }
static void Main(string[] args) { PrefixTree T = new PrefixTree(); T.AddValue("abracadabra"); T.AddValue("abbar"); T.AddValue("abce"); T.AddValue("sort"); T.AddValue("sortset"); T.PrintAll(); //Console.WriteLine(p.ContainsValue("abba")); //Console.WriteLine(p.ContainsValue("ababacab")); Console.ReadKey(); }
public async Task TestTreeAddWithSingleCharStringTerm() { // Arrange var items = new[] { "A" }; var tree = new PrefixTree(); var expected = items; // Act tree.Add(items); var actual = await tree.FindAsync(string.Empty); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
/// <summary> /// Initializes the prefix tree. /// </summary> private void Initialize() { this.nodePool.Reset(); this.nextBlockIndex = 0; this.blockTree = this.nodePool.GetNode(); for (int i = 0; i < this.alphabet.Length; i++) { PrefixTree node = this.nodePool.GetNode(); node.Number = this.nextBlockIndex++; this.blockTree.Nodes.Add(this.alphabet[i], node); } this.blockCodeSize = this.alphabet.Length > 0 ? (this.alphabet.Length - 1).ToString().Length : 0; }
public async Task TestGetItemsWithSingleCharAndMultipleBranches() { // Arrange var items = new[] { "ABCD", "AdCE" }; var tree = new PrefixTree(); tree.Add(items); var expected = items; // Act var actual =await tree.FindAsync("A"); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Count(x => actual.Contains(x.ToUpper()))); }
public async Task TestTreeAddWithMultipleItemsStartedWithSamePrefix() { // Arrange var items = new[] { "AbC", "ABcD" }; var tree = new PrefixTree(); var expected = items; // Act tree.Add(items); var actual =await tree.FindAsync(string.Empty); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Count(x => actual.Contains(x.ToUpper()))); }
public PrefixTreeTests() { _treeUnderTest = new PrefixTree( "978", 3, "International ISBN Agency", new[] { new RangeRule(0, 4, 1), new RangeRule(11, 22, 2) }); _treeUnderTest.AddChild("0", 1, "English language", new[] { new RangeRule(00, 12, 2), new RangeRule(229, 368, 3) }); }
/// <summary> /// Returns the next free node. /// </summary> /// <returns>A free node</returns> public PrefixTree GetNode() { if (this.nextFreeNode >= this.nodePool.Capacity) { this.nodePool.Capacity *= 2; for (int i = this.nodePool.Count; i < this.nodePool.Capacity; ++i) { PrefixTree node = new PrefixTree(); node.Nodes = new Dictionary <char, PrefixTree>(); this.nodePool.Add(node); } } this.nodePool[this.nextFreeNode].Number = 0; this.nodePool[this.nextFreeNode].Nodes.Clear(); return(this.nodePool[this.nextFreeNode++]); }
public void AddChildTest() { var tree = new PrefixTree("978", 3, "International ISBN Agency", new[] { new RangeRule(0, 4, 1), new RangeRule(11, 22, 2) }); bool addResult = tree.AddChild("0", 1, "English language", new[] { new RangeRule(00, 12, 2), new RangeRule(229, 368, 3) }); addResult.Should().BeTrue(); }
public void TestMethod2() { PrefixTree T = new PrefixTree(); T.AddValue("abracadabra"); T.AddValue("abbar"); T.AddValue("abce"); T.AddValue("sort"); T.AddValue("sortset"); T.Remove("sort"); T.Remove("abce"); List <string> res = new List <string>(); T.AllToList(ref res); List <string> trueAnswer = new List <string>(); trueAnswer.Add("abbar"); trueAnswer.Add("abracadabra"); trueAnswer.Add("sortset"); CollectionAssert.AreEqual(res, trueAnswer); }
public PrefixTree Build() { PrefixTree tree = new PrefixTree(); string[] lines = File.ReadAllLines(_file.FullName); foreach (string line in lines) { if (line.StartsWith("CUSTOM") || line.StartsWith("BASEWORDS") || line.StartsWith("DEFINITION")) { continue; } else if (line.StartsWith("COMPOUND")) { string[] parts = line.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { string[] words = parts[1].Split(new char[] { '+' }, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { string temp = word.Trim(); tree.Insert(temp); } } } else { string[] parts = line.Split(new char[] { '>' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { string[] words = parts[1].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); foreach (string word in words) { tree.Insert(word); } } } } return tree; }
// Constructor public MainPage() { InitializeComponent(); // PrefixTree takes a few seconds to create, so do it here dictionary = new PrefixTree(); dictionary.CreateDictionaryHash(); const bool runUnitTests = true; if (runUnitTests) { Content = UnitTestSystem.CreateTestPage(); IMobileTestPage imtp = Content as IMobileTestPage; if (imtp != null) { BackKeyPress += (x, xe) => xe.Cancel = imtp.NavigateBack(); } } }
public InputMapper() { Root = new PrefixTree <char, Func <ArraySegment <char>, int> >((char)0); }
void Awake() { dictionary = DefaultWordDictionary.Instance.Dictionary; }
public WordFilter(string[] words) { prefixTree = new PrefixTree(10, words); suffixTree = new PrefixTree(10, words, true); }
public async Task TestGetItemsWithFullTerm() { // Arrange var items = new[] { "ABC" }; var tree = new PrefixTree(); tree.Add(items); var expected = items; // Act var actual =await tree.FindAsync("ABC"); // Assert Assert.IsNotNull(actual); Assert.AreEqual(expected.Count(), expected.Where(actual.Contains).Count()); }
public void TestAddNullThrowsException() { // Arrange var items = new[] { "as", null, "daf" }; var tree = new PrefixTree(); // Act tree.Add(items); }
public async Task TestFindNullThrowsException() { // Arrange var items = new[] { "ABF", "ABE" }; var tree = new PrefixTree(); tree.Add(items); // Act await tree.FindAsync(null); }
public void SetUp() { _tree = new PrefixTree(); }
public static IReadOnlyDictionary <string, PrefixTree> BuildFromISBNRangeMessage(ISBNRangeMessage isbnRangeMessage) { if (isbnRangeMessage == null) { throw new ArgumentNullException(nameof(isbnRangeMessage)); } if (isbnRangeMessage.EAN_UCCPrefixes?.EAN_UCC == null) { throw new ArgumentException("EAN_UCC is null in message.", nameof(isbnRangeMessage)); } var rootPrefixTrees = new Dictionary <string, PrefixTree>(2, StringComparer.Ordinal); foreach (var eanUcc in isbnRangeMessage.EAN_UCCPrefixes.EAN_UCC) { if (eanUcc.Rules?.Rule == null) { continue; } var mainRangeRules = new List <RangeRule>(eanUcc.Rules.Rule.Count); foreach (var rule in eanUcc.Rules.Rule) { var numberOfDigits = rule.Length; if (numberOfDigits > 0) { var ranges = rule.Range.Split('-', StringSplitOptions.RemoveEmptyEntries); var from = int.Parse(ranges[0].Substring(0, numberOfDigits)); var to = int.Parse(ranges[1].Substring(0, numberOfDigits)); mainRangeRules.Add(new RangeRule(@from, to, numberOfDigits)); } } var mainPrefix = eanUcc.Prefix; var prefixTree = new PrefixTree( mainPrefix, eanUcc.Prefix.Length, eanUcc.Agency, mainRangeRules); rootPrefixTrees.Add(mainPrefix, prefixTree); } if (rootPrefixTrees.Count == 0) { throw new ArgumentException("Invalid data, the message does not contain any UCCPrefixes.", nameof(isbnRangeMessage)); } var allGroups = isbnRangeMessage.RegistrationGroups?.Group; if (allGroups == null) { return(rootPrefixTrees); } for (var i = 0; i < allGroups.Count; i++) { var currentGroup = allGroups[i]; var groupPrefixes = currentGroup.Prefix.Split('-', StringSplitOptions.RemoveEmptyEntries); var parentPrefixStr = groupPrefixes[0]; var groupPrefixStr = groupPrefixes[1]; if (currentGroup.Rules?.Rule == null) { continue; } var groupRules = new List <RangeRule>(currentGroup.Rules.Rule.Count); foreach (var rule in currentGroup.Rules.Rule) { var numberOfDigits = rule.Length; if (numberOfDigits > 0) { var ranges = rule.Range.Split('-', StringSplitOptions.RemoveEmptyEntries); var from = int.Parse(ranges[0].Substring(0, numberOfDigits)); var to = int.Parse(ranges[1].Substring(0, numberOfDigits)); var rangeRule = new RangeRule(@from, to, numberOfDigits); groupRules.Add(rangeRule); } } if (groupRules.Count > 0) { if (!rootPrefixTrees[parentPrefixStr].AddChild(groupPrefixStr, groupPrefixStr.Length, currentGroup.Agency, groupRules)) { throw new InvalidDataException( $"Could not add child {groupPrefixStr} to root {parentPrefixStr}."); } } } return(rootPrefixTrees); }
public void PrefixTree_WordsAreInsertedAsLowercase() { PrefixTree tree = new PrefixTree(); tree.Insert("CART"); tree.Insert("DINO"); tree.Insert("TAR"); tree.Insert("PEN"); Assert.IsNotNull(tree.Root.FindNode('c')); }