コード例 #1
0
    public void One_row()
    {
        var actual   = PascalsTriangle.Calculate(1);
        var expected = new[] { new[] { 1 } };

        Assert.Equal(expected, actual, NestedEnumerableEqualityComparer <int> .Instance);
    }
コード例 #2
0
    public void Five_rows()
    {
        var actual   = PascalsTriangle.Calculate(5);
        var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 }, new[] { 1, 4, 6, 4, 1 } };

        Assert.Equal(expected, actual, NestedEnumerableEqualityComparer <int> .Instance);
    }
コード例 #3
0
    public void Twenty_rows()
    {
        var actual   = PascalsTriangle.Calculate(20).Last();
        var expected = new[] { 1, 19, 171, 969, 3876, 11628, 27132, 50388, 75582, 92378, 92378, 75582, 50388, 27132, 11628, 3876, 969, 171, 19, 1 };

        Assert.Equal(expected, actual);
    }
コード例 #4
0
        /// <summary>Returns the number of ways r items can be chosen from n items.</summary>
        /// <remarks>
        /// Returns the number of ways r items can be chosen from n items.  The value of
        /// n is (int) d[0] and the value of r is (int) d[1].
        /// </remarks>
        public virtual double Of(double[] d, int numParam)
        {
            int n = (int)d[0];
            int r = (int)d[1];

            return(PascalsTriangle.NCr(n, r));
        }
コード例 #5
0
    public void Two_rows()
    {
        var actual   = PascalsTriangle.Calculate(2).ToArray();
        var expected = new[] { new[] { 1 }, new[] { 1, 1 } };

        Assert.Equal(expected, actual, NestedEnumerableEqualityComparer <int> .Instance);
    }
コード例 #6
0
        /*
         * Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,
         * there are exactly 6 routes to the bottom right corner.
         *  _____  __         _              _
         *  |_|_|    |   |     |   |_   |__   |_
         *  |_|_|    |   |__   |_    |_    |    |
         *
         * How many such routes are there through a 20×20 grid?
         *
         *    1           1
         *    2        1  2  1
         *    3      1  3  3  1
         *    4    1  4  6  4  1
         *    5   1  5  10 10 5  1
         *    6  1  6  15 20 15 6 1
         *
         */

        public long Solution1(int depth)
        {
            int value = depth * 2;
            var pt    = new PascalsTriangle(value);

            pt.Build();
            return(pt.MaxPaths());
        }
コード例 #7
0
    public void Single_row()
    {
        var expected = new[]
        {
            new[] { 1 }
        };

        Assert.Equal(expected, PascalsTriangle.Calculate(1));
    }
コード例 #8
0
    public void Two_rows()
    {
        var expected = new[]
        {
            new[] { 1 },
            new[] { 1, 1 }
        };

        Assert.Equal(expected, PascalsTriangle.Calculate(2));
    }
コード例 #9
0
    public void Four_rows()
    {
        var expected = new[]
        {
            new[] { 1 },
            new[] { 1, 1 },
            new[] { 1, 2, 1 },
            new[] { 1, 3, 3, 1 }
        };

        Assert.Equal(expected, PascalsTriangle.Calculate(4));
    }
コード例 #10
0
    public void Six_rows()
    {
        var expected = new[]
        {
            new[] { 1 },
            new[] { 1, 1 },
            new[] { 1, 2, 1 },
            new[] { 1, 3, 3, 1 },
            new[] { 1, 4, 6, 4, 1 },
            new[] { 1, 5, 10, 10, 5, 1 }
        };

        Assert.Equal(expected, PascalsTriangle.Calculate(6));
    }
コード例 #11
0
    public void Ten_rows()
    {
        var expected = new[]
        {
            new[] { 1 },
            new[] { 1, 1 },
            new[] { 1, 2, 1 },
            new[] { 1, 3, 3, 1 },
            new[] { 1, 4, 6, 4, 1 },
            new[] { 1, 5, 10, 10, 5, 1 },
            new[] { 1, 6, 15, 20, 15, 6, 1 },
            new[] { 1, 7, 21, 35, 35, 21, 7, 1 },
            new[] { 1, 8, 28, 56, 70, 56, 28, 8, 1 },
            new[] { 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 }
        };

        Assert.Equal(expected, PascalsTriangle.Calculate(10));
    }
コード例 #12
0
    public void Three_rows()
    {
        var actual = PascalsTriangle.Calculate(3);

        Assert.That(actual, Is.EqualTo(new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 } }));
    }
コード例 #13
0
 public void Zero_rows()
 {
     Assert.Empty(PascalsTriangle.Calculate(0));
 }
コード例 #14
0
ファイル: Program.cs プロジェクト: jacobkurien1/Algorithms
        static void Main(string[] args)
        {
            // StringProblems
            //Test calls for Reverse string
            string input = "jacob";

            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jake";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jdshjdh@#$%^&)";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));

            ReplaceSpaces.TestReplaceSpacesInplace();
            Anagrams.TestIsAnagramAlgo();
            StringRotation.TestIsThisRotatedString();
            RemoveDuplicates.TestRemoveDuplicatesFromString();
            StringToLongConverter.TestStringToLong();
            RegexMatching.TestMatch();
            SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray();
            SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray();
            PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue();
            PalindromeInStringPermutation.TestPalindromeInStringPermutation();
            EditDistanceBetweenStrings.TestEditDistanceBetweenStrings();
            AnagramIsPalindrome.TestAnagramIsPalindrome();
            GreatestPalindrome.TestGreatestPalindrome();
            ReverseStringWithoutVowels.TestReverseStringWithoutVowels();
            LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars();
            // Pattern Matching
            NativePatternMatching.TestNativePatternMatching();
            KMPPatternMatching.TestKMPPatternMatching();
            BoyerMoorePatternMatching.TestPatternMatching();
            RabinKarp.TestRabinKarp();

            //Console.ReadLine();

            //Array Problems
            ArrayOfNumsIncrement.TestIncrementArrayOfNumbers();
            MajorityElement.TestFindMajorityElement();
            Merge2SortedArrays.TestMergeSortedArrays();
            MaxDistanceInArray.TestMaxDistanceInArray();
            MovingAverage.TestMovingAverage();
            TotalAverage.TestTotalAverage();
            ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight();
            WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram();
            CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum();
            //Median.TestGetMedianOf2SortedArray();

            // Sorting Problems
            SelectionSort.TestSorting();
            BubbleSort.TestSorting();
            InsertionSort.TestSorting();
            ShellSort.TestSorting();
            MergeSort.TestMergeSort();
            QuickSort.TestQuickSort();
            HeapSortTester.TestHeapSort();
            CountingSort.TestSorting();
            RadixSort.TestRadixSort();
            DutchNationalFlag.TestDutchNationalFlag();
            SortedSquares.TestSortedSquares();

            // Matrix Problem
            Rotate_Matrix_90_degree.TestRotateMatrix();
            Matrix_Column_Rows_0.TestMakeRowColZero1();
            Matrix_Column_Rows_0.TestMakeRowColZero2();
            RotateMatrix180.TestRotateMatrix180();
            SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements();
            SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix();
            SearchWordInMatrix.TestSearchWordInMatrix();
            MaxOnesInRow.TestMaxOnesInRow();
            MatrixAsTriangle.TestMatrixAsTriangle();
            MinRangeInMatrix.TestMinRangeInMatrix();
            PrintMatrixAsSnake.TestPrintMatrixAsSnake();
            PrintMatrixInSpiral.TestPrintMatrixInSpiral();
            MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix();
            TicTacToeWinner.TestTicTacToeWinner();
            WaterfallCreation.TestWaterfallCreation();

            // Linked list Problems
            DeleteLinkedListNode.TestDeleteFirstNode();
            DeleteDuplicatesFromLinkedList.TestDeleteDuplicates();
            NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList();
            DeleteNodeWithDirectReference.TestDeleteNode();
            AddNumbers.TestAddNumbersRepresentedByLinkedList();
            CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode();
            CommonElementInTwoLinkedList.TestCommonElement();
            ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes();
            MergeSortedLinkedList.TestMerge();
            CycleInLinkedList.TestStartOfCycleInLinkedList();
            MedianForCircularLinkedList.TestGetMedian();
            ReverseLinkedList.TestReverseLinkedList();
            SortedCircularLinkedList.TestCircularLinkedList();

            // stack and queue problem
            ThreeStackWithOneArray.TestThreeStackWithOneArray();
            StackWithMinElement.TestStackWithMinElement();
            StackOfPlates.TestStackOfPlates();
            SortAStack.TestSortAStackAscending();
            WellFormedExpression.TestWellFormedExpression();
            QueueVia2Stack.TestQueueVia2Stack();
            LRUCache.TestLRUCache();
            EvaluatePrefixNotation.TestGetPrefixNotationResult();
            EvaluateInflixNotation.TestGetInflixNotationResults();
            EvaluatePostfixNotation.TestGetPostfixNotationResult();
            TestCircularQueue.TestCircularQueueWithDifferentCases();
            LargestAreaInHistogram.TestLargestAreaInHistogram();
            TextEditerWithUndo.TestTextEditerWithUndo();

            //Recursion Problem
            TowerOfHanoi.TestTowerOfHanoi();
            MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums();

            // Back tracking problems
            Sudoku.TestSudokuSolver();
            HamiltonianCycle.TestHamiltonianCycle();
            GraphColoringWithMColors.TestGraphColoringWithMColors();
            MakeLargestIsland.TestMakeLargestIsland();

            //Misc Problem
            MinNumOfCoins.TestMinNumOfCoins();
            IsPrime.TestCheckPrime();
            SquareRoot.TestCalculateSquareRoot();
            CreditCardCheck.TestLuhnAlgo();
            ExcelFirstRowConversion.TestCovertExcelColumnToLong();
            Skyline.TestSkyline();
            SumOfSquaresWithoutMultiplication.TestSumOfSquares();
            MergeIntervals.TestMergeIntervals();
            WidthOfCalendar.TestWidthOfCalendar();
            JosephusProblem.TestJosephusProblem();

            // Permutation and Combination problem
            ShuffleAList.TestFisherYatesAlgo();
            CombinationsOfBinaryString.TestCombinationsOfBinaryString();
            AllCombinationsOfString.TestAllCombinationsOfString();
            AllPermutationsOfString.TestAllPermutationsOfString();
            PhoneNumberToWords.TestPhoneNumberToWords();
            AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits();
            DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff();
            PowerSet.TestPowerSet();
            AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis();
            GoodDiceRoll.TestGoodDiceRoll();
            PermutationsOfValidTime.TestPermutationsOfValidTime();

            // Tree Problems
            TreeFromExpression.TestCreateTreeFromExpression();
            TestBinarySearchTree.TestDifferentOperationsOnBST();
            AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST();
            CheckBTisBST.TestCheckBTisBST();
            MaxSumOnTreeBranch.TestMaxSum();
            WalkTheTree.TestWalkTheTree();
            SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST();
            CheckIfTheTreeIsBalanced.TestIsTreeBalanced();
            LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth();
            PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel();
            PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally();
            TreeSubtreeOfAnother.TestMatchTree();
            AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT();
            AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT();
            LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT();
            ExteriorOfBT.TestPrintExteriorOfBT();
            DepthOfTree.TestGetDepthOfTree();
            TreeToColumns.TestTreeToColumns();
            KthSmallestElementFromBST.TestKthSmallestElementFromBST();
            MakeBSTFromPreOrder.TestMakeBSTFromPreOrder();
            MirrorATree.TestMirrorATree();
            CloneABTWithRandPointer.TestCloneABTWithRandPointer();
            TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder();
            TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder();
            TreePathSumsToValue.TestTreePathSumsToValue();
            AllPathInNArayTree.TestAllPathInNArayTree();
            SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree();
            SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree();
            AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree();
            AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT();

            // Trie problems
            CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie();
            // ToDo: have a problem of suffix trees
            ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet();

            // Dynamic Programming problems
            LongestCommonSubsequence.TestGetLongestCommonSubsequence();
            LongestPalindromeSubString.TestGetLongestPalindromeSubString();
            LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence();
            MaximumAs.TestGetMaximumAs();
            MinNumberOfJumps.TestGetMinimumNumberOfJumps();
            LongestCommonSubString.TestGetLongestCommonSubString();
            KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight();
            TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits();
            WordBreaking.TestBreakTheWords();
            DistanceOfWords.TestDistanceOfWords();
            LongestIncreasingSubSequence.TestLongestIncreasingSubSequence();
            MinCostPath.TestMinCostPath();
            DifferentWaysForCoinChange.TestDifferentWaysForCoinChange();
            MatrixMultiplication.TestMatrixMultiplication();
            BinomialCoefficient.TestBinomialCoefficient();
            BoxStacking.TestBoxStacking();
            WordWrapping.TestWordWrapping();
            MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes();
            LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum();
            PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets();
            MaxSumRectangle.TestMaxSumRectangle();
            RegularExpressionMatch.TestRegularExpressionMatch();
            NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares();
            LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString();
            StringDecodeAsAlphabets.TestStringDecodeAsAlphabets();
            BalloonBursting.TestBalloonBursting();
            TravellingSalesmanProblem.TestTravellingSalesmanProblem();
            MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements();
            MaxPathThroughMatrix.TestMaxPathThroughMatrix();
            BrickLaying.TestBrickLaying();
            JobSchedullingWithConstraints.TestJobSchedullingWithConstraints();
            EggDropMinTrials.TestEggDropMinTrials();

            // Graph Problems
            ShortestPath.TestGetShortestPathBetween2Vertex();
            CycleInDirectedGraph.TestIsCycleInDirectedGraph();
            CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph();
            SolveAMaze.TestSolveAMaze();
            AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex();
            AllPaths.TestGetAllPathsInGraphFromStartVertex();
            ColorVertices.TestColorVerticesWithDifferentColor();
            CheckBipartiteGraph.TestCheckBipartiteGraph();
            TransformOneWordToAnother.TestGetTransformation();
            ConstraintsVerification.TestConstraintsVerification();
            ExtendedContactsInSocialNetwork.TestComputeExtendedContacts();
            CourseScheduling.TestCourseScheduling();
            SnakeAndLadder.TestSnakeAndLadder();
            IsGraphATree.TestIsGraphATree();
            ReverseGraph.TestReverseGraph();
            StronglyConnectedGraph.TestStronglyConnectedGraph();
            ConnectedComponents.TestConnectedComponents();
            ContinentalDivide.TestContinentalDivide();
            CloneGraph.TestCloneGraph();
            Wordament.TestWordament();
            // ShortestPathAlgo
            FloydWarshall.TestFloydWarshall();
            DijkstraAlgorithm.TestDijkstraAlgorithm();
            BellmanFord.TestBellmanFord();
            TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix();
            HeuristicSearch.TestHeuristicSearch();
            AStar.TestAStar();
            ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved();
            ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates();
            //MaxFlow
            FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp();
            MinCut.TestMinCut();
            MaximumBipartiteMatching.TestMaximumBipartiteMatching();
            //Minimum Spanning Tree
            KruskalAlgorithm.TestKruskalAlgorithm();
            PrimsAlgorithm.TestPrimsAlgorithm();


            //Heap problems
            BasicMaxHeap.TestMaxHeap();
            BasicMinHeap.TestMinHeap();
            TestMinHeapMap.DoTest();
            TestPriorityQueue.Run();
            MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers();

            //DisjointSets
            TestingDisjointSet.Run();
            //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it

            //Geometry
            ClosestPairOfPoints.TestClosestPairOfPoints();
            RectangleIntersection.TestRectangleIntersection();
            LineSegmentIntersection.TestLineSegmentIntersection();
            ConvexHull.TestConvexHull();
            KClosestPointToOrigin.TestKClosestPointToOrigin();

            //Greedy Algorithm
            HuffmanCoding.TestHuffmanCoding();

            //Randomized Algorithm
            RandomGeneration.TestRandomGeneration();

            // Bit Algorithms
            IntHaveOppositeSigns.TestIntHaveOppositeSigns();
            Parity.TestParity();

            //Math Problem
            ZerosInFactorial.TestZerosInFactorial();
            GetAllPrimeFactors.TestGetAllPrimeFactors();
            NumberOfFactors.TestNumberOfFactors();
            AllFactors.TestAllFactors();
            MultiplyLongNumbers.TestMultiplyLongNumbers();
            NextLargestPermutation.TestNextLargestPermutation();
            AllPrimesTillN.TestAllPrimesTillN();
            PascalsTriangle.TestPascalsTriangle();
            SubtractLongNumbers.TestSubtractLongNumbers();

            //Search problems
            SearchInSortedRotatedArray.TestSearchInSortedRotatedArray();
            KClosestElementInArray.TestKClosestElementInArray();
            SearchInSortedMatrix.TestSearchInSortedMatrix();
            BinarySearchUnbounded.TestBinarySearchUnbounded();
            LinkedListSublistSearch.TestLinkedListSublistSearch();
            NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray();
            GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray();

            //Distributed algorithms
            KWayMerge.TestKWayMerge();


            Console.ReadLine();
        }
コード例 #15
0
    public void Four_rows()
    {
        var actual = new PascalsTriangle().Calculate(4);

        Assert.That(actual, Is.EqualTo(new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 } }));
    }
コード例 #16
0
 public void Negative_rows()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => PascalsTriangle.Calculate(-1));
 }
コード例 #17
0
 public static Object Solve()
 {
     return(PascalsTriangle.GetEntry(GridSize * 2, GridSize));
 }
コード例 #18
0
 public void BeforeEach()
 {
     PascalsTriangle = new PascalsTriangle();
 }
コード例 #19
0
    public void One_row()
    {
        var actual = PascalsTriangle.Calculate(1);

        Assert.That(actual, Is.EqualTo(new[] { new[] { 1 } }));
    }
コード例 #20
0
    public void Twenty_rows()
    {
        var actual = PascalsTriangle.Calculate(20).Last();

        Assert.That(actual, Is.EqualTo(new[] { 1, 19, 171, 969, 3876, 11628, 27132, 50388, 75582, 92378, 92378, 75582, 50388, 27132, 11628, 3876, 969, 171, 19, 1 }));
    }
コード例 #21
0
    public void Five_rows()
    {
        var actual = PascalsTriangle.Calculate(5);

        Assert.That(actual, Is.EqualTo(new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 }, new [] { 1, 4, 6, 4, 1 } }));
    }