Esempio n. 1
0
        static void Main()
        {
            var tree = new Tree<int>();

            tree.Add(13);
            tree.Add(18);
            tree.Add(5);
            tree.Add(20);
            tree.Add(15);
            tree.Add(5);
            tree.Add(9);
            tree.Add(3);
            tree.Add(17);
            tree.Add(10);

            foreach (var item in tree)
            {
                Console.WriteLine("{0}", item);
            }

            tree.Remove(13);

            foreach (var item in tree)
            {
                Console.WriteLine("{0}", item);
            }
        }
Esempio n. 2
0
        public void AddingTwo_SmallerGoesToLeft()
        {
            var t = new Tree<int>();

            t.Add(23);
            t.Add(1);

            Assert.AreEqual(1, t.Root.Left.Item);
        }
Esempio n. 3
0
        public void AddingTwo_LargerGoesToRight()
        {
            var t = new Tree<int>();

            t.Add(23);
            t.Add(78);

            Assert.AreEqual(78, t.Root.Right.Item);
        }
Esempio n. 4
0
 public void Initialize()
 {
     tree = new Tree<int>();
     tree.Add(5);
     tree.Add(2);
     tree.Add(1);
     tree.Add(3);
     tree.Add(4);
 }
Esempio n. 5
0
        public void CheckUnderDirectoriesWithWildcard()
        {
            var tree = new Tree<bool>();
            tree.Add(@"C:\X", true);
            tree.Add(@"C:\X\*", false);

            Assert.IsTrue(tree.Under(@"C:\X"));
            Assert.IsFalse(tree.Under(@"C:\X\foo"));
            Assert.IsFalse(tree.Under(@"C:\X\1\foo"));
            Assert.IsFalse(tree.Under(@"D:\foo"));
        }
Esempio n. 6
0
        public void CheckUnderDirectories()
        {
            var tree = new Tree<bool>();
            tree.Add(@"C:\A\1", true);
            tree.Add(@"C:\A\2", true);
            tree.Add(@"C:\B", true);
            tree.Add(@"C:\B\1", false);

            Assert.IsTrue(tree.Under(@"C:\A\1\foo"));
            Assert.IsTrue(tree.Under(@"C:\B\2\foo"));
            Assert.IsTrue(tree.Under(@"C:\B"));
            Assert.IsFalse(tree.Under(@"C:\B\1\foo"));
            Assert.IsFalse(tree.Under(@"C:\C\foo"));
            Assert.IsFalse(tree.Under(@"D:\foo"));
        }
Esempio n. 7
0
        public Tree getTree( )
        {
            Tree tree = new Tree();

            tree.Key = "Header";
            {

                tree.Add("EngineVersion", this._EngineVersion);
                tree.Add("Owner", this._Owner);
                tree.Add("Version", this._Version);
                tree.Add("Time", this._Time);
                tree.Add("Title", this._Title);
            }

            return tree;
        }
Esempio n. 8
0
 public void ToString_ReturnsBFSString()
 {
     var tree = new Tree<int>();
     tree.Add(3).Add(2).Add(5).Add(4);
     var result = tree.ToString();
     Assert.AreEqual("3 2 5 4 ", result);
 }
Esempio n. 9
0
        static void Main()
        {
            Tree<int> tree = new Tree<int>(10);

            for (int i = 0; i < 20; i++)
            {
                if (i == 10) i++;
                tree.Add(i);
            }

            Console.WriteLine(tree);
            Console.WriteLine(tree.HasValue(15));
            Console.WriteLine(tree.HasValue(25));

            tree.Add(25);
            Console.WriteLine(tree);
            Console.WriteLine(tree.HasValue(25));
        }
Esempio n. 10
0
        public void CheckCaseSensitiveSentence()
        {
            var tree = new Tree<bool>(new char[] { ' ', ',', '.' }, StringComparer.Ordinal);
            tree.Add("The quick brown fox jumps.", true);

            Assert.IsTrue(tree.Under("The quick brown fox jumps over the lazy dog."));
            Assert.IsFalse(tree.Under("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."));
            Assert.IsFalse(tree.Under("A different sentence."));
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            var tree = new Tree<int>();
            tree.Add(30).Add(25).Add(36).Add(12).Add(5);
            Console.WriteLine($"There are {tree.Count} elements in the tree");
            ITreeBuilder<int> builder = new IntTreeBuilder();
            var largeTree = builder.Build(1000000);

            Console.WriteLine($"There are {largeTree.Count} elements in the large tree");
        }
Esempio n. 12
0
 void MakeRows(Tree<Cell> table)
 {
     do {
         var row = makeTreeCell(string.Empty);
         row.Value.SetAttribute(CellAttribute.StartTag, startTags[1]);
         row.Value.SetAttribute(CellAttribute.EndTag, endTags[1]);
         table.Add(row);
         MakeCells(row);
         if (scanner.Current.Type == TokenType.Newline) scanner.MoveNext();
     } while (scanner.Current.Type == TokenType.BeginCell || scanner.Current.Type == TokenType.Word);
 }
Esempio n. 13
0
        private static Tree BuildTree(IEnumerable<Type> types, string rootName)
        {
            var nodeFactory = new NodeFactory();
            var tree = new Tree(nodeFactory, rootName);

            foreach (var type in types)
            {
                var fullName = type.FullName;
                tree.Add(fullName);
            }
            return tree;
        }
Esempio n. 14
0
 public void EnumerateWithNoChildren()
 {
     var tree = new Tree<int>(7, EnumeratorOrder.DepthFirstSearch);
     Assert.AreEqual(7, tree.AsEnumerable().First());
     tree.Order = EnumeratorOrder.BreadthFirstSearch;
     Assert.AreEqual(7, tree.AsEnumerable().First());
     var subtree = new Tree<int>(5, EnumeratorOrder.BreadthFirstSearch);
     tree.Add(subtree);
     Assert.AreEqual(5, tree.AsEnumerable().Last());
     tree.Order = EnumeratorOrder.DepthFirstSearch;
     Assert.AreEqual(5, tree.AsEnumerable().Last());
 }
Esempio n. 15
0
        public void op_Add_Tree()
        {
            var obj = new Tree<int>();

            var expected = new Tree<int>();
            var actual = obj.Add(expected);

            Assert.Same(expected, actual);
            Assert.Same(obj, actual.Parent);
            Assert.Empty(actual);
            Assert.NotEmpty(obj);
            Assert.Equal(1, obj.Count);
        }
Esempio n. 16
0
        public void op_Add_T()
        {
            var obj = new Tree<string>();

            const string expected = "example";
            var actual = obj.Add(expected);

            Assert.Same(expected, actual.Value);
            Assert.Same(obj, actual.Parent);
            Assert.Empty(actual);
            Assert.NotEmpty(obj);
            Assert.Equal(1, obj.Count);
        }
Esempio n. 17
0
 void AddSurplusRow(object surplusValue, Tree<Cell> table) {
     var cells = new List<Tree<Cell>>();
     foreach (var actualValue in strategy.ActualValues(surplusValue)) {
         var cell = processor.Compose(actualValue.IsVoid ? new TypedValue(string.Empty) : actualValue);
         if (cells.Count == 0) {
             cell.Value.SetAttribute(CellAttribute.Label, "surplus");
         }
         cells.Add(cell);
     }
     var row = processor.MakeCell(string.Empty, "tr", cells);
     processor.TestStatus.MarkWrong(row.Value);
     table.Add(row);
 }
   private void AddSorterToTree(NodeSorter sorter, Tree.TreeNodeCollection parentCollection)
   {
      if (sorter == null)
         return;

      Tree.TreeNode tn = new Tree.TreeNode(this.GetSorterName(sorter));
      tn.Tag = sorter;
      tn.IsExpanded = true;

      this.treeNodes.Add(sorter, tn);

      parentCollection.Add(tn);
      this.AddSorterToTree(sorter.SecondarySorter, parentCollection);
   }
Esempio n. 19
0
        private static Tree<int> CreateTreeWithValues(int numberOfValues)
        {
            if (numberOfValues <= 0)
            {
                return null;
            }

            var tree = new Tree<int>(1);
            for (int i = 2; i <= numberOfValues; i++)
            {
                tree.Add(i);
            }

            return tree;
        }
Esempio n. 20
0
 void MakeCells(Tree<Cell> row)
 {
     while (scanner.Current.Type == TokenType.BeginCell || scanner.Current.Type == TokenType.Word) {
         var cell = makeTreeCell(scanner.Current.Content);
         cell.Value.SetAttribute(CellAttribute.StartTag, startTags[2]);
         cell.Value.SetAttribute(CellAttribute.EndTag, endTags[2]);
         if (scanner.Current.Type == TokenType.BeginCell) {
             MakeTables(cell);
         }
         else if (scanner.Current.Type == TokenType.Word) {
             cell.Value.SetAttribute(CellAttribute.Body, HttpUtility.HtmlEncode(scanner.Current.Content));
         }
         row.Add(cell);
         scanner.MoveNext();
     }
 }
Esempio n. 21
0
        public void DeleteLeaf_RightChild()
        {
            var t = new Tree<int>();
            t.Add(23);
            t.Add(20);
            t.Add(25);
            t.Add(24);
            t.Add(33);
            t.Add(10);
            t.Add(7);
            t.Add(8);

            t.Delete(33);

            Assert.AreEqual(23, t.Root.Item);
            Assert.AreEqual(20, t.Root.Left.Item);
            Assert.AreEqual(10, t.Root.Left.Left.Item);
            Assert.AreEqual(8, t.Root.Left.Left.Left.Right.Item);
            Assert.AreEqual(7, t.Root.Left.Left.Left.Item);
            Assert.AreEqual(25, t.Root.Right.Item);
            Assert.AreEqual(24, t.Root.Right.Left.Item);
            Assert.IsNull(t.Find(33));
        }
Esempio n. 22
0
    void Run()
    {
        Scanner input = new Scanner(Console.In);

        int N = input.NextInt();
        char[] op = new char[N];
        int[] arg = new int[N];
        List<int> keys = new List<int>();

        for (int i = 0; i < N; i++) {
            string s = input.Next();
            op[i] = char.ToUpper(s[0]);
            arg[i] = input.NextInt();

            if (op[i] == 'P')
                keys.Add(arg[i]);

            if (op[i] != 'P' && op[i] != 'G')
                throw new Exception();
        }

        Tree tree = new Tree(keys.ToArray());
        for (int i = 0; i < N; i++) {
            if (op[i] == 'P') {
                tree.Add(arg[i]);
            } else {
                try {
                    tree.Remove(tree.Find(arg[i]));
                } catch (Exception e) {}
            }
        }

        int[] res = tree.ToArray();
        foreach (int i in res)
            Console.WriteLine(i);

        if (res.Length == 0)
            Console.WriteLine("empty");
    }
Esempio n. 23
0
    void Solve()
    {
        var I = G();
        int N = I[0], a = I[1] - 1, b = I[2] - 1;
        var all = new Point[N];
        var rev = new Point[N];
        var ps  = new Tree();
        var qs  = new Tree();

        for (var i = 0; i < N; i++)
        {
            I = G();
            int x = I[0] + I[1], y = I[0] - I[1];
            ps.Add(all[i] = new Point(x, y, i));
            qs.Add(rev[i] = new Point(y, x, i));
        }
        var D  = all[a].Distance(all[b]);
        var s  = new HashSet <int>();
        var st = new Stack <int>();

        st.Push(a);
        Action <Point, Point, Tree, Tree> f1 = (f, t, p, q) => {
            while (true)
            {
                var l = p.LowerBound(f);
                if (l == null || l.Item.CompareTo(t) > 0)
                {
                    break;
                }
                if (!s.Contains(l.Item.I))
                {
                    st.Push(l.Item.I);
                }
                q.Remove(new Point(l.Item.Y, l.Item.X));
                p.Remove(l);
            }
        };

        while (st.Count > 0)
        {
            var i = st.Pop();
            if (s.Contains(i))
            {
                continue;
            }
            s.Add(i);
            var u = all[i];
            ps.Remove(u);
            qs.Remove(rev[i]);
            f1(new Point(u.X - D, u.Y - D), new Point(u.X - D, u.Y + D), ps, qs);
            f1(new Point(u.X + D, u.Y - D), new Point(u.X + D, u.Y + D), ps, qs);
            f1(new Point(u.Y - D, u.X - D), new Point(u.Y - D, u.X + D), qs, ps);
            f1(new Point(u.Y + D, u.X - D), new Point(u.Y + D, u.X + D), qs, ps);
        }
        var ind = s.ToList();

        ind.Sort();
        var M  = ind.Count;
        var px = new List <Point>();
        var qx = new List <Point>();

        foreach (var x in ind)
        {
            px.Add(all[x]);
        }
        foreach (var x in ind)
        {
            qx.Add(rev[x]);
        }
        px.Sort();
        qx.Sort();
        var ans = 0L;
        Action <Point, Point, List <Point> > f2 = (f, t, p) => {
            var l = FirstBinary(0, M, i => p[i].CompareTo(f) >= 0);
            var r = FirstBinary(0, M, i => p[i].CompareTo(t) >= 0);
            ans += r - l;
        };

        foreach (var u in px)
        {
            f2(new Point(u.X - D, u.Y - D), new Point(u.X - D, u.Y + D + 1), px);
            f2(new Point(u.X + D, u.Y - D), new Point(u.X + D, u.Y + D + 1), px);
            f2(new Point(u.Y - D, u.X - D + 1), new Point(u.Y - D, u.X + D), qx);
            f2(new Point(u.Y + D, u.X - D + 1), new Point(u.Y + D, u.X + D), qx);
        }
        WriteLine(ans / 2);
    }
Esempio n. 24
0
        public Tree <List <Line> > Build_CHT(List <Line> pe) // Построить дерево выпуклых фигур.
        {
            Tree <List <Line> > CHT = null;                  // голова дерева

            if (pe == null)                                  // пустая фигура
            {
                return(CHT);
            }
            if (pe.Capacity == 1) // одно ребро.
            {
                Tree <List <Line> > node = new Tree <List <Line> >(pe);
                CHT = node;
                return(CHT);
            }
            else
            {
                List <Point> CH = this.Build_Convex_Hull(pe); //convex hull
                //получаем che - convex hull edges(принадлежат CH).DONE

                //получаем dre - delta regions edges(не принадлежат CH).DONE

                //получаем dhp - delta&hull points - точки из dre, которые лежат на CH. DONE

                //ищем dr - отдельные наборы граней из dre. Включаем из dre пока не замкнемся,
                //либо пока не встретим новую точку из dhp. Тогда добавляем dr[i]. DONE

                //*Проходя вычеркиваем из dhp, dre пройденные точки, грани соответственно - ПРОВЕРЬ УПОРЯДОЧЕННОСТЬ ГРАНЕЙ*
                //Бежим по dre пока не обойдем все грани.
                List <Line>         CHE = null, DRE = null;
                List <Point>        DHP = null;
                List <List <Line> > DR  = null;

                //che
                //Тут подпрограмма должна быть:
                Point P_prev      = CH[0];
                Line  Line_to_add = null;
                foreach (Point P_next in CH)
                {
                    if (P_next == CH[0])
                    {
                        continue;
                    }
                    Line_to_add = new Line(P_prev, P_next);
                    P_prev      = P_next;
                    CHE.Add(Line_to_add);
                }
                //.
                //dre
                foreach (Line L1 in pe)
                {
                    foreach (Line L2 in CHE)
                    {
                        if (L1 == L2) // найти несовпадающие и записать в DRE
                        {
                            continue;
                        }
                        else
                        {
                            //Line to_add = new Line(L1.Beg, L1.End);
                            DRE.Add(L1);
                        }
                    }
                    //замыкаем дельта регион
                    Line to_close = new Line(DRE[0].Beg, DRE[DRE.Count - 1].End);
                    DRE.Add(to_close);
                }
                //dhp
                Point Point_to_add = new Point();
                foreach (Line L1 in DRE)
                {
                    foreach (Line L2 in CHE)
                    {
                        Point_to_add = get_lineIntersection(L1.Beg, L1.End, L2.Beg, L2.End); //попросить у Паши
                    }
                    if (Point_to_add != null)
                    {
                        DHP.Add(Point_to_add);
                    }
                }
                //dr
                List <Line> DR_to_add = null;
                foreach (Line L1 in DRE)
                {
                    DR_to_add.Add(L1);
                    foreach (Point P in DHP)
                    {
                        if (L1.End == P)
                        {
                            DR.Add(DR_to_add);
                            DR_to_add = null;
                        }
                    }
                }
                //.
                //List<Line> DR_i = null;
                foreach (List <Line> DR_i in DR)
                {
                    Tree <List <Line> > node = null;

                    node = this.Build_CHT(DR_i);
                    CHT.Add(node);
                }
            }
            return(CHT);
        }
Esempio n. 25
0
        public void After_backup_and_restore_recovery_must_not_throw_missing_journal_if_we_have_synced_everything()
        {
            RequireFileBasedPager();

            var r     = new Random(1); // we must use seed to ensure we always fill up the journal
            var bytes = new byte[512];

            for (int i = 0; i < 10; i++)
            {
                using (var tx = Env.WriteTransaction())
                {
                    Tree tree = tx.CreateTree("tree");

                    for (int j = 0; j < 100; j++)
                    {
                        r.NextBytes(bytes);
                        tree.Add(new string((char)j, 1000), bytes);
                    }

                    tx.Commit();
                }
            }

            Env.FlushLogToDataFile();

            for (int i = 0; i < 20; i++)
            {
                using (var tx = Env.WriteTransaction())
                {
                    Tree tree = tx.CreateTree("tree");

                    for (int j = 0; j < 100; j++)
                    {
                        r.NextBytes(bytes);
                        tree.Add(new string((char)j, 1000), bytes);
                    }

                    tx.Commit();
                }
            }

            // here we're filling up the last journal completely, we'll have Available4Kbs == 0 after the commit

            using (var tx = Env.WriteTransaction())
            {
                Tree tree = tx.CreateTree("tree");

                for (int j = 0; j < 226; j++)
                {
                    var specialBytes = new byte[1024];

                    r.NextBytes(specialBytes);
                    tree.Add(new string((char)j, 1000), specialBytes);
                }

                tx.Commit();
            }

            Env.FlushLogToDataFile();

            using (var operation = new WriteAheadJournal.JournalApplicator.SyncOperation(Env.Journal.Applicator))
            {
                var syncResult = operation.SyncDataFile();
            }

            var voronDataDir = new VoronPathSetting(DataDir);

            BackupMethods.Full.ToFile(Env, voronDataDir.Combine("voron-test.backup"));

            BackupMethods.Full.Restore(voronDataDir.Combine("voron-test.backup"), voronDataDir.Combine("backup-test.data"));

            var options = StorageEnvironmentOptions.ForPath(Path.Combine(DataDir, "backup-test.data"));

            options.MaxLogFileSize = Env.Options.MaxLogFileSize;

            using (var env = new StorageEnvironment(options))
            {
                using (var tx = env.ReadTransaction())
                {
                    using (var it = tx.ReadTree("tree").Iterate(prefetch: false))
                    {
                        Assert.True(it.Seek(Slices.BeforeAllKeys));

                        var count = 0;

                        do
                        {
                            count++;
                        } while (it.MoveNext());

                        Assert.Equal(226, count);
                    }
                }
            }
        }
Esempio n. 26
0
        public LevelDBBlockchain(string path)
        {
            header_index.Add(GenesisBlock.Hash);
            Version version;
            Slice   value;

            db = DB.Open(path, new Options {
                CreateIfMissing = true
            });
            if (db.TryGet(ReadOptions.Default, SliceBuilder.Begin(DataEntryPrefix.CFG_Version), out value) && Version.TryParse(value.ToString(), out version) && version >= Version.Parse("0.5"))
            {
                ReadOptions options = new ReadOptions {
                    FillCache = false
                };
                value = db.Get(options, SliceBuilder.Begin(DataEntryPrefix.SYS_CurrentBlock));
                this.current_block_hash   = new UInt256(value.ToArray().Take(32).ToArray());
                this.current_block_height = BitConverter.ToUInt32(value.ToArray(), 32);
                foreach (Block header in db.Find(options, SliceBuilder.Begin(DataEntryPrefix.DATA_HeaderList), (k, v) =>
                {
                    using (MemoryStream ms = new MemoryStream(v.ToArray(), false))
                        using (BinaryReader r = new BinaryReader(ms))
                        {
                            return(new
                            {
                                Index = BitConverter.ToUInt32(k.ToArray(), 1),
                                Headers = r.ReadSerializableArray <Block>()
                            });
                        }
                }).OrderBy(p => p.Index).SelectMany(p => p.Headers).ToArray())
                {
                    if (header.Hash != GenesisBlock.Hash)
                    {
                        header_chain.Add(header.Hash, header, header.PrevBlock);
                        header_index.Add(header.Hash);
                    }
                    stored_header_count++;
                }
                if (stored_header_count == 0)
                {
                    Dictionary <UInt256, Block> table = db.Find(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block), (k, v) => Block.FromTrimmedData(v.ToArray(), sizeof(long))).ToDictionary(p => p.PrevBlock);
                    for (UInt256 hash = GenesisBlock.Hash; hash != current_block_hash;)
                    {
                        Block header = table[hash];
                        header_chain.Add(header.Hash, header, header.PrevBlock);
                        header_index.Add(header.Hash);
                        hash = header.Hash;
                    }
                }
                else if (current_block_height >= stored_header_count)
                {
                    List <Block> list = new List <Block>();
                    for (UInt256 hash = current_block_hash; hash != header_index[(int)stored_header_count - 1];)
                    {
                        Block header = Block.FromTrimmedData(db.Get(options, SliceBuilder.Begin(DataEntryPrefix.DATA_Block).Add(hash)).ToArray(), sizeof(long));
                        list.Add(header);
                        header_index.Insert((int)stored_header_count, hash);
                        hash = header.PrevBlock;
                    }
                    for (int i = list.Count - 1; i >= 0; i--)
                    {
                        header_chain.Add(list[i].Hash, list[i], list[i].PrevBlock);
                    }
                }
                this.current_header_hash = header_index[header_index.Count - 1];
            }
            else
            {
                WriteBatch  batch   = new WriteBatch();
                ReadOptions options = new ReadOptions {
                    FillCache = false
                };
                using (Iterator it = db.NewIterator(options))
                {
                    for (it.SeekToFirst(); it.Valid(); it.Next())
                    {
                        batch.Delete(it.Key());
                    }
                }
                db.Write(WriteOptions.Default, batch);
                Persist(GenesisBlock);
                db.Put(WriteOptions.Default, SliceBuilder.Begin(DataEntryPrefix.CFG_Version), Assembly.GetExecutingAssembly().GetName().Version.ToString());
            }
            thread_persistence      = new Thread(PersistBlocks);
            thread_persistence.Name = "LevelDBBlockchain.PersistBlocks";
            thread_persistence.Start();
            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
        }
Esempio n. 27
0
 public virtual void Add(Slot slot)
 {
     _slots = ((TreeIntObject)Tree.Add(_slots, new TreeIntObject(slot.Address(), slot)
                                       ));
 }
        public Tree GetOperator(StreamReader stream, int?limitOperation = null)
        {
            var result     = new Tree();
            var symbol     = stream.Read();
            var buffer     = new StringBuilder(20);
            var limit      = limitOperation;
            var skipSymbol = new int[] { '\r', '\n', '\t', ' ' };
            var stopSymbol = new int[] { '\r', '\n', '\t', ' ', '(' };

            while (symbol >= 0 && symbol != '}')
            {
                if (buffer.Length == 0 && skipSymbol.Contains(symbol))
                {
                    symbol = stream.Read();
                    continue;
                }

                if (buffer.Length != 0 && symbol == ';')
                {
                    buffer.Clear();
                    symbol = stream.Read();
                    continue;
                }

                var curOperation = _operators.FirstOrDefault(it =>
                                                             it.Tag.Equals(((char)symbol).ToString(), StringComparison.CurrentCultureIgnoreCase));

                if (curOperation != null)
                {
                    var tree = curOperation.Process(buffer.ToString(), stream);
                    result.Add(tree);
                    buffer.Clear();
                    if (limit.HasValue)
                    {
                        if (limit == 1)
                        {
                            return(result);
                        }

                        limit = limit - 1;
                    }
                }
                else
                {
                    buffer.Append((char)symbol);
                    var next = stream.Peek();
                    if (!stopSymbol.Contains(next))
                    {
                        symbol = stream.Read();
                        continue;
                    }

                    var bufferTag = buffer.ToString().Trim();

                    curOperation = _operators.FirstOrDefault(it =>
                                                             it.Tag.Equals(bufferTag, StringComparison.CurrentCultureIgnoreCase));

                    if (curOperation != null)
                    {
                        var tree = curOperation.Process(buffer.ToString(), stream);
                        result.Add(tree);
                        buffer.Clear();
                        if (limit.HasValue)
                        {
                            if (limit == 1)
                            {
                                return(result);
                            }

                            limit = limit - 1;
                        }
                    }
                }
                symbol = stream.Read();
            }
            return(result);
        }
Esempio n. 29
0
        public VM()
        {
            Add = new DelegateCommand(() =>
            {
                Node <int> sni = Tree.Find(AddValue);
                if (sni == null)
                {
                    Tree.Add(AddValue);
                    UpdateItems();
                    RaisePropertyChanged("Items");
                }
                else
                {
                    string title   = "Information";
                    string message = AddValue + " already exists in tree";
                    MessageBox.Show(message, title);
                }
            });
            Delete = new DelegateCommand(() =>
            {
                Node <int> sni = Tree.Find(DeleteValue);
                if (sni != null)
                {
                    Tree.Remove(DeleteValue);
                    UpdateItems();
                    RaisePropertyChanged("Items");
                }
            });
            Find = new DelegateCommand(() =>
            {
                Node <int> sni = Tree.Find(FindValue);
                string title   = "Information";
                string message = null;
                if (sni != null)
                {
                    message = "Color of " + FindValue + " is " + sni.Color.ToString();
                }
                else
                {
                    message = FindValue + " not exists in tree";
                }
                MessageBox.Show(message, title);
            });
            Min = new DelegateCommand(() =>
            {
                int min        = int.MaxValue;
                Node <int> sni = Tree.Root;
                while (sni != null)
                {
                    min = sni.Data;
                    sni = (Node <int>)sni.Left;
                }
                string message = "Min value in tree is " + min;
                string title   = "Information";
                MessageBox.Show(message, title);
            });
            Max = new DelegateCommand(() =>
            {
                int max        = int.MinValue;
                Node <int> sni = Tree.Root;
                while (sni != null)
                {
                    max = sni.Data;
                    sni = (Node <int>)sni.Right;
                }
                string message = "Max value in tree is " + max;
                string title   = "Information";
                MessageBox.Show(message, title);
            });
            FindNext = new DelegateCommand(() =>
            {
                Node <int> sni = Tree.Find(FindNextValue);
                string message = null;
                string title   = "Information";
                if (sni != null)
                {
                    Node <int> next = (Node <int>)Tools.NextItem(sni);
                    if (next != null && next.Data != 0 && next.Color != Color.Header)
                    {
                        message = "Next after " + FindNextValue + " - " + next.Data + ", color - " + next.Color;
                    }
                    else
                    {
                        message = "Nothing after " + FindNextValue;
                    }
                }
                else
                {
                    message = FindNextValue + " not exist in tree";
                }
                MessageBox.Show(message, title);
            });
            FindPrev = new DelegateCommand(() =>
            {
                Node <int> sni = Tree.Find(FindPrevValue);
                string message = null;
                string title   = "Information";
                if (sni != null)
                {
                    Node <int> prev = (Node <int>)Tools.PreviousItem(sni);
                    if (prev != null && prev.Data != 0 && prev.Color != Color.Header)
                    {
                        message = "Prev before " + FindPrevValue + " - " + prev.Data + ", color - " + prev.Color;
                    }
                    else
                    {
                        message = "Nothing prev " + FindPrevValue;
                    }
                }
                else
                {
                    message = FindPrevValue + " not exist in tree";
                }
                MessageBox.Show(message, title);
            });
            Tree = new RedBlackTree <int>();

            List <int> list = new List <int>();
            Random     rnd  = new Random();

            for (int i = 0; i < 1; i++)
            {
                int a = rnd.Next(1, 100);
                if (!list.Contains(a))
                {
                    list.Add(a);
                    Tree.Add(a);
                }
            }
            UpdateItems();
        }
Esempio n. 30
0
 public void Add(TKey key, IEnumerable <TKey> sections, TValue value)
 {
     Tree.Add(key, sections, value);
 }
Esempio n. 31
0
        public static void Test()
        {
            var pool = new BufferPool();
            var tree = new Tree(pool, 128);

            const int leafCountAlongXAxis = 11;
            const int leafCountAlongYAxis = 13;
            const int leafCountAlongZAxis = 15;
            var       leafCount           = leafCountAlongXAxis * leafCountAlongYAxis * leafCountAlongZAxis;

            pool.Take <BoundingBox>(leafCount, out var leafBounds);

            const float boundsSpan    = 2;
            const float spanRange     = 2;
            const float boundsSpacing = 3;
            var         random        = new Random(5);

            for (int i = 0; i < leafCountAlongXAxis; ++i)
            {
                for (int j = 0; j < leafCountAlongYAxis; ++j)
                {
                    for (int k = 0; k < leafCountAlongZAxis; ++k)
                    {
                        var index = leafCountAlongXAxis * leafCountAlongYAxis * k + leafCountAlongXAxis * j + i;
                        leafBounds[index].Min = new Vector3(i, j, k) * boundsSpacing;
                        leafBounds[index].Max = leafBounds[index].Min + new Vector3(boundsSpan) +
                                                spanRange * new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble());
                    }
                }
            }

            var prebuiltCount = Math.Max(leafCount / 2, 1);

            tree.SweepBuild(pool, leafBounds.Slice(0, prebuiltCount));
            tree.Validate();


            for (int i = prebuiltCount; i < leafCount; ++i)
            {
                tree.Add(ref leafBounds[i], pool);
            }
            tree.Validate();

            pool.Take <int>(leafCount, out var handleToLeafIndex);
            pool.Take <int>(leafCount, out var leafIndexToHandle);
            for (int i = 0; i < leafCount; ++i)
            {
                handleToLeafIndex[i] = i;
                leafIndexToHandle[i] = i;
            }

            const int iterations = 100000;
            const int maximumChangesPerIteration = 20;

            var          threadDispatcher = new SimpleThreadDispatcher(Environment.ProcessorCount);
            var          refineContext    = new Tree.RefitAndRefineMultithreadedContext();
            var          selfTestContext  = new Tree.MultithreadedSelfTest <OverlapHandler>(pool);
            var          overlapHandlers  = new OverlapHandler[threadDispatcher.ThreadCount];
            Action <int> pairTestAction   = selfTestContext.PairTest;

            QuickList <int, Buffer <int> > .Create(pool.SpecializeFor <int>(), leafCount, out var removedLeafHandles);

            for (int i = 0; i < iterations; ++i)
            {
                var changeCount = random.Next(maximumChangesPerIteration);
                for (int j = 0; j <= changeCount; ++j)
                {
                    var addedFraction = tree.LeafCount / (float)leafCount;
                    if (random.NextDouble() < addedFraction)
                    {
                        //Remove a leaf.
                        var leafIndexToRemove = random.Next(tree.LeafCount);
                        var handleToRemove    = leafIndexToHandle[leafIndexToRemove];
                        var movedLeafIndex    = tree.RemoveAt(leafIndexToRemove);
                        if (movedLeafIndex >= 0)
                        {
                            var movedHandle = leafIndexToHandle[movedLeafIndex];
                            handleToLeafIndex[movedHandle]       = leafIndexToRemove;
                            leafIndexToHandle[leafIndexToRemove] = movedHandle;
                            leafIndexToHandle[movedLeafIndex]    = -1;
                        }
                        else
                        {
                            //The removed leaf was the last one. This leaf index is no longer associated with any existing leaf.
                            leafIndexToHandle[leafIndexToRemove] = -1;
                        }
                        handleToLeafIndex[handleToRemove] = -1;

                        removedLeafHandles.AddUnsafely(handleToRemove);

                        tree.Validate();
                    }
                    else
                    {
                        //Add a leaf.
                        var indexInRemovedList = random.Next(removedLeafHandles.Count);
                        var handleToAdd        = removedLeafHandles[indexInRemovedList];
                        removedLeafHandles.FastRemoveAt(indexInRemovedList);
                        var leafIndex = tree.Add(ref leafBounds[handleToAdd], pool);
                        leafIndexToHandle[leafIndex]   = handleToAdd;
                        handleToLeafIndex[handleToAdd] = leafIndex;

                        tree.Validate();
                    }
                }

                tree.Refit();
                tree.Validate();

                tree.RefitAndRefine(pool, i);
                tree.Validate();

                var handler = new OverlapHandler();
                tree.GetSelfOverlaps(ref handler);
                tree.Validate();

                refineContext.RefitAndRefine(ref tree, pool, threadDispatcher, i);
                tree.Validate();
                for (int k = 0; k < threadDispatcher.ThreadCount; ++k)
                {
                    overlapHandlers[k] = new OverlapHandler();
                }
                selfTestContext.PrepareJobs(ref tree, overlapHandlers, threadDispatcher.ThreadCount);
                threadDispatcher.DispatchWorkers(pairTestAction);
                selfTestContext.CompleteSelfTest();
                tree.Validate();

                if (i % 50 == 0)
                {
                    Console.WriteLine($"Cost: {tree.MeasureCostMetric()}");
                    Console.WriteLine($"Cache Quality: {tree.MeasureCacheQuality()}");
                    Console.WriteLine($"Overlap Count: {handler.OverlapCount}");
                }
            }

            threadDispatcher.Dispose();
            pool.Clear();
        }
Esempio n. 32
0
 public void Add(KeyValuePair <TKey, IDictionaryTreeNode <TKey, TValue> > item)
 {
     Tree.Add(item);
 }
Esempio n. 33
0
 public void Add(TKey key, TValue value)
 {
     Tree.Add(key, value);
 }
Esempio n. 34
0
 public virtual void EvictedFromCache(BTreeNode node)
 {
     _evictedFromCache = ((TreeIntObject)Tree.Add(_evictedFromCache, new TreeIntObject
                                                      (node.GetID(), node)));
 }
Esempio n. 35
0
 internal virtual void AddNode(BTreeNode node)
 {
     _nodes = (TreeIntObject)((TreeIntObject)Tree.Add(_nodes, new TreeIntObject(node.GetID
                                                                                    (), node)));
     AddToProcessing(node);
 }
Esempio n. 36
0
 public static Db4objects.Db4o.Internal.TreeInt Add(Db4objects.Db4o.Internal.TreeInt
                                                    tree, int value)
 {
     return((Db4objects.Db4o.Internal.TreeInt)((Db4objects.Db4o.Internal.TreeInt)Tree.
                                               Add(tree, new Db4objects.Db4o.Internal.TreeInt(value))));
 }
Esempio n. 37
0
 private void TreeViewLoaded()
 {
     tracer.GetImport().Log(TraceLevel.Verbose, "TreeView loading started");
     Tree.Add(assemblyMetadataView);
     tracer.GetImport().Log(TraceLevel.Verbose, "TreeView loading finished");
 }
Esempio n. 38
0
        public void NullKeyUnderThrows()
        {
            var tree = new Tree<bool>();
            tree.Add(@"C:\A", true);

            tree.Under(null);
        }
Esempio n. 39
0
    static void Main()
    {
        Node <int> root = new Node <int>(5);
        Tree <int> tree = new Tree <int>(root);

        tree.Add(new Node <int>(7));
        tree.Add(new Node <int>(1));
        tree.Add(new Node <int>(2));
        tree.Add(new Node <int>(9));
        tree.Add(new Node <int>(4));
        tree.Add(new Node <int>(8));
        tree.Add(new Node <int>(0));
        tree.Add(new Node <int>(11));
        tree.Add(new Node <int>(-3));
        tree.Add(new Node <int>(-6));
        tree.Add(new Node <int>(-5));
        tree.Add(new Node <int>(-8));
        tree.Add(new Node <int>(5));
        tree.Add(new Node <int>(12));

        tree.Print();
        var allPaths  = tree.FindAllPaths();
        int sumToLook = 41;

        Console.WriteLine("++++++++++++++++++++++++++++");
        Console.WriteLine("Paths with sum " + sumToLook);

        var allPathsWithSum = tree.FindAllPathsWithSum(sumToLook);

        foreach (var path in allPathsWithSum)
        {
            foreach (var item in path)
            {
                Console.Write(item.Value + " ");
            }

            Console.WriteLine();
        }
    }
Esempio n. 40
0
 internal virtual void AddClassStats(ClassUsageStats classStats
                                     )
 {
     _classUsageStats = ((TreeStringObject)Tree.Add(_classUsageStats, new TreeStringObject
                                                        (classStats.ClassName(), classStats)));
 }
Esempio n. 41
0
 public void Visit(int i)
 {
     treeInts.value = ((TreeInt)Tree.Add(((TreeInt)treeInts.value), new TreeInt(i)));
 }
Esempio n. 42
0
            static void ProcessFile(string fileName, Tree <string, string> root)
            {
                string baseName  = Path.GetFileNameWithoutExtension(fileName);
                string className = GetKey(baseName);

                if (className == null)
                {
                    return;
                }
                Console.WriteLine($"{Environment.NewLine}Processing file '{className}'...{Environment.NewLine}");

                if (!root.TryGetValue(className, out Tree <string, string> node))
                {
                    node = new Tree <string, string>(className, root.Comparer);
                    root.Add(node);
                }

                StreamReader reader    = null;
                CsvReader    csvReader = null;

                try
                {
                    reader    = new StreamReader(fileName ?? throw new ArgumentNullException(nameof(fileName)), Encoding.UTF8);
                    csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);

                    while (csvReader.Read())
                    {
                        string entry   = csvReader.GetField(0);
                        string fullKey = GetKey(entry);
                        if (fullKey == null)
                        {
                            continue;
                        }
                        string value = csvReader.GetField(1).ToNullIfEmpty() ?? $"{baseName}/{entry}";

                        if (!fullKey.Contains('.'))
                        {
                            if (!node.TryGetValue(fullKey, out Tree <string, string> item))
                            {
                                item = new Tree <string, string>(fullKey, node.Comparer)
                                {
                                    Value = value
                                };

                                node.Add(item);
                            }
                        }
                        else
                        {
                            string[] keys = fullKey.Split(StringSplitOptions.RemoveEmptyEntries, '.');
                            Tree <string, string> current = node;

                            for (int i = 0; i < keys.Length; i++)
                            {
                                string key = keys[i];

                                if (!current.TryGetValue(key, out Tree <string, string> item))
                                {
                                    item = new Tree <string, string>(key, current.Comparer);
                                    current.Add(item);
                                }

                                if (i == keys.Length - 1)
                                {
                                    item.Value = value;
                                }
                                current = item;
                            }
                        }

                        Console.WriteLine($"{entry} => {fullKey} = '{value}'");
                    }
                }
                finally
                {
                    ObjectHelper.Dispose(ref csvReader);
                    ObjectHelper.Dispose(ref reader);
                }
            }
Esempio n. 43
0
 public static Db4objects.Db4o.Internal.TreeIntObject Add(Db4objects.Db4o.Internal.TreeIntObject
                                                          tree, int key, object value)
 {
     return((Db4objects.Db4o.Internal.TreeIntObject)Tree.Add(tree, new Db4objects.Db4o.Internal.TreeIntObject
                                                                 (key, value)));
 }
Esempio n. 44
0
 public void Add(TreeInt node)
 {
     tree = (TreeInt)((TreeInt)Tree.Add(tree, node));
 }
Esempio n. 45
0
 public virtual void AddId(int id)
 {
     _ids = (TreeInt)Tree.Add(_ids, new TreeInt(id));
 }
Esempio n. 46
0
 protected override void MapNonClassIDs(int origID, int mappedID)
 {
     _tree = Tree.Add(_tree, new TreeIntObject(origID, mappedID));
 }
Esempio n. 47
0
    static void Main()
    {
        Node <int> root = new Node <int>(5);
        Tree <int> tree = new Tree <int>(root);

        tree.Add(new Node <int>(7));
        tree.Add(new Node <int>(1));
        tree.Add(new Node <int>(2));
        tree.Add(new Node <int>(9));
        tree.Add(new Node <int>(4));
        tree.Add(new Node <int>(8));
        tree.Add(new Node <int>(0));
        tree.Add(new Node <int>(11));
        tree.Add(new Node <int>(-3));
        tree.Add(new Node <int>(-6));
        tree.Add(new Node <int>(-5));
        tree.Add(new Node <int>(-8));
        tree.Add(new Node <int>(5));
        tree.Add(new Node <int>(12));

        tree.Print();
        tree.FindLongestPath();
        //var allPaths = tree.FindAllPaths();
        //Console.WriteLine(allPaths.Count);

        //foreach (var path in allPaths)
        //{
        //    foreach (var item in path)
        //    {
        //        Console.Write(item.Value + " ");
        //    }

        //    Console.WriteLine();
        //}
    }
Esempio n. 48
0
    static void Main()
    {
        Node <int> root = new Node <int>(5);
        Tree <int> tree = new Tree <int>(root);

        tree.Add(new Node <int>(7));
        tree.Add(new Node <int>(1));
        tree.Add(new Node <int>(2));
        tree.Add(new Node <int>(9));
        tree.Add(new Node <int>(4));
        tree.Add(new Node <int>(8));
        tree.Add(new Node <int>(0));
        tree.Add(new Node <int>(11));
        tree.Add(new Node <int>(-3));
        tree.Add(new Node <int>(-6));
        tree.Add(new Node <int>(-5));
        tree.Add(new Node <int>(-8));
        tree.Add(new Node <int>(5));
        tree.Add(new Node <int>(12));

        tree.Print();
        tree.FindLongestPath();

        Console.WriteLine("++++++++++++++++++++++++++++");

        var allSubTreessWithSum = tree.FindSubtreesWithSum(-10);

        foreach (var subTree in allSubTreessWithSum)
        {
            subTree.Print();
        }
    }
Esempio n. 49
0
        public void PopulateTables()
        {
            var tablesNode = new TreeViewItem {
                Header = "Tables"
            };

            tablesNode.Selected += OnTreeViewItemSelected;
            tablesNode.ExpandSubtree();

            foreach (var item in database.Tables)
            {
                var table = new TreeViewItem {
                    Header = item.DisplayName, Tag = item                            /*, FontWeight = FontWeights.Bold*/
                };
                table.Selected += OnTreeViewItemSelected;
                //table.ExpandSubtree();
                tablesNode.Items.Add(table);

                var columns = new TreeViewItem {
                    Header = "Columns", FontWeight = FontWeights.Normal
                };
                //columns.ExpandSubtree();
                table.Items.Add(columns);

                foreach (var column in item.Columns)
                {
                    var columnNode = new TreeViewItem();
                    columnNode.Selected += OnTreeViewItemSelected;
                    columnNode.Header    = column.Value.DisplayName;
                    //columnNode.Tag = new KeyValuePair<string, string>(item.Name, column.Value.Name);
                    if (column.Value.IsPrimaryKey)
                    {
                        columnNode.Items.Add("Primary Key");
                    }
                    if (column.Value.IdentitySeed.HasValue)
                    {
                        columnNode.Items.Add("Identity Seed: " + column.Value.IdentitySeed.GetValueOrDefault(1));
                    }
                    if (column.Value.IdentityIncrement.HasValue)
                    {
                        columnNode.Items.Add("Identity Increment: " + column.Value.IdentityIncrement.GetValueOrDefault(1));
                    }
                    if (column.Value.IsForeignKey)
                    {
                        columnNode.Items.Add("Foreign Key");
                    }
                    columnNode.Items.Add("Ordinal Position:  " + column.Value.Ordinal);
                    columnNode.Items.Add(new TreeViewItem {
                        Header = "Database Type:  " + column.Value.DatabaseType
                    });
                    columnNode.Items.Add(new TreeViewItem {
                        Header = ".NET CLR Type:  " + column.Value.ManagedType
                    });
                    columnNode.Items.Add(new TreeViewItem {
                        Header = "Allows Null:  " + column.Value.AllowsNull
                    });
                    if (column.Value.ManagedType == typeof(string))
                    {
                        columnNode.Items.Add("Max Length:  " + column.Value.MaxLength);
                    }
                    columns.Items.Add(columnNode);
                }

                var indexes = new TreeViewItem {
                    Header = "Indexes", FontWeight = FontWeights.Normal
                };
                table.Items.Add(indexes);

                if (item.Indexes != null)
                {
                    foreach (var index in item.Indexes)
                    {
                        var indexNode = new TreeViewItem {
                            Header = index.Name
                        };
                        indexNode.Items.Add(new TreeViewItem {
                            Header = "Column:  " + index.Column.DisplayName
                        });
                        indexNode.Items.Add(new TreeViewItem {
                            Header = "Unique:  " + index.Unique
                        });
                        indexNode.Items.Add(new TreeViewItem {
                            Header = "Clustered:  " + index.Clustered
                        });
                        indexes.Items.Add(indexNode);
                    }
                }
            }

            if (Tree == null)
            {
                Tree = new ObservableCollection <TreeViewItem>();
            }

            Tree.Clear();
            Tree.Add(GetDatabaseInformationTree());
            Tree.Add(tablesNode);
            RaisePropertyChanged("Tree");
        }
Esempio n. 50
0
 void AddCell(Tree<Cell> row, object theNewValue)
 {
     row.Add(Processor.Compose(theNewValue));
 }
Esempio n. 51
0
 public void OrderPropertyValidation()
 {
     var subtree = new Tree<int>(5, EnumeratorOrder.DepthFirstSearch) { 1, 2 };
     var tree = new Tree<int>(7, EnumeratorOrder.BreadthFirstSearch);
     tree.Add(subtree);
     Assert.AreEqual(EnumeratorOrder.BreadthFirstSearch, subtree.Order);
     foreach (Tree<int> child in subtree.Children)
     {
         Assert.AreEqual(EnumeratorOrder.BreadthFirstSearch, child.Order);
     }
     subtree.Add(3);
     Assert.AreEqual(EnumeratorOrder.BreadthFirstSearch, subtree.Children.First(c => c.Value == 3).Order);
     tree.Order = EnumeratorOrder.DepthFirstSearch;
     subtree.Add(4);
     Assert.AreEqual(EnumeratorOrder.DepthFirstSearch, subtree.Children.First(c => c.Value == 4).Order);
     try
     {
         tree.Order = (EnumeratorOrder)123;
         Assert.Fail("Unknown order type defined.");
     }
     catch (ArgumentOutOfRangeException)
     {
     }
     catch (Exception)
     {
         Assert.Fail("Invalid exception type.");
     }
 }
        static void Main()
        {
            //Console.WriteLine("Enter number of nodes: ");
            //var numberOfNodes = int.Parse(Console.ReadLine());

            //for (int i = 0, len = numberOfNodes; i < len; i++)
            //{
            //    Console.WriteLine("Parent: ");
            //    var key = int.Parse(Console.ReadLine());
            //    Console.WriteLine("Child: ");
            //    var value = int.Parse(Console.ReadLine());
            //    nodes.Add(key, value);
            //}

            var parents = new List<int>();
            var children = new List<int>();
            parents.Add(2);
            children.Add(4);

            parents.Add(3);
            children.Add(2);

            parents.Add(5);
            children.Add(0);

            parents.Add(3);
            children.Add(5);

            parents.Add(5);
            children.Add(6);

            parents.Add(5);
            children.Add(1);

            parents.Add(4);
            children.Add(7);

            var tree = new Tree<int>();

            while (parents.Count > 0)
            {
                var rootElements = GetTopParentNodes(parents, children);

                foreach (var root in rootElements)
                {
                    Console.WriteLine(root);
                    var rootChildren = GetChildrenOf(root, parents, children);
                    foreach (var child in rootChildren)
                    {
                        tree.Add(root, child);
                    }

                    var index = 0;
                    while (parents.Contains(root))
                    {
                        parents.Remove(root);
                        children.Remove(rootChildren[index]);
                        index++;
                    }
                }
            }
            // TO DO:
            // get the root - add HasPerant prop
            // each element
            // middle nodes = as of row? - add counter, when end is reached traverse till end/2 - cycle
            // traverse through tree with counter depth, save it, and if any deeper branch is found, replace the saved one
            Console.WriteLine();
        }
Esempio n. 53
0
        public override void MapId(int id, Slot slot)
        {
            var idSlotMapping = new IdSlotTree(id, slot);

            _idsToSlots = ((IdSlotTree)Tree.Add(_idsToSlots, idSlotMapping));
        }
Esempio n. 54
0
    static void Main()
    {
        Node<int> root = new Node<int>(5);
        Tree<int> tree = new Tree<int>(root);

        tree.Add(new Node<int>(7));
        tree.Add(new Node<int>(1));
        tree.Add(new Node<int>(2));
        tree.Add(new Node<int>(9));
        tree.Add(new Node<int>(4));
        tree.Add(new Node<int>(8));
        tree.Add(new Node<int>(0));
        tree.Add(new Node<int>(11));
        tree.Add(new Node<int>(-3));
        tree.Add(new Node<int>(-6));
        tree.Add(new Node<int>(-5));
        tree.Add(new Node<int>(-8));
        tree.Add(new Node<int>(5));
        tree.Add(new Node<int>(12));

        tree.Print();
        var allPaths = tree.FindAllPaths();
        int sumToLook = 41;

        Console.WriteLine("++++++++++++++++++++++++++++");
        Console.WriteLine("Paths with sum "+sumToLook);

        var allPathsWithSum = tree.FindAllPathsWithSum(sumToLook);

        foreach (var path in allPathsWithSum)
        {
            foreach (var item in path)
            {
                Console.Write(item.Value + " ");
            }

            Console.WriteLine();
        }
    }
Esempio n. 55
0
    static void Main()
    {
        Node<int> root = new Node<int>(5);
        Tree<int> tree = new Tree<int>(root);

        tree.Add(new Node<int>(7));
        tree.Add(new Node<int>(1));
        tree.Add(new Node<int>(2));
        tree.Add(new Node<int>(9));
        tree.Add(new Node<int>(4));
        tree.Add(new Node<int>(8));
        tree.Add(new Node<int>(0));
        tree.Add(new Node<int>(11));
        tree.Add(new Node<int>(-3));
        tree.Add(new Node<int>(-6));
        tree.Add(new Node<int>(-5));
        tree.Add(new Node<int>(-8));
        tree.Add(new Node<int>(5));
        tree.Add(new Node<int>(12));

        tree.Print();
        tree.FindLongestPath();

        Console.WriteLine("++++++++++++++++++++++++++++");

        var allSubTreessWithSum = tree.FindSubtreesWithSum(-10);

        foreach (var subTree in allSubTreessWithSum)
        {
            subTree.Print();
        }
    }
Esempio n. 56
0
   private void AddFilterToTree(Filter<IMaxNode> filter, Tree.TreeNodeCollection parentCollection)
   {
      filter.FilterChanged += filterChanged;

      Tree.TreeNode tn = new Tree.TreeNode();
      tn.Text = GetTreeNodeText(filter, tn);
      tn.Tag = filter;

      this.treeNodes.Add(filter, tn);

      FilterCombinator<IMaxNode> combinator = filter as FilterCombinator<IMaxNode>;
      if (combinator != null)
      {
         foreach (Filter<IMaxNode> child in combinator.Filters)
         {
            this.AddFilterToTree(child, tn.Nodes);
         }
         combinator.Filters.FilterAdded += this.filterAdded;
         combinator.Filters.FilterRemoved += this.filterRemoved;
         tn.DragDropHandler = new FilterCombinatorDragDropHandler(combinator);
      }
      else
         tn.DragDropHandler = new FilterDragDropHandler(filter);

      parentCollection.Add(tn);
   }
Esempio n. 57
0
 public virtual void Add(Tree tree)
 {
     Changed();
     _tree = _tree == null ? tree : _tree.Add(tree);
 }
Esempio n. 58
0
        //this code is built on top of this solution: https://leetcode.com/discuss/interview-question/347457/Amazon-or-OA-2019-or-Treasure-Island/317634
        internal static LinkedList <Point> FindShortestDistance(char[][] matrix)
        {
            if (matrix == null || matrix.Length == 0)
            {
                return(null);
            }
            int steps = 0;
            //in BFS nodes are queued, unlike the DFS algorithm which uses stack
            Queue <Point> queue = new Queue <Point>();

            //we need to mark every visited nodes, so we don't scan it again
            bool[,] visited = new bool[matrix.Length, matrix[0].Length];
            //this tree is to represent the solution in a parent-child relationship to be able to get the route
            //BFS doesn't know which nodes led to the target one, it only can help count levels until the goal is reached
            Tree <Point> tree = new Tree <Point>();

            LinkedList <Point> route = new LinkedList <Point>();
            TreeNode <Point>   goal  = null;
            var head = new Point(0, 0);

            queue.Enqueue(head);
            visited[0, 0] = true;
            //down,up,right,left ({row, column})
            int[][] dirs = new int[][] { new[] { 1, 0 }, new[] { -1, 0 }, new[] { 0, 1 }, new[] { 0, -1 } };
            //on every node visited, we save it in this HashSet, every node becomes a potential parent for the next iteration's nodes, so we need to register these relations
            HashSet <TreeNode <Point> > parentsCache = new HashSet <TreeNode <Point> >();

            //BFS
            while (queue.Count != 0)
            {
                int size = queue.Count;
                for (int i = 0; i < size; i++)
                {
                    Point            point = queue.Dequeue();
                    TreeNode <Point> parent;
                    if (tree.Root == null)
                    {
                        parent = tree.Add(point);
                    }
                    else
                    {
                        parent = tree.Last;
                    }
                    int x = point.R;
                    int y = point.C;
                    if (matrix[x][y] == 'X')
                    {
                        var curr = goal;
                        while (curr != null)
                        {
                            route.AddFirst(curr.Value);
                            curr = curr.Parents.First();
                        }
                        return(route);
                    }

                    foreach (int[] dir in dirs)
                    {
                        int newX = x + dir[0];
                        int newY = y + dir[1];
                        //findng the available unvisited direction
                        if (newX >= 0 && newX < matrix.Length && newY >= 0 && newY < matrix[0].Length &&
                            matrix[newX][newY] != 'D' && !visited[newX, newY])
                        {
                            var child = new Point(newX, newY);
                            queue.Enqueue(child);

                            var parents = parentsCache.Where(p => p.Value.IsParentTo(child));
                            TreeNode <Point> node;


                            if (parents != null && parents.Count() > 0)
                            {
                                node = tree.AddMultiParent(child, parents.ToList());
                            }
                            else
                            {
                                node = tree.Add(child, parent);
                            }
                            if (matrix[newX][newY] == 'X')
                            {
                                goal = node;
                            }
                            parentsCache.Add(node);
                            visited[newX, newY] = true;
                        }
                    }
                }
                steps++;
            }
            return(null);
        }
Esempio n. 59
0
 public void Add(TKey key, TValue value, params TKey[] sections)
 {
     Tree.Add(key, value, sections);
 }
Esempio n. 60
0
 public void AddNullKeyThrows()
 {
     var tree = new Tree<bool>();
     tree.Add(null, true);
 }