コード例 #1
0
        public void LevelOrderTest(int treeIndex, string expected)
        {
            var    tree   = _trees[treeIndex];
            string result = string.Join(",", Traversals.LevelOrder(tree[0], tree.GetChildren).Select(node => node.ToString()));

            Assert.AreEqual(expected, result);
        }
コード例 #2
0
        //static void Main(string[] args)
        //     {

        //         var root = new TreeNode<int>(4);
        //         root.left = new TreeNode<int>(2);
        //         root.right = new TreeNode<int>(7);
        //         root.left.left = new TreeNode<int>(1);
        //         root.left.right = new TreeNode<int>(3);
        //         root.right.left = new TreeNode<int>(6);
        //         root.right.right = new TreeNode<int>(9);

        //DFSTraverse(root, Traversals.PreOrder);
        //}

        public static void DFSTraverse(TreeNode <int> node, Traversals type)
        {
            if (node == null)
            {
                return;
            }
            switch (type)
            {
            case Traversals.PreOrder:
                Console.WriteLine(node.data);
                DFSTraverse(node.left, Traversals.PreOrder);
                DFSTraverse(node.right, Traversals.PreOrder);
                Console.WriteLine(node.data.ToString() + " Done");
                break;

            case Traversals.InOrder:
                DFSTraverse(node.left, Traversals.InOrder);
                Console.WriteLine(node.data);
                DFSTraverse(node.right, Traversals.InOrder);
                break;

            case Traversals.PostOrder:
                DFSTraverse(node.left, Traversals.PostOrder);
                DFSTraverse(node.right, Traversals.PostOrder);
                Console.WriteLine(node.data);
                break;

            default:
                break;
            }
        }
コード例 #3
0
        public void StatelessInOrderTest(int treeIndex, string expected)
        {
            BinaryNode[] tree   = _trees[treeIndex];
            string       result = string.Join(",", Traversals.StatelessInOrder(tree[0], tree.GetLeft, tree.GetRight, tree.GetParent).Select(node => node.ToString()));

            Assert.AreEqual(expected, result);
        }
コード例 #4
0
    internal static PredictedMove CalculateMove(int size, PredictedMove previousMove, Direction direction)
    {
        int      score        = (int)previousMove.NewScore;
        Grid2048 previousGrid = new Grid2048(previousMove.Grid);

        bool moved = false;

        Coord   cell;
        DigTile tile;

        Coord      vector     = GetDirectionalOffset(direction);
        Traversals traversals = Traversals.BuildTraversals(size, vector);

        foreach (int x in traversals.x)
        {
            foreach (int y in traversals.y)
            {
                cell = new Coord(x, y);
                tile = previousGrid.CellContent(cell);

                if (tile != null)
                {
                    FarthestPosition positions = FindFarthestPosition(previousGrid, cell, vector);
                    DigTile          next      = previousGrid.CellContent(positions.Next);

                    if (next != null && next.Value == tile.Value && next.MergedFrom == null)
                    {
                        DigTile merged = new DigTile(positions.Next, tile.Value * 2)
                        {
                            MergedFrom = new List <DigTile> {
                                tile, next
                            }
                        };

                        previousGrid.InsertTile(merged);
                        previousGrid.RemoveTile(tile);

                        tile.UpdatePosition(positions.Next);

                        score += merged.Value;
                    }
                    else
                    {
                        MoveTile(previousGrid, tile, positions.Farthest);
                    }

                    if (!PositionsEqual(cell, tile))
                    {
                        moved = true;
                    }
                }
            }
        }

        return(new PredictedMove(moved ? score : -1, previousGrid, direction));
    }
コード例 #5
0
        char GetRandomNode(Node root)
        {
            string traversalString = string.Empty;

            traversalString = Traversals.InOrder(root, traversalString);

            Random rnd          = new Random();
            int    randomNumber = rnd.Next(0, traversalString.Length);

            return(traversalString[randomNumber]);
        }
コード例 #6
0
 public TransactionContextState GetExpectedCommitState()
 {
     if (Traversals.LevelOrder(this.GetController(), node => node.Children.Where(child => !child.IsController)).All(node => node.VoteAction == VoteAction.VoteCommit))
     {
         return(TransactionContextState.ToBeCommitted);
     }
     else
     {
         return(TransactionContextState.ToBeRollbacked);
     }
 }
コード例 #7
0
ファイル: TTraversals.cs プロジェクト: inthefabric/Weaver
        public void GetNameOfGrandchildOfSaturn()
        {
            //saturn.in('father').in('father').name

            var v = new WeaverVarAlias <Character>("saturn");

            IWeaverQuery q = Traversals.GetGrandchildOfCharacter(v)
                             .Property(x => x.Name)
                             .ToQuery();

            string expectScript = "saturn.inE('father').outV.inE('father').outV.property('name');";

            Assert.AreEqual(expectScript, q.Script, "Incorrect script.");
        }
コード例 #8
0
ファイル: TTraversals.cs プロジェクト: inthefabric/Weaver
        public void GetSaturn()
        {
            //saturn = g.V('name','saturn').next()

            IWeaverVarAlias <Examples.Core.Vertices.Titan> v;

            IWeaverQuery q = Traversals.GetCharacterByName <Examples.Core.Vertices.Titan>(
                "saturn", "saturn", out v);

            string expectScript = "saturn=g.V('name',_P0).next();";

            Assert.AreEqual(expectScript, q.Script, "Incorrect script.");
            Assert.AreEqual("saturn", v.Name, "Incorrect Alias.Name.");

            var expectParams = new Dictionary <string, IWeaverQueryVal>();

            expectParams.Add("_P0", new WeaverQueryVal("saturn"));
            WeaverTestUtil.CheckQueryParamsOriginalVal(q, expectParams);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: agao2/MyDataStructures
        static void Main(string[] args)
        {
            Graph g = new Graph();

            g.AddVertex("0");
            g.AddVertex("1");
            g.AddVertex("2");
            g.AddVertex("3");


            g.AddEdge("0", "1");
            g.AddEdge("0", "2");
            g.AddEdge("1", "2");
            g.AddEdge("2", "3");
            g.AddEdge("3", "3");

            //Traversals.DFS(g,"2");
            Traversals.BFS(g, "2");
        }
コード例 #10
0
        public List <T> ToList(Traversals traver)
        {
            List <T> result = new List <T>();

            switch (traver)
            {
            case Traversals.PreOrderTraversal:
                PreOrderTraversal(result.Add);
                break;

            case Traversals.InOrderTraversal:
                InOrderTraversal(result.Add);
                break;

            case Traversals.PostOrderTraversal:
                PostOrderTraversal(result.Add);
                break;
            }

            return(result);
        }
コード例 #11
0
        bool isSubTreeUsingStringComparison(Node bigTree, Node smallTree)
        {
            string bigTreePreOrderString = string.Empty;

            bigTreePreOrderString = Traversals.PreOrderWithNulls(bigTree, bigTreePreOrderString);

            string bigTreeInOrderString = string.Empty;

            bigTreeInOrderString = Traversals.InOrderWithNulls(bigTree, bigTreeInOrderString);

            string smallTreePreOrderString = string.Empty;

            smallTreePreOrderString = Traversals.PreOrderWithNulls(smallTree, smallTreePreOrderString);

            string smallTreeInOrderString = string.Empty;

            smallTreeInOrderString = Traversals.InOrderWithNulls(smallTree, smallTreeInOrderString);

            return(bigTreeInOrderString.Contains(smallTreeInOrderString) &&
                   bigTreePreOrderString.Contains(smallTreePreOrderString));
        }
コード例 #12
0
        public static Traversals BuildTraversals(int size, Coord vector)
        {
            Traversals traversals = new Traversals();

            for (int pos = 0; pos < size; pos++)
            {
                traversals.x.Add(pos);
                traversals.y.Add(pos);
            }

            if (vector.x > 0)
            {
                traversals.x.Reverse();
            }
            if (vector.y > 0)
            {
                traversals.y.Reverse();
            }

            return(traversals);
        }
コード例 #13
0
        public static IEnumerable <string> EnumerateDirectories(string path, string searchPattern = "*.*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (string.IsNullOrEmpty(searchPattern))
            {
                throw new ArgumentNullException(nameof(searchPattern));
            }

            Func <string, IEnumerable <string> > getChildren =
                child => SafeGetFileSystemEnumerable(() => Directory.EnumerateDirectories(child, searchPattern, SearchOption.TopDirectoryOnly));

            if (searchOption == SearchOption.TopDirectoryOnly)
            {
                return(getChildren(path));
            }
            else
            {
                return(Traversals.LevelOrder(path, getChildren));
            }
        }
コード例 #14
0
        public static void Main(string[] args)
        {
            System.Console.WriteLine("LinkList Sample");

            SinglyLinkedList <int> primeNumbers = new SinglyLinkedList <int>();

            // first we'll add the middle element. Then try the AddToFront with 3 and then try the AddToBack with 7
            // generating the final sequence as 3, 5, 7

            primeNumbers.AddToFront(5);
            primeNumbers.AddToFront(3);
            primeNumbers.AddToBack(7);
            primeNumbers.AddToBack(9);
            primeNumbers.AddToBack(8);
            primeNumbers.AddToBack(7);
            primeNumbers.Remove(8);
            primeNumbers.RemoveLast();

            PrintHelpers.PrintFromNode(primeNumbers.Head);


            System.Console.WriteLine("Stack Sample: ");

            PostfixCalculator postfixCalculator = new PostfixCalculator();
            int result = postfixCalculator.calculate("5 6 7 * + 1 -");

            System.Console.WriteLine($"The postfix expression result is: {result}");


            System.Console.WriteLine("Binary Search Tree Sample:");

            BinaryTree <int> binaryTree = new BinaryTree <int>();

            binaryTree.Add(3);
            binaryTree.Add(7);
            binaryTree.Add(5);
            binaryTree.Add(4);
            binaryTree.Add(6);
            binaryTree.Add(8);
            binaryTree.Add(11);
            binaryTree.Add(1);

            System.Console.WriteLine($"Contains 5: {binaryTree.Contains(5)}");
            System.Console.WriteLine($"Contains 6: {binaryTree.Contains(6)}");
            System.Console.WriteLine($"Contains 1: {binaryTree.Contains(1)}");

            System.Console.WriteLine($"Remove 9 op result: {binaryTree.Remove(9)}");
            System.Console.WriteLine($"Remove 7 op result: {binaryTree.Remove(7)}");

            System.Console.WriteLine("Traversal Outputs:");

            Traversals <int> traversals = new Traversals <int>();

            IReadOnlyCollection <int> preOrder  = traversals.PreorderTraversal(binaryTree);
            IReadOnlyCollection <int> inOrder   = traversals.InorderTraversal(binaryTree);
            IReadOnlyCollection <int> postOrder = traversals.PostorderTraversal(binaryTree);

            System.Console.WriteLine($"Postorder: {string.Join(", ", preOrder)}");
            System.Console.WriteLine($"Inorder: {string.Join(", ", inOrder)}");
            System.Console.WriteLine($"Postorder: {string.Join(", ", postOrder)}");
        }
コード例 #15
0
ファイル: BinaryTree.cs プロジェクト: davemk99/binarytree
 public BinaryTree()
 {
     this.Root      = null;
     this.Traversal = Traversals.PreOrderTraversal;
 }
コード例 #16
0
        // Move tiles on the grid in the specified direction
        private void InternalMove(MoveDirection direction)
        {
            if (IsGameTerminated())
            {
                return;                     // Don't do anything if the game's over
            }
            GameTile tile = null;

            var vector     = GetVector(direction);
            var traversals = new Traversals(_size, vector);
            var moved      = false;

            // Save the current tile positions and remove merger information
            PrepareTiles();

            // Traverse the grid in the right direction and move tiles
            foreach (var x in traversals.Xs)
            {
                foreach (var y in traversals.Ys)
                {
                    var cell = new CellPosition(x, y);
                    tile = _grid.CellContent(cell);

                    if (null != tile)
                    {
                        var positions = FindFarthestPosition(cell, vector);
                        var next      = _grid.CellContent(positions.Next);

                        // Only one merger per row traversal?
                        if (null != next && next.Value == tile.Value && (null == next.MergedFrom))
                        {
                            var merged = new GameTile(positions.Next, tile.Value * 2);
                            merged.MergedFrom = new MergeTile(tile.Position, next.Position);

                            _grid.InsertTile(merged);
                            _grid.RemoveTile(tile);

                            // Converge the two tiles' positions
                            tile.UpdatePosition(positions.Next);

                            // Update the score
                            Score += merged.Value;

                            // The mighty 2048 tile
                            if (merged.Value == _winingTileValue)
                            {
                                Won = true;
                            }
                        }
                        else
                        {
                            MoveTile(tile, positions.Farthest);
                        }

                        if (!cell.IsEqual(tile.Position))
                        {
                            moved = true; // The tile moved from its original cell!
                        }
                    }
                }
            }

            if (moved)
            {
                AddRandomTile();

                if (!MovesAvailable())
                {
                    Over = true; // Game over!
                }

                Actuate();
            }
        }
コード例 #17
0
        static void Main(string[] args)
        {
            Mine mine = new Mine();

            int[][] twoD = new int[2][];
            twoD[0] = new int[] { 0, 0 };
            twoD[1] = new int[] { 0, 1 };


            int[,] field = mine.Minesweeper(twoD, 3, 4);

            int mRow = field.GetUpperBound(0);
            int mCol = field.GetUpperBound(1);

            for (int r = 0; r <= mRow; r++)
            {
                for (int c = 0; c <= mCol; c++)
                {
                    Console.Write(field[r, c] + " ");
                }
                Console.WriteLine("");
            }

            int[]        bst          = { 2, 3, 4, 10, 40 };
            BinarySearch binarySearch = new BinarySearch();
            int          n            = bst.Length;
            int          x            = 10;

            Console.WriteLine("Recurcive: The index is " + binarySearch.BinarySearchRecursive(bst, 0, n - 1, x));
            Console.WriteLine("Itirative: The index is " + binarySearch.BinarySearchItirative(bst, x));


            var path = new List <int>();
            var Prev = new Dictionary <int, int>();

            Console.WriteLine(string.Join(", ", search.DFS(unDirectedgraph, 1)));
            Console.WriteLine(string.Join(", ", search.BFS(unDirectedgraph, 1, ref Prev, v => path.Add(v))));
            Console.WriteLine("Trace Path...");
            Console.WriteLine(string.Join(", ", path));
            foreach (var vertex in vertices)
            {
                Console.WriteLine("shortest path to {0,2}: {1}", vertex, string.Join(", ", search.ShortestPathFromPrev(Prev, 1, vertex)));
            }
            Console.WriteLine("Topological Sort....");
            Console.WriteLine(string.Join(", ", TopSort()));
            Console.WriteLine("Is 'create' anagram of 'eaterc'? : " + anagram.isAnagram("create", "eaterc"));

            void checkPalindrome(string str)
            {
                Palindrome p = new Palindrome();

                Console.WriteLine("Is this word a palindrome? " + str);
                Console.WriteLine(p.isPalidrome(str, false));
            };

            checkPalindrome("hello");
            checkPalindrome("motor");
            checkPalindrome("rotor");

            Misc misc = new Misc();

            int[] arr1 = { 5, 6, 1, 2, 3, 4 };
            int   n1   = arr1.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr1, 0, n1 - 1));

            int[] arr2 = { 1, 2, 3, 4 };
            int   n2   = arr2.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr2, 0, n2 - 1));

            int[] arr3 = { 1 };
            int   n3   = arr3.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr3, 0, n3 - 1));

            int[] arr4 = { 1, 2 };
            int   n4   = arr4.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr4, 0, n4 - 1));

            int[] arr5 = { 2, 1 };
            int   n5   = arr5.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr5, 0, n5 - 1));

            int[] arr6 = { 5, 6, 7, 1, 2, 3, 4 };
            int   n6   = arr6.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr6, 0, n1 - 1));

            int[] arr7 = { 1, 2, 3, 4, 5, 6, 7 };
            int   n7   = arr7.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr7, 0, n7 - 1));

            int[] arr8 = { 2, 3, 4, 5, 6, 7, 8, 1 };
            int   n8   = arr8.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr8, 0, n8 - 1));

            int[] arr9 = { 3, 4, 5, 1, 2 };
            int   n9   = arr9.Length;

            Console.WriteLine("The minimum element is " +
                              misc.FindMinInSortedRotated(arr9, 0, n9 - 1));

            int[]      arr   = { 64, 34, 25, 12, 22, 11, 90 };
            BubbleSort bSort = new BubbleSort();

            bSort.Sort(arr);
            Console.Write("arr = { 64, 34, 25, 12, 22, 11, 90 } => Sorted array = ");
            printArray(arr);

            int[]     ar = { 99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0 };
            QuickSort qs = new QuickSort();

            qs.Quick_Sort(ar);
            Console.Write("arr = { 99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0} => Insertion Sorted array = ");
            printArray(ar);

            int[]         arr_1 = { 64, 34, 25, 12, 22, 11, 90 };
            SelectionSort sSort = new SelectionSort();

            sSort.Sort(arr_1);
            Console.Write("arr_1 = { 64, 34, 25, 12, 22, 11, 90 } => Sorted array = ");
            printArray(arr_1);

            WordLadder wordLadder = new WordLadder();
            string     strpath    = "";
            int        i          = wordLadder.LadderLength("hit", "cog", ref strpath);

            Console.WriteLine(strpath);

            HammingWeight hw = new HammingWeight();

            int[] hw_1 = { 31, 51 };
            Console.WriteLine("Hamming Weight of hw_1 = {    31,51} = " + hw.GetHammingWeightbyPreprocessing(hw_1));

            Fibonacci fib = new Fibonacci();

            Console.WriteLine("6th Fibonacci number by rec is : " + fib.FibRecursive(6));
            Console.WriteLine("6th Fibonacci number by DP is : " + fib.FibDP(6));
            Console.WriteLine("6th Fibonacci number by Bottomup is : " + fib.FibBottomUp(6));

            Subsets subsets = new Subsets();

            int[] arrSS = new int[] { 2, 4, 6, 10 };
            Console.WriteLine("No. of subsets whose sum is 16 in { 2, 4, 6, 10 } : " + subsets.CountSubsetsDP(arrSS, 16));

            HasPairWithSum obj = new HasPairWithSum();

            Console.WriteLine("Does the array { 2, 4, 6, 10 } has a pair whose sum is 12: " + obj.isPairWithSumExists(arrSS, 12));

            MergeArrays ma = new MergeArrays();

            int[] arrSorted2 = new int[] { 0, 3, 4 };
            int[] arrSorted1 = new int[] { 2, 4, 6, 10 };

            Console.WriteLine("Merged Sorted array for the sorted arrays { 0, 3, 4} and { 2, 4, 6, 10 } : ");
            printArray(ma.MergeSortedArrays(arrSorted1, arrSorted2));

            MoveZeros mz = new MoveZeros();

            Console.WriteLine("Move Zeros from {0,0,1} ");
            int[] mzA = new int[] { 0, 0, 1 };
            mz.MoveZeroes(mzA);
            printArray(mzA);

            FirstRecurring fr = new FirstRecurring();

            int[] fra = new int[] { 2, 5, 1, 2, 3, 5, 1, 2, 4 };
            Console.WriteLine("First recurring element in  { 2, 5, 1, 2, 3, 5, 1, 2, 4 } is: " + fr.GetFirstRecurringElement <int>(fra));

            Islands il = new Islands();

            int[,] M = new int[, ] {
                { 1, 1, 0, 0, 0 },
                { 0, 1, 0, 0, 1 },
                { 1, 0, 0, 1, 1 },
                { 0, 0, 0, 0, 0 },
                { 1, 0, 1, 0, 1 }
            };
            Console.Write("Number of islands is: " +
                          il.countIslands(M));

            LongestPalindromicSubstring lss = new LongestPalindromicSubstring();

            Console.Write("LongestPalindrome in 'babad' : " + lss.LongestPalindrome("cbbd"));


            BinaryTree tree = new BinaryTree();

            tree.root            = new TreeNode(1);
            tree.root.left       = new TreeNode(2);
            tree.root.right      = new TreeNode(3);
            tree.root.left.left  = new TreeNode(4);
            tree.root.left.right = new TreeNode(5);
            Console.WriteLine("");
            Traversals trav = new Traversals();

            trav.printInorder(tree.root);
            Console.WriteLine("");
            trav.printPreorder(tree.root);
            Console.WriteLine("");
            trav.printPostOrder(tree.root);
            Console.WriteLine("");

            Console.Write("The height of the tree is : " + trav.GetTreeHeight(tree.root));
            Console.WriteLine("Level Order:");
            trav.LevelOrderTraversal(tree.root);
        }
コード例 #18
0
    private void Move(Direction direction)
    {
        Coord   cell;
        DigTile tile;

        Coord      vector     = GetDirectionalOffset(direction);
        Traversals traversals = Traversals.BuildTraversals(Size, vector);
        bool       moved      = false;

        PrepareTiles();

        foreach (int x in traversals.x)
        {
            foreach (int y in traversals.y)
            {
                cell = new Coord(x, y);
                tile = grid.CellContent(cell);

                if (tile != null)
                {
                    FarthestPosition positions = FindFarthestPosition(cell, vector);
                    DigTile          next      = grid.CellContent(positions.Next);

                    if (next != null && next.Value == tile.Value && next.MergedFrom == null)
                    {
                        DigTile merged = new DigTile(positions.Next, tile.Value * 2)
                        {
                            MergedFrom = new List <DigTile> {
                                tile, next
                            }
                        };

                        grid.InsertTile(merged);
                        grid.RemoveTile(tile);

                        tile.UpdatePosition(positions.Next);

                        CurrentScore += merged.Value;

                        if (merged.Value == Goal)
                        {
                            Solve();
                        }
                        if (merged.Value == 2048 && !hasWon2048)
                        {
                            Win2048.SetActive(true);
                            hasWon2048 = justWon2048 = true;
                            HideDirectionHighlights(true);
                        }
                    }
                    else
                    {
                        MoveTile(tile, positions.Farthest);
                    }

                    if (!PositionsEqual(cell, tile))
                    {
                        moved = true;
                    }
                }
            }
        }

        if (moved)
        {
            AddRandomTile();

            Actuate();
            LogGrid(direction);

            if (!MovesAvailable())
            {
                GameOver();
            }
        }
    }
コード例 #19
0
 public override string ToString()
 {
     return(string.Join(" | ", Traversals.PreOrder(this, node => node.Children).Select(node => $"{{Id={node.Id},Affinity={node.Affinity},VoteAction={node.VoteAction}}}")));
 }