Exemple #1
0
	/**
	 * Enlarge cubical "box", salvaging existing tree structure.
	 *
	 * @param tree   the root of the tree.
	 * @param nsteps the current time step
	 */
	public void expandBox(BTree tree, int nsteps)
	{
		MathVector rmid = MathVector.makeMathVector();

		int k;
		bool inbox = icTest(tree);
		while(!inbox)
		{
			double rsize = tree.rsize;
			rmid.addScalar(tree.rmin, 0.5 * rsize);

			for(k = 0; k < MathVector.NDIM; k++)
			{
				if(pos.value(k) < rmid.value(k))
				{
					double rmin = tree.rmin.value(k);
					tree.rmin.setValue(k, rmin - rsize);
				}
			}
			tree.rsize = 2.0 * rsize;
			if(tree.root != null)
			{
				MathVector ic = tree.intcoord(rmid);
				k = Node.oldSubindex(ic, Node.IMAX >> 1);
				Cell newt = Cell.makeCell();
				newt.subp[k] = tree.root;
				tree.root = newt;
				inbox = icTest(tree);
			}
		}
	}
Exemple #2
0
        public void CanSearchForValueInTree()
        {
            var tree = new BTree<string>(5);
            tree.Insert("/usr0/actors/DanielCraig");
            tree.Insert("/usr0/writers/AlistairMacLean");
            tree.Insert("/usr0/superheroes/Xavier");
            tree.Insert("/usr0/heroes/Vendetta");
            tree.Insert("/usr0/actors/HumphryBogart");
            tree.Insert("/usr0/scientists/MichaelFaraday");
            tree.Insert("/usr0/actors/Armorer");
            tree.Insert("/usr0/philosophers/Aristotle");
            tree.Insert("/usr0/superheroes/BruceWayne");
            tree.Insert("/usr0/worlds/Hyrule");
            tree.Insert("/usr0/mmo/Ettenmoor");
            tree.Insert("/usr0/diseases/Dengue");
            tree.Insert("/usr0/listerature/Jekyll");
            tree.Insert("/usr0/random/Koralos");
            tree.Insert("/usr0/scientists/Lagrange");
            tree.Insert("/usr0/random/Nurf");
            tree.Insert("/usr0/mammals/Orca");
            tree.Insert("/usr0/mythicals/Werewolf");
            tree.Insert("/usr0/places/Cheydinhal");
            tree.Insert("/usr0/compilers/ClangCompiler");
            tree.Insert("/usr0/places/DeepSea");
            tree.Insert("/usr0/places/Clyde");
            tree.Insert("/usr0/places/Clydesdale");

            Console.Out.WriteLine(tree);
            BTreeNodeElement<string> element = tree.Search("/usr0/places/Clyde");
            Console.Out.WriteLine("Found:" + element.Value);
        }
Exemple #3
0
        public void Add(bool optimize, params IComparable[] values)
        {
            if (this.Values.Length != values.Length) throw new Exception("To less values to add, this DB needs " + this.Values.Length);

            if (Values[0][level].Count == int.MaxValue) {
                if (level == int.MaxValue) throw new Exception("There's no more space left in this DB!");
                else level++;
                for (int i = 0; i < Values.Length; i++) {
                    Values[i].Add(new List<IComparable>());
                    Indices.Add(new List<DBIndex>());
                }
            }
            Indices[level].Add(new DBIndex(level, Values[0][level].Count));
            if (!hasroot) {
                for (int i = 0; i < Trees.Length; i++) {
                    Trees[i] = new BTree<IComparable>(ref Values[i], Indices[level][Indices[level].Count - 1]);
                }
                hasroot = true;
            }
            else {
                for (int i = 0; i < values.Length; i++) {
                    Values[i][level].Add(values[i]);
                    Trees[i].Add(Indices[level][Indices[level].Count - 1], optimize);
                }
            }
        }
Exemple #4
0
        public static void exampleTests()
        {
            BTree<string> T1 = new BTree<string>();
            T1.Add("programming");  T1.Add("languages");
            T1.Add("provide");      T1.Add("lots");
            T1.Add("opportunity");  T1.Add("for");
            T1.Add("mistakes");

            string[] arr = new string[10];
            T1.CopyTo(arr, 0);

            BTree<string> T2 = new BTree<string>();
            T2.Add("pg"); T2.Add("lg");
            T2.Add("asdf"); T2.Add("l");

            BTree<string> asdf = T1 + T2;
            asdf.ToString();
            IEnumerator<string> e = T1.GetEnumerator();
            while (e.MoveNext())
                Console.WriteLine(e.Current);
            e.Reset();
            while (e.MoveNext())
                Console.WriteLine(e.Current);

            Console.WriteLine(T1.ToString());

            T1.Remove("languages");
        }
Exemple #5
0
        static void RunBTree()
        {
            try
            {
                BTree<Number> tree0 = new BTree<Number>();
                tree0.Add(new Number(5));
                tree0.Add(new Number(3));
                tree0.Add(new Number(2));
                tree0.Add(new Number(4));
                tree0.Add(new Number(6));
            }
            catch (ComparationException e) { Console.WriteLine(e.Message); }

            BTree<int> tree = new BTree<int>();

            tree.Add(5);
            tree.Add(3);
            tree.Add(2);
            tree.Add(4);
            tree.Add(6);

            foreach (int i in tree) Console.Write(i + " ");
            Console.WriteLine();
            tree.TraverseOrder = BTree<int>.Order.INORDER;
            foreach (int i in tree) Console.Write(i + " ");
            Console.WriteLine();
            tree.TraverseOrder = BTree<int>.Order.POSTODER;
            foreach (int i in tree) Console.Write(i + " ");
            Console.WriteLine();
        }
        //File manipulators
        public static string createBinTreeFile(BTree<int, sTweet> Tree, TreeIndexCheck check)
        {
            string filePath;
            string startDir = Directory.GetCurrentDirectory();
            string currentDir = startDir + @"\Searches\";

            if(!Directory.Exists(currentDir))
                Directory.CreateDirectory(currentDir);
            Directory.SetCurrentDirectory(currentDir);

            BinaryFormatter bf = new BinaryFormatter();
            byte[] buffer;
            using(var ms = new MemoryStream())
            {
                bf.Serialize(ms, Tree);
                buffer = ms.ToArray();
            }

            filePath = String.Format("indexedTweets.bin");
            using(BinaryWriter newFile = new BinaryWriter(File.Open(filePath, FileMode.Create)))
            {
                newFile.Write(buffer, 0, buffer.Length);
                newFile.Close();
            }

            Directory.SetCurrentDirectory(startDir);
            SaveTreeIndex(check.index, check.height, check.degree);

            return currentDir + filePath;
        }
    // *** end of global SYN and SEM declarations from ATG ***
    private static void NT_BinaryTree()
    {
        for (;;) {
          switch (Syn.Interpret()) {
        case 0:
          return;
        case 1: // SEM
          tree = new BTree();

          break;
        case 2:
          NT_SubTree(ref tree);
          break;
        case 3: // SEM
          Console.WriteLine("Tree:");
          			Console.Write("(");
          			if (tree.HasBeenAssigned()) {
          				Console.Write(tree);
          			}
          			Console.WriteLine(")");

          break;
          } // switch
        } // for
    }
 void OnGUI()
 {
     if(GUI.Button(new Rect(0,0,100,40),"load"))
     {
         BTreeMgr.sInstance.Load(text.text);
         this.tree = BTreeMgr.sInstance.GetTree("test_tree");
     }
 }
        public static void PrintToConsole(BTree<int> tree)
        {
            Console.WriteLine("\n\nPrinting to Console.");
            PrintParentIndetifier();
            ConsolePrinter printer = new ConsolePrinter();
            BTreePrinter<int> treePrinter = new BTreePrinter<int>(printer);

            treePrinter.PrintBTree(tree);
        }
Exemple #10
0
 private void Initialize()
 {
     var block = _node.GetDataBlock();
     _heap = new Heap(block);
     _bTree = new BTree<Property, ushort>(
         _heap,
         b => BitConverter.ToUInt16(b.Array, b.Offset),
         CreateProperty);
 }
        public int InsertMultipleNodesToSplit()
        {
            var btree = new BTree<int, int>(Degree);

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestDataAndValidateTree(btree, i);
            }
            return btree.Height;
        }
 public void BTreeIsCreatedEmpty()
 {
     var btree = new BTree<int, int>();
     var root = btree.Root;
     root.Should().NotBeNull();
     root.Entries.Should().NotBeNull();
     root.Children.Should().NotBeNull();
     root.Entries.Should().HaveCount(0);
     root.Children.Should().HaveCount(0);
 }
        public void SearchNodes()
        {
            var btree = new BTree<int, int>(Degree);

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestData(btree, i);
                this.SearchTestData(btree, i);
            }
        }
        public void MultipleNodesFormASplit()
        {
            var btree = new BTree<int, int>();

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestDataAndValidateTree(btree, i);
            }

            btree.Height.Should().Be(2);
        }
Exemple #15
0
        public void InsertMultipleNodesToSplit()
        {
            var btree = new BTree<int, int>(Degree);

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestDataAndValidateTree(btree, i);
            }

            Assert.AreEqual(2, btree.Height);
        }
Exemple #16
0
        static void Main(string[] args)
        {
            BTree<int> tree = new BTree<int>(1);
            tree.Add(5, 5);
            tree.Add(1, 1);
            tree.Add(2, 2);
            tree.Add(4, 4);
            tree.Add(6, 6);

            Console.WriteLine(tree.ToPrint());
        }
Exemple #17
0
 public Contact(string name)
 {
     listeners = new List<ContactInfoChangedListener>();
     Name = name;
     addresses = new BTree<Address>(new LambdaComparer<Address>((x, y) => x.Index.CompareTo(y.Index)), 50);
     numbers = new BTree<Number>(new LambdaComparer<Number>((x, y) => x.Index.CompareTo(y.Index)), 50);
     emails = new BTree<Email>(new LambdaComparer<Email>((x, y) => x.Index.CompareTo(y.Index)), 50);
     addresses.AllowDuplicates = true;
     numbers.AllowDuplicates = true;
     emails.AllowDuplicates = true;
 }
Exemple #18
0
        public void CreateBTree()
        {
            var btree = new BTree<int, int>(Degree);

            Node<int, int> root = btree.Root;
            Assert.IsNotNull(root);
            Assert.IsNotNull(root.Entries);
            Assert.IsNotNull(root.Children);
            Assert.AreEqual(0, root.Entries.Count);
            Assert.AreEqual(0, root.Children.Count);
        }
Exemple #19
0
        public void DeleteNonExistingNode()
        {
            var btree = new BTree<int, int>(Degree);

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestData(btree, i);
            }

            btree.Delete(99999);
            TreeValidation.ValidateTree(btree.Root, Degree, this.testKeyData.ToArray());
        }
Exemple #20
0
	/**
	 * Descend Tree and insert particle.  We're at a cell so
	 * we need to move down the tree.
	 *
	 * @param p    the body to insert into the tree
	 * @param xpic
	 * @param l
	 * @param tree the root of the tree
	 * @return the subtree with the new body inserted
	 */
	public override Cell loadTree(Body p, MathVector xpic, int l, BTree tree)
	{
		// move down one level
		int si = Node.oldSubindex(xpic, l);
		Node rt = subp[si];
		if(rt != null)
			subp[si] = rt.loadTree(p, xpic, l >> 1, tree);
		else
			subp[si] = p;

		return this;
	}
Exemple #21
0
        public void Find_Nonexistent_Element_Returns_Null()
        {
            var block = Block.Create(_heapData);
            var heap = new Heap(block);
            var btree = new BTree<byte[], ushort>(
                heap,
                b => BitConverter.ToUInt16(b.Array, b.Offset),
                b => b.ToArray());

            var result = btree.Find(1234);
            Assert.IsNull(result);
        }
Exemple #22
0
 public void Add(int value)
 {
     if (Column0.Count == 0)
         Column0.Add(new List<int>());
     Column0[0].Add(value);
     DBIndex i = new DBIndex(Column0[0].Count - 1);
     indexes.Add(i);
     if (Root == null)
         Root = new BTree<int>(ref Column0, indexes[indexes.Count - 1]);
     else
         Root.Add(indexes[indexes.Count - 1]);
 }
Exemple #23
0
        public void Run()
        {
            Console.WriteLine("Choose file:"); // Prompt
            Console.WriteLine("1 - tinyBTree.txt"); // Prompt
            Console.WriteLine("or quit"); // Prompt

            var fileNumber = Console.ReadLine();
            var fieName = string.Empty;
            switch (fileNumber)
            {
                case "1":
                    fieName = "tinyBTree.txt";
                    break;
                case "quit":
                    return;
                default:
                    return;
            }

            var @in = new In($"Files\\Context\\{fieName}");
            var keyValues = @in.ReadAllLines();

            //var list = words.Select(word => new StringComparable(word)).ToList();

            //var listComparable = list.Cast<IComparable>().ToList();
            //var arrayComparable = list.Cast<IComparable>().ToArray();
            //var listStrings = words.ToList();

            var bree = new BTree<string,string>();

            foreach (var keyValue in keyValues)
            {
                var splittedKeyValue = keyValue.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
                var key = splittedKeyValue[0];
                var value = splittedKeyValue[1];
                bree.Put(key,value);
            }

            Console.WriteLine("cs.princeton.edu:  " + bree.Get("www.cs.princeton.edu"));
            Console.WriteLine("hardvardsucks.com: " + bree.Get("www.harvardsucks.com"));
            Console.WriteLine("simpsons.com:      " + bree.Get("www.simpsons.com"));
            Console.WriteLine("apple.com:         " + bree.Get("www.apple.com"));
            Console.WriteLine("ebay.com:          " + bree.Get("www.ebay.com"));
            Console.WriteLine("dell.com:          " + bree.Get("www.dell.com"));
            Console.WriteLine();

            Console.WriteLine("size:    " + bree.Size());
            Console.WriteLine("height:  " + bree.Height());
            Console.WriteLine(bree);

            Console.ReadLine();
        }
Exemple #24
0
        public static sTweet[] BTreeToSerialITweet(BTree<int, sTweet> Tree, TreeIndexCheck check)
        {
            Entry<int, sTweet> chave = new Entry<int, sTweet>();
            sTweet[] TweetArray = new sTweet[check.index];

            for(int index = 0; index < check.index; index++)
            {
                chave = Tree.Search(index);
                TweetArray[index] = chave.Pointer; //salva ponteiro da árvore no array
            }

            return TweetArray;
        }
Exemple #25
0
 public DB(params string[] desc)
 {
     Trees = new BTree<IComparable>[desc.Length];
     Names = new string[desc.Length];
     Values = new List<List<IComparable>>[desc.Length];
     Indices = new List<List<DBIndex>>();
     Indices.Add(new List<DBIndex>());
     for (int i = 0; i < desc.Length; i++) {
         Values[i] = new List<List<IComparable>>();
         Values[i].Add(new List<IComparable>());
         Names[i] = desc[i];
     }
 }
Exemple #26
0
 private bool checkTreeFileIntegrity(BTree.BTree<int, sTweet> tree, TreeIndexCheck checkNewTree)
 {
     if(tree.Degree != checkNewTree.degree || tree.Height != checkNewTree.height)
     {
         MessageBox.Show(@"Problema com a árvore lida! Houve problema no salvamento dos arquivos,
                         \nOu alguém alterou informações de dentro dos arquivos.", "ERRO 004");
         return false;
     }
     else
     {
         MessageBox.Show(String.Format("Árvore salva com sucesso!\n\nHeight:\t{0}\nDegree:\t{1}\nIndex:\t{2}", tree.Height, tree.Degree, checkNewTree.index));
         return true;
     }
 }
Exemple #27
0
	/**
	 * Construct the root of the data structure that represents the N-bodies.
	 */

	public static BTree makeTreeX()
	{
		BTree t = new BTree();
		t.rmin = MathVector.makeMathVector();
		t.rsize = -2.0 * -2.0;
		t.root = null;
		t.bodyTab = null;
		t.bodyTabRev = null;

		t.rmin.setValue(0, -2.0);
		t.rmin.setValue(1, -2.0);
		t.rmin.setValue(2, -2.0);

		return t;
	}
        public Entry<int, int> SearchNonExistingNode()
        {
            var btree = new BTree<int, int>(Degree);

            // search an empty tree
            Entry<int, int> nonExisting = btree.Search(9999);
            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestData(btree, i);
                this.SearchTestData(btree, i);
            }

            // search a populated tree
           return  nonExisting = btree.Search(9999);
        }
Exemple #29
0
        public static void abcTests()
        {
            BTree<string> tree = new BTree<string>();
            tree.Add("D");
            tree.Add("B");
            tree.Add("F");
            tree.Add("A");
            tree.Add("C");
            tree.Add("E");
            tree.Add("G");

            Console.WriteLine(tree.Count);
            tree.Remove("B");
            Console.WriteLine(tree.Count);
            BTree<string> cloneTree = tree.Clone();
            Console.WriteLine(cloneTree.ToString());
            Console.WriteLine(tree.ToString());
            BTree<string> t1 = new BTree<string>();
            BTree<string> t2 = new BTree<string>();
            t1.Remove("12");
            BTree<string> nulltest = t1 + t2;

            t1.Add("D");
            t1.Add("B");
            t1.Add("A");
            t1.Add("C");

            t2.Add("F");
            t2.Add("E");
            t2.Add("G");

            BTree<float> t3 = new BTree<float>();
            t3.Add((float)11.23);
            t3.Add((float)1.7);

            float[] vals = new float[t3.Count + 5];
            t3.CopyTo(vals, 5);

            Console.WriteLine(t1.Count + "\n" + t2.Count);
            BTree<string> addedTree = t1 + t2;
            Console.WriteLine(addedTree.Count);
            addedTree.Clear();
            Console.WriteLine(addedTree.ToString() + addedTree.Count);

            BTree<string> asdf = addedTree + tree;
            Console.WriteLine(asdf);
        }
        public void NodesCanBeDeletedInReverse()
        {
            var btree = new BTree<int, int>();

            for (int i = 0; i < this.testKeyData.Length; i++)
            {
                this.InsertTestData(btree, i);
            }

            for (int i = this.testKeyData.Length - 1; i > 0; i--)
            {
                btree.Delete(this.testKeyData[i]);
                ValidateTree(btree.Root, 2, this.testKeyData.Take(i).ToArray());
            }

            btree.Height.Should().Be(1);
        }
Exemple #31
0
    private static void writeTree(BTree newTree)
    {
        BTree tree      = newTree;
        int   treeCount = 0;

        for (int i = 0; i < 10; i++)
        {
            if (i % 2 != 0)
            {
                Console.WriteLine();
                Console.WriteLine();
            }
            else
            {
                string str = "", text = "", pad = "";
                int    nodeCount = (int)(Math.Pow((double)2, (double)(i / 2)));
                int    strLength = 64 / nodeCount;

                int j = (strLength - 4) / 2;


                /// j = padLength
                /// on row 1 (index = 0), nodeCount = 1, strLength = 48, j = 22
                /// on row 2 (index = 2), nodeCount = 2,  strLength = 24, 48/2 = 8, j = 10
                /// on row 5 (index = 8), nodeCount = 16, strLength = 3, 48/16 = 3, j = -1
                while (j > 0)
                {
                    pad += ' ';
                    j--;
                }

                while (nodeCount > 0)
                {
                    if (tree.CurrentInput == treeCount)
                    {
                        str = "__";
                    }
                    else if (tree.getNode(treeCount).myValue.Length < 2)
                    {
                        str = " " + tree.getNode(treeCount).myValue;
                    }
                    else
                    {
                        str = tree.getNode(treeCount).myValue;
                    }


                    if (tree.lowestCommonParent == treeCount)
                    {
                        str = "*" + str + "*";
                    }
                    else if (tree.NodeA_index == treeCount || tree.NodeB_index == treeCount)
                    {
                        str = "[" + str + "]";
                    }
                    else
                    {
                        str = " " + str + " ";
                    }


                    /// check if node[treeCount] needs marker symbol
                    /// by comparing treeCount to list of:
                    /// input, lowestParent, nodeA, nodeB



                    /// switch statement for symbol to wrap node value
                    /// 1 = ' ## ' : default for normal nodes with values
                    /// 2 = '~##~' : nodes A and B will be marked as children
                    /// 3 = '*##*' : least common parent will be marked as Parent
                    /// 4 = ' __ ' : selection, for inputing new node values



                    text += pad + str + pad;
                    treeCount++;
                    nodeCount--;
                }
                Console.WriteLine(text);
            }
        }
    }
Exemple #32
0
 internal void Swap(BTree <TK, TV> that)
 {
     RefSwap(ref _comparer, ref that._comparer);
     RefSwap(ref _root, ref that._root);
 }
Exemple #33
0
 public virtual void RegisterBTreeIDs(BTree btree, IDMappingCollector collector)
 {
     collector.CreateIDMapping(this, btree.GetID(), false);
     TraverseAllIndexSlots(btree, new _IVisitor4_244(this, collector));
 }
Exemple #34
0
 /// <exception cref="System.Exception"></exception>
 protected override void Db4oSetupAfterStore()
 {
     _btree = NewBTree();
 }
        public void BTree_AccuracyTest()
        {
            var nodeCount = 1000;

            var rnd           = new Random();
            var randomNumbers = Enumerable.Range(1, nodeCount)
                                .OrderBy(x => rnd.Next())
                                .ToList();

            var order = 5;
            var tree  = new BTree <int>(order);

            for (int i = 0; i < nodeCount; i++)
            {
                tree.Insert(randomNumbers[i]);

                var actualMaxHeight = BTreeTester.GetMaxHeight(tree.Root);
                var actualMinHeight = BTreeTester.GetMinHeight(tree.Root);

                Assert.IsTrue(actualMaxHeight == actualMinHeight);

                //https://en.wikipedia.org/wiki/B-tree#Best_case_and_worst_case_heights
                var theoreticalMaxHeight = Math.Ceiling(Math.Log((i + 2) / 2, (int)Math.Ceiling((double)order / 2)));

                Assert.IsTrue(actualMaxHeight <= theoreticalMaxHeight);
                Assert.IsTrue(tree.Count == i + 1);

                Assert.IsTrue(tree.HasItem(randomNumbers[i]));
                //IEnumerable test using linq count()
                Assert.AreEqual(tree.Count, tree.Count());
            }

            for (int i = 0; i < nodeCount; i++)
            {
                Assert.IsTrue(tree.HasItem(randomNumbers[i]));
            }

            //IEnumerable test using linq count()
            Assert.AreEqual(tree.Count, tree.Count());

            Assert.AreEqual(tree.Max, randomNumbers.Max());
            Assert.AreEqual(tree.Min, randomNumbers.Min());

            //shuffle again before deletion tests
            randomNumbers = Enumerable.Range(1, nodeCount)
                            .OrderBy(x => rnd.Next())
                            .ToList();

            for (int i = 0; i < nodeCount; i++)
            {
                tree.Delete(randomNumbers[i]);
                Assert.IsFalse(tree.HasItem(randomNumbers[i]));

                var actualMaxHeight = BTreeTester.GetMaxHeight(tree.Root);
                var actualMinHeight = BTreeTester.GetMinHeight(tree.Root);

                Assert.IsTrue(actualMaxHeight == actualMinHeight);

                //https://en.wikipedia.org/wiki/B-tree#Best_case_and_worst_case_heights
                var theoreticalMaxHeight = Math.Ceiling(Math.Log((nodeCount - i + 2) / 2, (int)Math.Ceiling((double)order / 2)));

                Assert.IsTrue(actualMaxHeight <= theoreticalMaxHeight);
                Assert.IsTrue(tree.Count == nodeCount - 1 - i);
                //IEnumerable test using linq count()
                Assert.AreEqual(tree.Count, tree.Count());
            }

            Assert.IsTrue(tree.Count == 0);
            //IEnumerable test using linq count()
            Assert.AreEqual(tree.Count, tree.Count());
        }
        private static List <Declaration> BuildDeclarations()
        {
            List <Declaration> list = new List <Declaration>(83);

            list.Add(Aggregate.GetDeclaration());
            list.Add(AggregateRow.GetDeclaration());
            list.Add(Avg.GetDeclaration());
            list.Add(BTree.GetDeclaration());
            list.Add(BTreeNode.GetDeclaration());
            list.Add(BTreeNodeTuple.GetDeclaration());
            list.Add(BTreeNodeTupleList.GetDeclaration());
            list.Add(BTreeNodeHierarchyObj.GetDeclaration());
            list.Add(CalculatedFieldWrapperImpl.GetDeclaration());
            list.Add(ChildLeafInfo.GetDeclaration());
            list.Add(Count.GetDeclaration());
            list.Add(CountDistinct.GetDeclaration());
            list.Add(CountRows.GetDeclaration());
            list.Add(DataAggregateObj.GetDeclaration());
            list.Add(DataAggregateObjResult.GetDeclaration());
            list.Add(DataRegionMemberInstance.GetDeclaration());
            list.Add(DataFieldRow.GetDeclaration());
            list.Add(FieldImpl.GetDeclaration());
            list.Add(First.GetDeclaration());
            list.Add(Last.GetDeclaration());
            list.Add(Max.GetDeclaration());
            list.Add(Min.GetDeclaration());
            list.Add(Previous.GetDeclaration());
            list.Add(RuntimeCell.GetDeclaration());
            list.Add(RuntimeCells.GetDeclaration());
            list.Add(RuntimeCellWithContents.GetDeclaration());
            list.Add(RuntimeChartCriCell.GetDeclaration());
            list.Add(RuntimeChartCriGroupLeafObj.GetDeclaration());
            list.Add(RuntimeChartCriObj.GetDeclaration());
            list.Add(RuntimeChartObj.GetDeclaration());
            list.Add(RuntimeCriObj.GetDeclaration());
            list.Add(RuntimeDataRegionObj.GetDeclaration());
            list.Add(RuntimeDataTablixObj.GetDeclaration());
            list.Add(RuntimeDataTablixGroupLeafObj.GetDeclaration());
            list.Add(RuntimeDataTablixGroupRootObj.GetDeclaration());
            list.Add(RuntimeDataTablixMemberObj.GetDeclaration());
            list.Add(RuntimeDataTablixWithScopedItemsObj.GetDeclaration());
            list.Add(RuntimeDataTablixWithScopedItemsGroupLeafObj.GetDeclaration());
            list.Add(RuntimeDetailObj.GetDeclaration());
            list.Add(RuntimeExpressionInfo.GetDeclaration());
            list.Add(RuntimeGroupLeafObj.GetDeclaration());
            list.Add(RuntimeGroupObj.GetDeclaration());
            list.Add(RuntimeGroupRootObj.GetDeclaration());
            list.Add(RuntimeGroupingObj.GetDeclaration());
            list.Add(RuntimeHierarchyObj.GetDeclaration());
            list.Add(RuntimeMemberObj.GetDeclaration());
            list.Add(RuntimeRDLDataRegionObj.GetDeclaration());
            list.Add(RuntimeRICollection.GetDeclaration());
            list.Add(RuntimeSortDataHolder.GetDeclaration());
            list.Add(RuntimeSortFilterEventInfo.GetDeclaration());
            list.Add(RuntimeSortFilterEventInfo.SortExpressionScopeInstanceHolder.GetDeclaration());
            list.Add(RuntimeSortFilterEventInfo.SortFilterExpressionScopeObj.GetDeclaration());
            list.Add(RuntimeSortFilterEventInfo.SortScopeValuesHolder.GetDeclaration());
            list.Add(RuntimeSortHierarchyObj.GetDeclaration());
            list.Add(RuntimeSortHierarchyObj.SortHierarchyStructure.GetDeclaration());
            list.Add(RuntimeDataRowSortHierarchyObj.GetDeclaration());
            list.Add(RuntimeTablixCell.GetDeclaration());
            list.Add(RuntimeTablixGroupLeafObj.GetDeclaration());
            list.Add(RuntimeTablixObj.GetDeclaration());
            list.Add(RuntimeUserSortTargetInfo.GetDeclaration());
            list.Add(ScopeInstance.GetDeclaration());
            list.Add(ScopeLookupTable.GetDeclaration());
            list.Add(StDev.GetDeclaration());
            list.Add(StDevP.GetDeclaration());
            list.Add(Sum.GetDeclaration());
            list.Add(Var.GetDeclaration());
            list.Add(VarBase.GetDeclaration());
            list.Add(VarP.GetDeclaration());
            list.Add(Filters.FilterKey.GetDeclaration());
            list.Add(RuntimeGaugePanelObj.GetDeclaration());
            list.Add(LookupMatches.GetDeclaration());
            list.Add(LookupMatchesWithRows.GetDeclaration());
            list.Add(LookupTable.GetDeclaration());
            list.Add(RuntimeMapDataRegionObj.GetDeclaration());
            list.Add(DataScopeInfo.GetDeclaration());
            list.Add(BucketedDataAggregateObjs.GetDeclaration());
            list.Add(DataAggregateObjBucket.GetDeclaration());
            list.Add(RuntimeGroupingObjHash.GetDeclaration());
            list.Add(RuntimeGroupingObjTree.GetDeclaration());
            list.Add(RuntimeGroupingObjDetail.GetDeclaration());
            list.Add(RuntimeGroupingObjDetailUserSort.GetDeclaration());
            list.Add(RuntimeGroupingObjLinkedList.GetDeclaration());
            list.Add(RuntimeGroupingObjNaturalGroup.GetDeclaration());
            return(list);
        }
Exemple #37
0
 internal static long BTreeUsage(LocalObjectContainer db, BTree btree, ISlotMap slotMap
                                 )
 {
     return(BTreeUsage(db.SystemTransaction(), db.IdSystem(), btree, slotMap));
 }
Exemple #38
0
        public static void DoInsertTest()
        {
            BTree <int> bTree = new BTree <int>(4);

            //
            // CASE #1
            // Insert: 10, 30, 20, 50, 40, 60, 70
            // ROOT contains all values; no split.
            //

            /***************************************
            **
            **    [10 , 20 , 30 , 40, 50, 60, 70]
            **
            ***************************************
            */
            bTree.Insert(10);
            bTree.Insert(30);
            bTree.Insert(20);
            bTree.Insert(50);
            bTree.Insert(40);
            bTree.Insert(60);
            bTree.Insert(70);

            Assert.Equal(7, bTree.Root.Keys.Count);


            //
            // CASE #2
            // Insert to the previous tree: 35.
            // Split into multiple.
            //

            /***************************************
            **
            **                      [40]
            **                     /    \
            **                    /      \
            ** [10 , 20 , 30 , 35]        [50 , 60 , 70]
            **
            ***************************************
            */
            bTree.Insert(35);
            Assert.Equal(40, bTree.Root.Keys[0]);
            Assert.Equal(4, bTree.Root.Children[0].Keys.Count);
            Assert.Equal(3, bTree.Root.Children[1].Keys.Count);


            //
            // CASE #3
            // Insert to the previous tree: 5, 15, 25, 39.
            // Split leftmost child.
            //

            /***************************************
            **
            **                      [20 , 40]
            **                     /    |    \
            **                    /     |     \
            **         [5, 10, 15]      |      [50 , 60 , 70]
            **                          |
            **                   [25, 30, 35, 39]
            **
            ***************************************
            */

            bTree.Insert(5);
            bTree.Insert(15);
            bTree.Insert(25);
            bTree.Insert(39);
            Assert.Equal(20, bTree.Root.Keys[0]);
            Assert.Equal(40, bTree.Root.Keys[1]);
            Assert.Equal(3, bTree.Root.Children[0].Keys.Count);
            Assert.Equal(4, bTree.Root.Children[1].Keys.Count);
            Assert.Equal(3, bTree.Root.Children[2].Keys.Count);
        }
Exemple #39
0
 public void ProcessBTree(DefragmentServicesImpl context, BTree btree)
 {
     context.RegisterBTreeIDs(btree, _collector);
 }
 protected override void AdjustSizeOnRemovalByOtherTransaction(BTree btree, BTreeNode
                                                               node)
 {
 }
Exemple #41
0
        public static void DoDeleteTest()
        {
            // Build a base tree
            BTree <int> bTree = new BTree <int>(4);

            bTree.Insert(10);
            bTree.Insert(30);
            bTree.Insert(20);
            bTree.Insert(50);
            bTree.Insert(40);
            bTree.Insert(60);
            bTree.Insert(70);
            bTree.Insert(35);
            bTree.Insert(5);
            bTree.Insert(15);
            bTree.Insert(25);
            bTree.Insert(39);

            // The tree now looks like this:

            /***************************************
            **
            **                      [20 , 40]
            **                     /    |    \
            **                    /     |     \
            **         [5, 10, 15]      |      [50 , 60 , 70]
            **                          |
            **                   [25, 30, 35, 39]
            **
            ***************************************
            */
            // First. assert the shape.
            Assert.Equal(2, bTree.Search(20).Keys.Count);
            Assert.Equal(2, bTree.Search(40).Keys.Count);
            Assert.Null(bTree.Search(41));
            Assert.Equal(3, bTree.Search(5).Keys.Count);
            Assert.Equal(4, bTree.Search(25).Keys.Count);

            // Now, remove a key from the left-most child.
            bTree.Remove(5);

            // The tree now looks like this:

            /***************************************
            **
            **                              [40]
            **                             /    \
            **                            /      \
            ** [10, 15, 20, 25, 30, 35, 39]       [50 , 60 , 70]
            **
            ***************************************
            */

            // The tree should now be rooted around 40, with the left child full.
            Assert.Equal(null, bTree.Search(5));
            Assert.Equal(2, bTree.Root.Children.Count);
            Assert.Equal(7, bTree.Root.Children[0].Keys.Count); // left-most
            Assert.Equal(3, bTree.Root.Children[1].Keys.Count); // right-most

            // Remove 50 - it needs to be rebalanced now.
            bTree.Remove(50);

            // The tree now looks like this:

            /***************************************
            **
            **                           [39]
            **                          /    \
            **                         /      \
            ** [10, 15, 20, 25, 30, 35]       [40, 60, 70]
            **
            ***************************************
            */
            Assert.Equal(39, bTree.Root.Keys[0]);
            Assert.Equal(6, bTree.Root.Children[0].Keys.Count);
            Assert.Equal(3, bTree.Root.Children[1].Keys.Count);

            // Remove everything
            bTree.Remove(10);
            bTree.Remove(15);
            bTree.Remove(20);
            bTree.Remove(25);
            bTree.Remove(30);
            bTree.Remove(35);
            bTree.Remove(39);
            bTree.Remove(40);
            bTree.Remove(60);
            bTree.Remove(70);

            Assert.Null(bTree.Root);
        }
 protected override void Committed(BTree btree)
 {
 }
        public virtual void Convert(LocalObjectContainer container, int classIndexId, BTree
                                    bTree)
        {
            Transaction     trans  = container.SystemTransaction();
            ByteArrayBuffer reader = container.ReadBufferById(trans, classIndexId);

            if (reader == null)
            {
                return;
            }
            int entries = reader.ReadInt();

            for (int i = 0; i < entries; i++)
            {
                bTree.Add(trans, reader.ReadInt());
            }
        }
Exemple #44
0
        static void Main(string[] args)
        {
            String.LongestCommonPrefix(new string[] { "flower", "flow", "flight" });
            ArrayQ2 arrayQ2      = new ArrayQ2();
            int     remainingnum = arrayQ2.NumberWhichDoesnothaveaCorrrepondingNegative1(new int[] { 1, -1, 2, -2, 4, -4, 3 });

            arrayQ2.solution(new int[] { 1, 3, 2, 4, 5 });

            Recurssion recurssion = new Recurssion();

            recurssion.abs = 10;
            recurssion.Recurse(0);
            int    prop = recurssion.MyProperty;
            string s    = "jell";
            string sb   = String.ConvertToBinary(5);

            int[] nums = { 1, 2, 3, 2, 3 };

            Console.WriteLine(2 ^ 3);

            int unique = 0;

            foreach (int i in nums)
            {
                unique ^= i;
            }

            #region LinkedList

            LinkedListT linkedListT = new LinkedListT(1);
            linkedListT.head.Next      = new LinkedListNode(1);
            linkedListT.head.Next.Next = new LinkedListNode(2);

            LinkedListNode head = linkedListT.DeleteDuplicates(linkedListT.head);

            #endregion

            #region String

            string read = Console.ReadLine();

            #region Count of alphabet, integer and string
            int alph = 0; int num = 0; int special = 0;

            for (int i = 0; i < read.Length; i++)
            {
                if ((read[i] >= 'a' && read[i] <= 'z') || (read[i] >= 'A' && read[i] <= 'Z'))
                {
                    alph++;
                }
                else if (read[i] >= '0' && read[i] <= '9')
                {
                    num++;
                }
                else
                {
                    special++;
                }
            }

            Console.WriteLine($"Alphabet count in string is {alph}");
            Console.WriteLine($"Integer count in string is {num}");
            Console.WriteLine($"Special character count in string is {special}");
            #endregion

            Dictionary <char, int> dicCharCount = new Dictionary <char, int>();

            for (int i = 0; i < read?.Length; i++)
            {
                if (dicCharCount.ContainsKey(read[i]))
                {
                    dicCharCount[read[i]]++;
                }
                else
                {
                    dicCharCount.Add(read[i], 1);
                }
            }

            //var val = dicCharCount.Max();

            //Console.WriteLine(dicCharCount.Max().Value);

            /// Count of words in a string
            //Console.WriteLine(read.Split(' ').Length);

            //int counter = 0;
            //foreach (char a in read)
            //{
            //    counter++;
            //}
            //Console.WriteLine(counter);

            #region Palindrome
            string s4 = "raja";
            string s1 = string.Join("", s.Reverse().ToArray());
            if (read == s)
            {
                Console.WriteLine("Palindrome");
            }
            else
            {
                Console.WriteLine("Non Palindrome");
            }
            #endregion



            #endregion

            #region Tree
            BTree bTree = new BTree(5);
            bTree.InsertNodeBST(1);
            bTree.InsertNodeBST(7);

            //var b = bTree.SearchBST(bTree.rootNode, 5);


            bTree.printInOrder();
            //bTree.rootNode.left = new TreeNode(4);
            //bTree.rootNode.right = new TreeNode(6);
            //bTree.rootNode.left.left = new TreeNode(8);
            //bTree.printPostorder();
            //Console.WriteLine();
            //bTree.printPreOrder();
            //Console.WriteLine();
            //bTree.printInOrder();
            //Console.WriteLine(bTree.size(bTree.rootNode));
            //Console.ReadLine();
            #endregion

            #region Array

            #region Plus one in an array
            //Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
            //Input: [1,2,3]
            //Output:[1,2,4]

            int[] PlusOne(int[] digits)
            {
                int carry = 1;
                int i     = 0;

                for (i = digits.Length - 1; i >= 0; i--)
                {
                    if (digits[i] == 9)
                    {
                        digits[i] = 0;
                    }
                    else
                    {
                        digits[i] = digits[i] + 1;
                        return(digits);
                    }
                }

                if (i == -1)
                {
                    int[] arr = new int[digits.Length + 1];
                    arr[0] = 1;
                    return(arr);
                }

                return(digits);
            }

            #endregion

            #endregion

            #region Arithmetic

            #region Square Root
            int sq = 0;
            int x  = 6;

            while (sq <= x / 2)
            {
                if (sq * sq == x)
                {
                    Console.WriteLine(sq);
                    break;
                }
                else if (sq * sq > x)
                {
                    Console.WriteLine(sq - 1);
                    break;
                }
                sq++;
            }
            #endregion
            #endregion
        }
Exemple #45
0
        public void Contains_Item_Test()
        {
            BTree <int> bTree = InitBTree();

            Assert.IsTrue(bTree.Contains(5));
        }
Exemple #46
0
 private void InsertTestData(BTree <int, int> btree, int testDataIndex)
 {
     btree.Insert(this.testKeyData[testDataIndex], this.testPointerData[testDataIndex]);
 }
        public bool TryCreateObject(ObjectType objectType, out IPersistable persistObj)
        {
            switch (objectType)
            {
            case ObjectType.Aggregate:
                persistObj = new Aggregate();
                break;

            case ObjectType.AggregateRow:
                persistObj = new AggregateRow();
                break;

            case ObjectType.Avg:
                persistObj = new Avg();
                break;

            case ObjectType.BTree:
                persistObj = new BTree();
                break;

            case ObjectType.BTreeNode:
                persistObj = new BTreeNode();
                break;

            case ObjectType.BTreeNodeTupleList:
                persistObj = new BTreeNodeTupleList();
                break;

            case ObjectType.BTreeNodeTuple:
                persistObj = new BTreeNodeTuple();
                break;

            case ObjectType.BTreeNodeHierarchyObj:
                persistObj = new BTreeNodeHierarchyObj();
                break;

            case ObjectType.CalculatedFieldWrapperImpl:
                persistObj = new CalculatedFieldWrapperImpl();
                break;

            case ObjectType.ChildLeafInfo:
                persistObj = new ChildLeafInfo();
                break;

            case ObjectType.Count:
                persistObj = new Count();
                break;

            case ObjectType.CountDistinct:
                persistObj = new CountDistinct();
                break;

            case ObjectType.CountRows:
                persistObj = new CountRows();
                break;

            case ObjectType.DataAggregateObj:
                persistObj = new DataAggregateObj();
                break;

            case ObjectType.DataAggregateObjResult:
                persistObj = new DataAggregateObjResult();
                break;

            case ObjectType.DataFieldRow:
                persistObj = new DataFieldRow();
                break;

            case ObjectType.DataRegionMemberInstance:
                persistObj = new DataRegionMemberInstance();
                break;

            case ObjectType.FieldImpl:
                persistObj = new FieldImpl();
                break;

            case ObjectType.First:
                persistObj = new First();
                break;

            case ObjectType.Last:
                persistObj = new Last();
                break;

            case ObjectType.Max:
                persistObj = new Max();
                break;

            case ObjectType.Min:
                persistObj = new Min();
                break;

            case ObjectType.Previous:
                persistObj = new Previous();
                break;

            case ObjectType.RuntimeCells:
                persistObj = new RuntimeCells();
                break;

            case ObjectType.RuntimeChartCriCell:
                persistObj = new RuntimeChartCriCell();
                break;

            case ObjectType.RuntimeChartCriGroupLeafObj:
                persistObj = new RuntimeChartCriGroupLeafObj();
                break;

            case ObjectType.RuntimeChartObj:
                persistObj = new RuntimeChartObj();
                break;

            case ObjectType.RuntimeGaugePanelObj:
                persistObj = new RuntimeGaugePanelObj();
                break;

            case ObjectType.RuntimeCriObj:
                persistObj = new RuntimeCriObj();
                break;

            case ObjectType.RuntimeDataTablixGroupRootObj:
                persistObj = new RuntimeDataTablixGroupRootObj();
                break;

            case ObjectType.RuntimeDataTablixMemberObj:
                persistObj = new RuntimeDataTablixMemberObj();
                break;

            case ObjectType.RuntimeExpressionInfo:
                persistObj = new RuntimeExpressionInfo();
                break;

            case ObjectType.RuntimeHierarchyObj:
                persistObj = new RuntimeHierarchyObj();
                break;

            case ObjectType.RuntimeRICollection:
                persistObj = new RuntimeRICollection();
                break;

            case ObjectType.RuntimeSortDataHolder:
                persistObj = new RuntimeSortDataHolder();
                break;

            case ObjectType.RuntimeSortFilterEventInfo:
                persistObj = new RuntimeSortFilterEventInfo();
                break;

            case ObjectType.RuntimeSortHierarchyObj:
                persistObj = new RuntimeSortHierarchyObj();
                break;

            case ObjectType.RuntimeDataRowSortHierarchyObj:
                persistObj = new RuntimeDataRowSortHierarchyObj();
                break;

            case ObjectType.RuntimeTablixCell:
                persistObj = new RuntimeTablixCell();
                break;

            case ObjectType.RuntimeTablixGroupLeafObj:
                persistObj = new RuntimeTablixGroupLeafObj();
                break;

            case ObjectType.RuntimeTablixObj:
                persistObj = new RuntimeTablixObj();
                break;

            case ObjectType.RuntimeUserSortTargetInfo:
                persistObj = new RuntimeUserSortTargetInfo();
                break;

            case ObjectType.ScopeLookupTable:
                persistObj = new ScopeLookupTable();
                break;

            case ObjectType.SortExpressionScopeInstanceHolder:
                persistObj = new RuntimeSortFilterEventInfo.SortExpressionScopeInstanceHolder();
                break;

            case ObjectType.SortFilterExpressionScopeObj:
                persistObj = new RuntimeSortFilterEventInfo.SortFilterExpressionScopeObj();
                break;

            case ObjectType.SortHierarchyStruct:
                persistObj = new RuntimeSortHierarchyObj.SortHierarchyStructure();
                break;

            case ObjectType.SortScopeValuesHolder:
                persistObj = new RuntimeSortFilterEventInfo.SortScopeValuesHolder();
                break;

            case ObjectType.StDev:
                persistObj = new StDev();
                break;

            case ObjectType.StDevP:
                persistObj = new StDevP();
                break;

            case ObjectType.StorageItem:
                persistObj = new StorageItem();
                break;

            case ObjectType.Sum:
                persistObj = new Sum();
                break;

            case ObjectType.Var:
                persistObj = new Var();
                break;

            case ObjectType.VarP:
                persistObj = new VarP();
                break;

            case ObjectType.FilterKey:
                persistObj = new Filters.FilterKey();
                break;

            case ObjectType.LookupMatches:
                persistObj = new LookupMatches();
                break;

            case ObjectType.LookupMatchesWithRows:
                persistObj = new LookupMatchesWithRows();
                break;

            case ObjectType.LookupTable:
                persistObj = new LookupTable();
                break;

            case ObjectType.Union:
                persistObj = new Union();
                break;

            case ObjectType.RuntimeMapDataRegionObj:
                persistObj = new RuntimeMapDataRegionObj();
                break;

            case ObjectType.DataScopeInfo:
                persistObj = new DataScopeInfo();
                break;

            case ObjectType.BucketedDataAggregateObjs:
                persistObj = new BucketedDataAggregateObjs();
                break;

            case ObjectType.DataAggregateObjBucket:
                persistObj = new DataAggregateObjBucket();
                break;

            case ObjectType.RuntimeGroupingObjHash:
                persistObj = new RuntimeGroupingObjHash();
                break;

            case ObjectType.RuntimeGroupingObjTree:
                persistObj = new RuntimeGroupingObjTree();
                break;

            case ObjectType.RuntimeGroupingObjDetail:
                persistObj = new RuntimeGroupingObjDetail();
                break;

            case ObjectType.RuntimeGroupingObjDetailUserSort:
                persistObj = new RuntimeGroupingObjDetailUserSort();
                break;

            case ObjectType.RuntimeGroupingObjLinkedList:
                persistObj = new RuntimeGroupingObjLinkedList();
                break;

            case ObjectType.RuntimeGroupingObjNaturalGroup:
                persistObj = new RuntimeGroupingObjNaturalGroup();
                break;

            default:
                persistObj = null;
                return(false);
            }
            return(true);
        }
Exemple #48
0
 private void InsertTestDataAndValidateTree(BTree <int, int> btree, int testDataIndex)
 {
     btree.Insert(this.testKeyData[testDataIndex], this.testPointerData[testDataIndex]);
     TreeValidation.ValidateTree(btree.Root, Degree, this.testKeyData.Take(testDataIndex + 1).ToArray());
 }
Exemple #49
0
 private long BTreeUsage(BTree btree)
 {
     return(BTreeUsage(_db, btree, _slots));
 }
Exemple #50
0
 public void Setup()
 {
     tree = new BTree(3);
 }
Exemple #51
0
    void OnGUI()
    {
        //////////////////// draw the tree /////////////////////
        this.m_cScrollPos = GUI.BeginScrollView(new Rect(0, 0, position.width - 240, position.height), this.m_cScrollPos, new Rect(0, 0, this.maxSize.x, this.maxSize.y));

        Texture2D tex1 = new Texture2D(1, 1);

        tex1.SetPixel(0, 0, Color.black);
        tex1.Apply();
        Texture2D tex2 = new Texture2D(1, 1);

        tex2.SetPixel(0, 0, Color.gray);
        tex2.Apply();
        for (int i = 0; i < 1000; i++)
        {
            if (i % 2 == 0)
            {
                GUI.DrawTexture(new Rect(0, i * NODE_HEIGHT, BTreeWin.sInstance.position.width, NODE_HEIGHT), tex1);
            }
            else
            {
                GUI.DrawTexture(new Rect(0, i * NODE_HEIGHT, BTreeWin.sInstance.position.width, NODE_HEIGHT), tex2);
            }
        }

        if (cur_tree != null && cur_tree.m_cRoot != null)
        {
            int xx = 0;
            int yy = 0;
            cur_tree.m_cRoot.Render(xx, ref yy);
        }

        GUI.EndScrollView();
        //////////////////// draw the tree /////////////////////

        //////////////////// draw editor gui /////////////////////
        GUI.BeginGroup(new Rect(position.width - GUI_WIDTH, 0, 300, 1000));
        int          x   = 0;
        int          y   = 0;
        List <BTree> lst = BTreeMgr.sInstance.GetTrees();

        if (GUI.Button(new Rect(x, y, 200, 40), "Load"))
        {
            cur_tree              = null;
            cur_node              = null;
            cur_tree_index        = -1;
            last_tree_index       = -1;
            select_create_node_id = -1;
            select = null;

            BTreeMgr.sInstance.EditorLoad();
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "Save Editor BTree"))
        {
            BTreeMgr.sInstance.EditorSave();
            AssetDatabase.Refresh();
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "Save BTree"))
        {
//			BTreeMgr.sInstance.SaveEx();
            AssetDatabase.Refresh();
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        this.m_strInputName = GUI.TextField(new Rect(x, y + 10, 100, 20), this.m_strInputName);
        if (GUI.Button(new Rect(x + 100, y, 100, 40), "create tree"))
        {
            if (this.m_strInputName != "")
            {
                cur_node = null;
                BTree tree = new BTree();
                tree.m_strName = this.m_strInputName;
                BTreeMgr.sInstance.Add(tree);
                lst      = BTreeMgr.sInstance.GetTrees();
                cur_tree = tree;
                for (int i = 0; i < lst.Count; i++)
                {
                    if (lst[i].m_strName == tree.m_strName)
                    {
                        cur_tree_index = i;
                        break;
                    }
                }
                last_tree_index = cur_tree_index;
                Repaint();
            }
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "remove tree"))
        {
            cur_node = null;
            BTreeMgr.sInstance.Remove(cur_tree);
            lst             = BTreeMgr.sInstance.GetTrees();
            cur_tree        = null;
            cur_tree_index  = -1;
            last_tree_index = -1;
            Repaint();
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        string[] treeNames = new string[lst.Count];
        for (int i = 0; i < lst.Count; i++)
        {
            treeNames[i] = lst[i].m_strName;
        }
        cur_tree_index = EditorGUI.Popup(new Rect(x, y, 200, 45), cur_tree_index, treeNames);
        if (cur_tree_index != last_tree_index)
        {
            last_tree_index = cur_tree_index;
            cur_tree        = lst[cur_tree_index];
            cur_node        = null;
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;

        if (cur_tree != null)
        {
            GUI.Label(new Rect(x, y, 200, 20), "TreeName: " + cur_tree.m_strName);
            y += 20;
            cur_tree.m_strName = GUI.TextField(new Rect(x, y, 100, 20), cur_tree.m_strName);
            y += 20;
        }
        select_create_node_id = EditorGUI.Popup(new Rect(x, y, 100, 40), select_create_node_id, BNodeFactory.sInstance.GetNodeLst());
        if (GUI.Button(new Rect(x + 100, y, 100, 40), "create root"))
        {
            if (select_create_node_id >= 0)
            {
                BNode node = BNodeFactory.sInstance.Create(select_create_node_id);
                if (cur_tree != null)
                {
                    cur_tree.m_cRoot = node;
                }
            }
        }
        y += 40;
        if (GUI.Button(new Rect(x, y, 200, 40), "clear"))
        {
            if (cur_tree != null)
            {
                cur_tree.Clear();
            }
        }
        y += 40;
        GUI.Label(new Rect(x, y, 200, 20), "=======================");
        y += 20;
        if (cur_node != null)
        {
            GUI.Label(new Rect(x, y, 300, 20), "Node Type: " + cur_node.GetType().FullName);
            y += 20;
            GUI.Label(new Rect(x, y, 200, 20), "Node Name: " + cur_node.GetName());
            y += 20;
            GUI.Label(new Rect(x, y, 200, 15), "=======================");
            y += 15;
            cur_node.RenderEditor(x, y);
        }
        //
        GUI.EndGroup();
        //////////////////// draw editor gui /////////////////////
    }
        static void Main(string[] args)
        {
            var seeds = new Random();

            for (int j = 0; j < N.Length; j++)
            {
                var rnd = new Random(seeds.Next());
                for (int k = 0; k < 4; k++)
                {
                    var ss = new string[N[j]];
                    var ps = new int[N[j]];
                    for (int i = 0; i < N[j]; i++)
                    {
                        ss[i] = AString(rnd);
                    }
                    long ct = 0;
                    // Castro
                    var t  = DateTime.Now;
                    var bt = new BTree <string, int>(8);
                    for (int i = 0; i < N[j]; i++)
                    {
                        if (bt.Search(ss[i]) is Entry <string, int> e)
                        {
                            ps[i] = e.Pointer;
                        }
                        else
                        {
                            bt.Insert(ss[i], i);
                            ps[i] = i;
                        }
                    }
                    for (int i = 0; i < N[j]; i++)
                    {
                        if (bt.Search(ss[i]).Pointer != ps[i])
                        {
                            Console.WriteLine("Error 1");
                        }
                    }
                    //           for (int i = 0; i < N[j]; i++)
                    //               bt.Delete(ss[i]);
                    ct = (DateTime.Now - t).Ticks;
                    // Crowe
                    t = DateTime.Now;
                    var sb = SDict <string, int> .Empty;
                    for (int i = 0; i < N[j]; i++)
                    {
                        if (sb.Contains(ss[i]))
                        {
                            if (ps[i] != sb.Lookup(ss[i]))
                            {
                                Console.WriteLine("Mismatch");
                            }
                        }
                        else
                        {
                            sb    = sb.Add(ss[i], i);
                            ps[i] = i;
                        }
                    }
                    for (int i = 0; i < N[j]; i++)
                    {
                        if (sb.Lookup(ss[i]) != ps[i])
                        {
                            Console.WriteLine("Error 2");
                        }
                    }
                    //          for (int i = 0; i < N[j]; i++)
                    //              sb = sb.Remove(ss[i]);
                    var st = (DateTime.Now - t).Ticks;
                    Console.WriteLine(ct + " " + st + " " + (st * 100.0 / ct));
                }
            }
            Console.ReadLine();
        }
Exemple #53
0
 public BTreeKeyedNode(BTree tree, BTreeNodeDescriptor descriptor)
     : base(tree, descriptor)
 {
 }
Exemple #54
0
 public RunBTree()
 {
     _bst = new BTree <int>();
     InitTree();
 }
 public void InitTree()
 {
     testTree = new BTree <int>();
 }
Exemple #56
0
        static void Main(string[] args)
        {
            string        filePath     = "dbcore.xml";
            bool          cycleProgram = true;
            XmlSerializer formatter    = new XmlSerializer(typeof(Test[]));

            Console.WriteLine("TEST SYSTEM 'Sirik-9000' initialised");
            Console.WriteLine("");

            BTree <Test> tests = new BTree <Test>(default(Test));

            while (cycleProgram)
            {
                string query = "";
                Console.Write("> ");
                query = Console.ReadLine();
                Console.Write("");
                var queryTokens = query.Split(' ');

                switch (queryTokens[0])
                {
                case "exit":
                {
                    Console.WriteLine("Exiting program...");
                    cycleProgram = false;
                    break;
                }

                case "create":
                {
                    try
                    {
                        if (tests.Value is null)
                        {
                            tests.Value = new Test {
                                StudentName = queryTokens[1].ToString(), TestName = queryTokens[2].ToString(), TestPassDate = DateTime.Parse(queryTokens[3].ToString()), Mark = int.Parse(queryTokens[4])
                            }
                        }
                        ;
                        else
                        {
                            tests.BranchLeft(new Test {
                                    StudentName = queryTokens[1].ToString(), TestName = queryTokens[2].ToString(), TestPassDate = DateTime.Parse(queryTokens[3].ToString()), Mark = int.Parse(queryTokens[4])
                                });
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid arguments!");
                    }

                    break;
                }

                case "read":
                {
                    try
                    {
                        if (queryTokens[1] == "-a")
                        {
                            int i           = 0;
                            var resultquery = tests.ToArray();
                            Console.WriteLine("All records:");
                            foreach (Test item in resultquery)
                            {
                                Console.WriteLine($"{i}. '{item.StudentName}' wrote the test '{item.TestName}' in {item.TestPassDate.Year}-{item.TestPassDate.Month}-{item.TestPassDate.Day} with total points {item.Mark.ToString()}");
                                i++;
                            }
                            Console.WriteLine("");
                        }
                        else if (queryTokens[1] == "-p")
                        {
                            var resultquery = from t in tests.ToArray()
                                              orderby t.Mark descending
                                              where t.Mark >= int.Parse(queryTokens[2])
                                              select t;

                            Console.WriteLine($"Students, that passed {queryTokens[2]} mark criteria:");
                            foreach (Test item in resultquery)
                            {
                                Console.WriteLine($"'{item.StudentName}' wrote the test '{item.TestName}' in {item.TestPassDate.Year}-{item.TestPassDate.Month}-{item.TestPassDate.Day} with total points {item.Mark.ToString()}");
                            }
                            Console.WriteLine("");
                        }
                        else if (queryTokens[1] == "-i")
                        {
                            var resultquery = tests.ToArray()[int.Parse(queryTokens[2])];

                            Console.WriteLine($"Student with index {int.Parse(queryTokens[2])}");
                            Console.WriteLine($"'{resultquery.StudentName}' wrote the test '{resultquery.TestName}' in {resultquery.TestPassDate.Year}-{resultquery.TestPassDate.Month}-{resultquery.TestPassDate.Day} with total points {resultquery.Mark.ToString()}");
                            Console.WriteLine("");
                        }
                        else if (queryTokens[1] == "-c")
                        {
                            int resultquery = tests.ToArray().Length;
                            Console.WriteLine($"Records in DB {resultquery}");
                            Console.WriteLine("");
                        }
                        else if (queryTokens[1] == "-s")
                        {
                            int i           = 0;
                            var resultquery = from t in tests.ToArray()
                                              orderby t.Mark descending
                                              select t;

                            Console.WriteLine("Sorted records:");
                            foreach (Test item in resultquery)
                            {
                                Console.WriteLine($"{i}. '{item.StudentName}' wrote the test '{item.TestName}' in {item.TestPassDate.Year}-{item.TestPassDate.Month}-{item.TestPassDate.Day} with total points {item.Mark.ToString()}");
                                i++;
                            }
                            Console.WriteLine("");
                        }
                        else
                        {
                            Console.WriteLine("Invalid arguments!");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid arguments!");
                    }

                    break;
                }

                case "update":
                {
                    try
                    {
                        if (queryTokens[1] == "-n")
                        {
                            tests[int.Parse(queryTokens[2])].Value.StudentName = queryTokens[3].ToString();
                        }
                        else if (queryTokens[1] == "-t")
                        {
                            tests[int.Parse(queryTokens[2])].Value.TestName = queryTokens[3].ToString();
                        }
                        else if (queryTokens[1] == "-d")
                        {
                            tests[int.Parse(queryTokens[2])].Value.TestPassDate = DateTime.Parse(queryTokens[3]);
                        }
                        else if (queryTokens[1] == "-m")
                        {
                            tests[int.Parse(queryTokens[2])].Value.Mark = int.Parse(queryTokens[3]);
                        }
                        else
                        {
                            Console.WriteLine("Invalid arguments!");
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid arguments!");
                    }
                    break;
                }

                case "drop":
                {
                    try
                    {
                        if ((tests[int.Parse(queryTokens[1]) - 1]?.LeftLink?.Value is null))
                        {
                            tests[int.Parse(queryTokens[1]) - 1] = new BTerminal <Test>(default(Test));
                        }
                        else
                        {
                            tests[int.Parse(queryTokens[1]) - 1] = tests[int.Parse(queryTokens[1]) - 1].LeftLink;
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Invalid arguments!");
                    }

                    break;
                }
Exemple #57
0
 /// <summary>
 /// Checks whether tree has B Tree properties.
 /// </summary>
 /// <param name="tree">A BTree node. </param>
 /// <param name="expectedTotalKeyCount">The expected number of keys (duplicate and distinct) in the tree. </param>
 /// <param name="expectedDistinctKeyCount">The expected number of distinct keys in the tree. </param>
 /// <param name="expectedNodeCount">The expected number of nodes in the tree. </param>
 public static void HasBTreeProperties(BTree <int, string> tree, int expectedTotalKeyCount, int expectedDistinctKeyCount, int expectedNodeCount)
 {
     Assert.IsTrue(HasBTreeProperties(tree, expectedTotalKeyCount, expectedDistinctKeyCount, expectedNodeCount, HasBTreeNodeProperties <BTreeNode <int, string>, int, string>));
 }
Exemple #58
0
        public void Add_Items_Test()
        {
            BTree <int> bTree = InitBTree();

            Assert.AreEqual(bTree.Count, 10);
        }
Exemple #59
0
    static int Main(string[] args)
    {
        if (args.Length != 2)
        {
            Console.Clear();
            Console.WriteLine();
            Console.WriteLine("********************************************************************************");
            Console.WriteLine("*                                                                              *");
            Console.WriteLine("*         Proper use of program is:  ~~~~ > FindParent.exe [node1] [node2]     *");
            Console.WriteLine("*                                                                              *");
            Console.WriteLine("********************************************************************************");
            Console.WriteLine();
            return(1);
        }
        else if (!(isValidString(args[0]) && isValidString(args[1])))
        {
            Console.Clear();
            Console.WriteLine();
            Console.WriteLine("********************************************************************************");
            Console.WriteLine("*         Proper use of program is:   > FindParent.exe [node1] [node2]         *");
            Console.WriteLine("*          Where node1 and node2 are strings of 1 or 2 characters              *");
            Console.WriteLine("*        Characters can be numbers, or UPPPERCASE or lowercase letters         *");
            Console.WriteLine("********************************************************************************");
            Console.WriteLine();
            return(1);
        }
        Console.Clear();
        int    maxNode = (int)Math.Pow(2, 5) - 1;
        string nodeA   = args[0];
        string nodeB   = args[1];

        BTree tree = new BTree(maxNode);

        // tree = makeTree((int)Math.Log((double)(maxNode + 1), (double)2));
        string input = "";
        int    z     = 0;

        while (z < 31)
        {
            tree.CurrentInput = z;
            writeTree(tree);
            Console.WriteLine("********************************************************************************");
            Console.WriteLine("Please enter a valid string of 2 characters for the node value:");
            while (!(isValidString(input)))
            {
                input = Console.ReadLine();
            }
            tree.updateNode(z, input);

            Console.Clear();
            input = "";
            z++;
        }

        tree.CurrentInput = -1;
        int indexA = tree.getIndexByValue(nodeA);
        int indexB = tree.getIndexByValue(nodeB);

        if (indexA < 0 || indexB < 0)
        {
            Console.Clear();
            Console.WriteLine("One or both of the provided nodes A and B were not found in the tree");
            return(1);
        }
        tree.NodeA_index = indexA;
        tree.NodeB_index = indexB;
        writeTree(tree);
        Console.WriteLine("Please press enter to find the lowest common parent of the 2 highlighted nodes");
        Console.ReadLine();

        tree.lowestCommonParent = tree.findCommonParent();
        Console.Clear();
        writeTree(tree);
        Console.ReadLine();

        return(1);
    }
Exemple #60
0
        private int[] NewBTreeNodeSizedArray(int value)
        {
            BTree btree = Btree();

            return(BTreeAssert.NewBTreeNodeSizedArray(btree, value));
        }