├── .devcontainer └── devcontainer.json ├── .editorconfig ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── ci.yml │ └── stale.yml ├── .gitignore ├── Algorithms.Tests ├── Algorithms.Tests.csproj ├── AssemblyInfo.cs ├── Compressors │ ├── BurrowsWheelerTransformTests.cs │ ├── HuffmanCompressorTests.cs │ ├── ShannonFanoCompressorTests.cs │ └── TranslatorTests.cs ├── Crypto │ ├── Digests │ │ ├── AsconDigestTests.cs │ │ └── Md2DigestTests.cs │ ├── Exceptions │ │ ├── CryptoExceptionTests.cs │ │ ├── DataLengthExceptionTests.cs │ │ └── OutputLengthExceptionTests.cs │ ├── Paddings │ │ ├── Iso10126D2PaddingTests.cs │ │ ├── Iso7816D4PaddingTests.cs │ │ ├── Pkcs7PaddingTests.cs │ │ ├── TbcPaddingTests.cs │ │ └── X932PaddingTests.cs │ └── Utils │ │ ├── ByteEncodingUtils.cs │ │ ├── LongUtilsTests.cs │ │ └── ValidationUtilsTests.cs ├── Encoders │ ├── BlowfishEncoderTests.cs │ ├── CaesarEncoderTests.cs │ ├── FeistelCipherTest.cs │ ├── HillEnconderTests.cs │ ├── NysiisEncoderTests.cs │ ├── SoundexEncoderTest.cs │ └── VigenereEncoderTests.cs ├── Financial │ └── PresentValueTests.cs ├── Graph │ ├── BellmanFordTests.cs │ ├── BreadthFirstSearchTests.cs │ ├── BreadthFirstTreeTraversalTests.cs │ ├── DepthFirstSearchTests.cs │ ├── Dijkstra │ │ └── DijkstraTests.cs │ ├── FloydWarshallTests.cs │ ├── KosarajuTests.cs │ └── MinimumSpanningTree │ │ ├── KruskalTests.cs │ │ └── PrimMatrixTests.cs ├── Helpers │ ├── IntComparer.cs │ └── RandomHelper.cs ├── Knapsack │ ├── BranchAndBoundKnapsackSolverTests.cs │ ├── DynamicProgrammingKnapsackSolverTests.cs │ └── NaiveKnapsackSolverTests.cs ├── LinearAlgebra │ ├── Distances │ │ ├── ChebyshevTests.cs │ │ ├── EuclideanTests.cs │ │ ├── ManhattanTests.cs │ │ └── MinkowskiTests.cs │ └── Eigenvalue │ │ └── PowerIterationTests.cs ├── ModularArithmetic │ ├── ChineseRemainderTheoremTest.cs │ ├── ExtendedEuclideanAlgorithmTest.cs │ └── ModularMultiplicativeInverseTest.cs ├── Numeric │ ├── AbsTests.cs │ ├── AdditionWithoutArithmeticsTests.cs │ ├── AliquotSumCalculatorTests.cs │ ├── AmicableNumbersTest.cs │ ├── AutomorphicNumberTests.cs │ ├── BinomialCoefficientTests.cs │ ├── CeilTests.cs │ ├── Decomposition │ │ ├── LUTests.cs │ │ ├── MaclaurinTests.cs │ │ └── SVDTests.cs │ ├── EulerMethodTest.cs │ ├── FactorialTests.cs │ ├── Factorization │ │ └── TrialDivisionFactorizerTests.cs │ ├── FloorTests.cs │ ├── GaussJordanEliminationTests.cs │ ├── GreatestCommonDivisor │ │ ├── BinaryGreatestCommonDivisorFinderTests.cs │ │ └── EuclideanGreatestCommonDivisorFinderTests.cs │ ├── JosephusProblemTest.cs │ ├── KeithNumberTest.cs │ ├── KrishnamurthyNumberCheckerTests.cs │ ├── MillerRabinPrimalityTest.cs │ ├── ModularExponentiationTest.cs │ ├── NarcissisticNumberTest.cs │ ├── NewtonSquareRootTests.cs │ ├── PerfectCubeTests.cs │ ├── PerfectNumberTest.cs │ ├── PerfectSquareTest.cs │ ├── PseudoInverse │ │ └── PseudoInverseTests.cs │ ├── RungeKuttaMethodTest.cs │ └── SoftMaxTests.cs ├── Other │ ├── DecisionsConvolutionsTest.cs │ ├── FermatPrimeCheckerTests.cs │ ├── FloodFillTest.cs │ ├── GaussOptimizationTest.cs │ ├── GeoLocationTests.cs │ ├── GeofenceTests.cs │ ├── GeohashTests.cs │ ├── Int2BinaryTests.cs │ ├── JulianEasterTests.cs │ ├── KochSnowflakeTest.cs │ ├── LuhnTests.cs │ ├── MandelbrotTest.cs │ ├── ParetoOptimizationTests.cs │ ├── PollardsRhoFactorizingTests.cs │ ├── RGBHSVConversionTest.cs │ ├── SieveOfEratosthenesTests.cs │ ├── TriangulatorTests.cs │ └── WelfordsVarianceTest.cs ├── Problems │ ├── DynamicProgramming │ │ ├── CoinChange │ │ │ ├── GenerateChangesDictionaryTests.cs │ │ │ ├── GenerateSingleCoinChangesTests.cs │ │ │ ├── GetMinimalNextCoinTests.cs │ │ │ └── MakeCoinChangeDynamicTests.cs │ │ └── LevenshteinDistance │ │ │ └── LevenshteinDistanceTests.cs │ ├── NQueens │ │ └── BacktrackingNQueensSolverTests.cs │ └── StableMarriage │ │ └── GaleShapleyTests.cs ├── RecommenderSystem │ └── CollaborativeFilteringTests.cs ├── Search │ ├── BinarySearcherTests.cs │ ├── BoyerMooreTests.cs │ ├── FastSearcherTests.cs │ ├── FibonacciSearcherTests.cs │ ├── Helper.cs │ ├── InterpolationSearchTests.cs │ ├── JumpSearcherTests.cs │ ├── LinearSearcherTests.cs │ └── RecursiveBinarySearcherTests.cs ├── Sequences │ ├── AllOnesSequenceTests.cs │ ├── AllThreesSequenceTests.cs │ ├── AllTwosSequenceTests.cs │ ├── BinaryPrimeConstantSequenceTests.cs │ ├── BinomialSequenceTests.cs │ ├── CakeNumbersSequenceTests.cs │ ├── CatalanSequenceTest.cs │ ├── CentralPolygonalNumbersSequenceTests.cs │ ├── CubesSequenceTests.cs │ ├── DivisorsCountSequenceTests.cs │ ├── EuclidNumbersSequenceTests.cs │ ├── EulerTotientSequenceTests.cs │ ├── FactorialSequenceTest.cs │ ├── FermatNumbersSequenceTests.cs │ ├── FermatPrimesSequenceTests.cs │ ├── FibonacciSequenceTests.cs │ ├── GolombsSequenceTests.cs │ ├── KolakoskiSequenceTests.cs │ ├── KummerNumbersSequenceTests.cs │ ├── LucasNumbersBeginningAt2SequenceTests.cs │ ├── MakeChangeSequenceTests.cs │ ├── MatchstickTriangleSequenceTests.cs │ ├── NaturalSequenceTests.cs │ ├── NegativeIntegersSequenceTests.cs │ ├── NumberOfBooleanFunctionsSequenceTests.cs │ ├── NumberOfPrimesByNumberOfDigitsSequenceTests.cs │ ├── NumberOfPrimesByPowersOf10SequenceTests.cs │ ├── OnesCountingSequenceTest.cs │ ├── PowersOf10SequenceTests.cs │ ├── PowersOf2SequenceTests.cs │ ├── PrimePiSequenceTests.cs │ ├── PrimesSequenceTests.cs │ ├── PrimorialNumbersSequenceTests.cs │ ├── RecamansSequenceTests.cs │ ├── SquaresSequenceTests.cs │ ├── TetrahedralSequenceTests.cs │ ├── TetranacciNumbersSequenceTests.cs │ ├── ThreeNPlusOneStepsSequenceTests.cs │ ├── TribonacciNumbersSequenceTests.cs │ ├── VanEcksSequenceTests.cs │ └── ZeroSequenceTests.cs ├── Shufflers │ └── FisherYatesShufflerTests.cs ├── Sorters │ ├── Comparison │ │ ├── BasicTeamSorterTests.cs │ │ ├── BinaryInsertionSorterTests.cs │ │ ├── BogoSorterTests.cs │ │ ├── BubbleSorterTests.cs │ │ ├── CocktailSorterTests.cs │ │ ├── CombSorterTests.cs │ │ ├── CycleSorterTests.cs │ │ ├── ExchangeSorterTests.cs │ │ ├── HeapSorterTests.cs │ │ ├── InsertionSorterTests.cs │ │ ├── MedianOfThreeQuickSorterTests.cs │ │ ├── MergeSorterTests.cs │ │ ├── MiddlePointQuickSorterTests.cs │ │ ├── PancakeSorterTests.cs │ │ ├── RandomPivotQuickSorterTests.cs │ │ ├── SelectionSorterTests.cs │ │ ├── ShellSorterTests.cs │ │ └── TimSorterTests.cs │ ├── External │ │ └── ExternalMergeSorterTests.cs │ ├── Integer │ │ ├── BucketSorterTests.cs │ │ ├── CountingSorterTests.cs │ │ └── RadixSorterTests.cs │ ├── String │ │ └── MsdRadixStringSorterTests.cs │ └── Utils │ │ └── GallopingStrategyTests.cs ├── Stack │ ├── BalancedParenthesesCheckerTests.cs │ ├── NextGreaterElementTests.cs │ └── ReverseStackTests.cs └── Strings │ ├── GeneralStringAlgorithmsTests.cs │ ├── PalindromeTests.cs │ ├── PatternMatching │ ├── BitapTests.cs │ ├── BoyerMoreTests.cs │ ├── KnuthMorrisPrattSearcherTests.cs │ ├── NaiveStringSearchTests.cs │ ├── RabinKarpTests.cs │ ├── WildCardMatcherTests.cs │ └── ZblockSubstringSearchTest.cs │ ├── PermutationTests.cs │ └── Similarity │ ├── CosineSimilarityTests.cs │ ├── DamerauLevenshteinDistanceTests.cs │ ├── HammingDistanceTests.cs │ ├── JaccardDistanceTests.cs │ ├── JaccardSimilarityTests.cs │ ├── JaroSimilarityTests.cs │ ├── JaroWinklerDistanceTests.cs │ └── OptimalStringAlignmentTests.cs ├── Algorithms ├── Algorithms.csproj ├── Crypto │ ├── Digests │ │ ├── AsconDigest.cs │ │ ├── IDigest.cs │ │ └── Md2Digest.cs │ ├── Exceptions │ │ ├── CryptoException.cs │ │ ├── DataLengthException.cs │ │ └── OutputLengthException.cs │ ├── Paddings │ │ ├── IBlockCipherPadding.cs │ │ ├── Iso10126D2Padding.cs │ │ ├── Iso7816D4Padding.cs │ │ ├── Pkcs7Padding.cs │ │ ├── TbcPadding.cs │ │ └── X932Padding.cs │ └── Utils │ │ ├── ByteEncodingUtils.cs │ │ ├── LongUtils.cs │ │ └── ValidationUtils.cs ├── DataCompression │ ├── BurrowsWheelerTransform.cs │ ├── HuffmanCompressor.cs │ ├── ShannonFanoCompressor.cs │ └── Translator.cs ├── Encoders │ ├── BlowfishEncoder.cs │ ├── CaesarEncoder.cs │ ├── FeistelCipher.cs │ ├── HillEncoder.cs │ ├── IEncoder.cs │ ├── NysiisEncoder.cs │ ├── SoundexEncoder.cs │ └── VigenereEncoder.cs ├── Financial │ └── PresentValue.cs ├── Graph │ ├── BellmanFord.cs │ ├── BreadthFirstSearch.cs │ ├── BreadthFirstTreeTraversal.cs │ ├── DepthFirstSearch.cs │ ├── Dijkstra │ │ ├── DijkstraAlgorithm.cs │ │ └── DistanceModel.cs │ ├── FloydWarshall.cs │ ├── IGraphSearch.cs │ ├── Kosaraju.cs │ └── MinimumSpanningTree │ │ ├── Kruskal.cs │ │ └── PrimMatrix.cs ├── Knapsack │ ├── BranchAndBoundKnapsackSolver.cs │ ├── BranchAndBoundNode.cs │ ├── DynamicProgrammingKnapsackSolver.cs │ ├── IHeuristicKnapsackSolver.cs │ ├── IKnapsackSolver.cs │ └── NaiveKnapsackSolver.cs ├── LinearAlgebra │ ├── Distances │ │ ├── Chebyshev.cs │ │ ├── Euclidean.cs │ │ ├── Manhattan.cs │ │ └── Minkowski.cs │ └── Eigenvalue │ │ └── PowerIteration.cs ├── ModularArithmetic │ ├── ChineseRemainderTheorem.cs │ ├── ExtendedEuclideanAlgorithm.cs │ └── ModularMultiplicativeInverse.cs ├── NewtonSquareRoot.cs ├── Numeric │ ├── Abs.cs │ ├── AdditionWithoutArithmetic.cs │ ├── AliquotSumCalculator.cs │ ├── AmicableNumbersChecker.cs │ ├── AutomorphicNumber.cs │ ├── BinomialCoefficient.cs │ ├── Ceil.cs │ ├── Decomposition │ │ ├── LU.cs │ │ └── ThinSVD.cs │ ├── EulerMethod.cs │ ├── Factorial.cs │ ├── Factorization │ │ ├── IFactorizer.cs │ │ └── TrialDivisionFactorizer.cs │ ├── Floor.cs │ ├── GaussJordanElimination.cs │ ├── GreatestCommonDivisor │ │ ├── BinaryGreatestCommonDivisorFinder.cs │ │ ├── EuclideanGreatestCommonDivisorFinder.cs │ │ └── IGreatestCommonDivisorFinder.cs │ ├── JosephusProblem.cs │ ├── KeithNumberChecker.cs │ ├── KrishnamurthyNumberChecker.cs │ ├── MillerRabinPrimalityChecker.cs │ ├── ModularExponentiation.cs │ ├── NarcissisticNumberChecker.cs │ ├── PerfectCubeChecker.cs │ ├── PerfectNumberChecker.cs │ ├── PerfectSquareChecker.cs │ ├── Pseudoinverse │ │ └── PseudoInverse.cs │ ├── RungeKuttaMethod.cs │ ├── Series │ │ └── Maclaurin.cs │ └── SoftMax.cs ├── Other │ ├── DecisionsConvolutions.cs │ ├── FermatPrimeChecker.cs │ ├── FloodFill.cs │ ├── GaussOptimization.cs │ ├── GeoLocation.cs │ ├── Geofence.cs │ ├── Geohash.cs │ ├── Int2Binary.cs │ ├── JulianEaster.cs │ ├── KochSnowflake.cs │ ├── Luhn.cs │ ├── Mandelbrot.cs │ ├── ParetoOptimization.cs │ ├── PollardsRhoFactorizing.cs │ ├── RGBHSVConversion.cs │ ├── SieveOfEratosthenes.cs │ ├── Triangulator.cs │ └── WelfordsVariance.cs ├── Problems │ ├── DynamicProgramming │ │ ├── CoinChange │ │ │ └── DynamicCoinChangeSolver.cs │ │ └── LevenshteinDistance │ │ │ └── LevenshteinDistance.cs │ ├── NQueens │ │ └── BacktrackingNQueensSolver.cs │ └── StableMarriage │ │ ├── Accepter.cs │ │ ├── GaleShapley.cs │ │ └── Proposer.cs ├── RecommenderSystem │ ├── CollaborativeFiltering.cs │ └── ISimilarityCalculator.cs ├── Search │ ├── AStar │ │ ├── AStar.cs │ │ ├── Node.cs │ │ ├── NodeState.cs │ │ ├── PathfindingException.cs │ │ ├── PriorityQueue.cs │ │ └── VecN.cs │ ├── BinarySearcher.cs │ ├── BoyerMoore.cs │ ├── FastSearcher.cs │ ├── FibonacciSearcher.cs │ ├── InterpolationSearch.cs │ ├── JumpSearcher.cs │ ├── LinearSearcher.cs │ └── RecursiveBinarySearcher.cs ├── Sequences │ ├── AllOnesSequence.cs │ ├── AllThreesSequence.cs │ ├── AllTwosSequence.cs │ ├── BinaryPrimeConstantSequence.cs │ ├── BinomialSequence.cs │ ├── CakeNumbersSequence.cs │ ├── CatalanSequence.cs │ ├── CentralPolygonalNumbersSequence.cs │ ├── CubesSequence.cs │ ├── DivisorsCountSequence.cs │ ├── EuclidNumbersSequence.cs │ ├── EulerTotientSequence.cs │ ├── FactorialSequence.cs │ ├── FermatNumbersSequence.cs │ ├── FermatPrimesSequence.cs │ ├── FibonacciSequence.cs │ ├── GolombsSequence.cs │ ├── ISequence.cs │ ├── KolakoskiSequence.cs │ ├── KolakoskiSequence2.cs │ ├── KummerNumbersSequence.cs │ ├── LucasNumbersBeginningAt2Sequence.cs │ ├── MakeChangeSequence.cs │ ├── MatchstickTriangleSequence.cs │ ├── NaturalSequence.cs │ ├── NegativeIntegersSequence.cs │ ├── NumberOfBooleanFunctionsSequence.cs │ ├── NumberOfPrimesByNumberOfDigitsSequence.cs │ ├── NumberOfPrimesByPowersOf10Sequence.cs │ ├── OnesCountingSequence.cs │ ├── PowersOf10Sequence.cs │ ├── PowersOf2Sequence.cs │ ├── PrimePiSequence.cs │ ├── PrimesSequence.cs │ ├── PrimorialNumbersSequence.cs │ ├── RecamansSequence.cs │ ├── SquaresSequence.cs │ ├── TetrahedralSequence.cs │ ├── TetranacciNumbersSequence.cs │ ├── ThreeNPlusOneStepsSequence.cs │ ├── TribonacciNumbersSequence.cs │ ├── VanEcksSequence.cs │ └── ZeroSequence.cs ├── Shufflers │ ├── FisherYatesShuffler.cs │ └── IShuffler.cs ├── Sorters │ ├── Comparison │ │ ├── BasicTimSorter.cs │ │ ├── BinaryInsertionSorter.cs │ │ ├── BogoSorter.cs │ │ ├── BubbleSorter.cs │ │ ├── CocktailSorter.cs │ │ ├── CombSorter.cs │ │ ├── CycleSorter.cs │ │ ├── ExchangeSorter.cs │ │ ├── HeapSorter.cs │ │ ├── IComparisonSorter.cs │ │ ├── InsertionSorter.cs │ │ ├── MedianOfThreeQuickSorter.cs │ │ ├── MergeSorter.cs │ │ ├── MiddlePointQuickSorter.cs │ │ ├── PancakeSorter.cs │ │ ├── QuickSorter.cs │ │ ├── RandomPivotQuickSorter.cs │ │ ├── SelectionSorter.cs │ │ ├── ShellSorter.cs │ │ ├── TimSorter.cs │ │ └── TimSorterSettings.cs │ ├── External │ │ ├── ExternalMergeSorter.cs │ │ ├── IExternalSorter.cs │ │ ├── ISequentialStorage.cs │ │ ├── ISequentialStorageReader.cs │ │ ├── ISequentialStorageWriter.cs │ │ └── Storages │ │ │ ├── IntFileStorage.cs │ │ │ └── IntInMemoryStorage.cs │ ├── Integer │ │ ├── BucketSorter.cs │ │ ├── CountingSorter.cs │ │ ├── IIntegerSorter.cs │ │ └── RadixSorter.cs │ ├── String │ │ ├── IStringSorter.cs │ │ └── MsdRadixStringSorter.cs │ └── Utils │ │ └── GallopingStrategy.cs ├── Stack │ ├── BalancedParenthesesChecker.cs │ ├── NextGreaterElement.cs │ └── ReverseStack.cs └── Strings │ ├── GeneralStringAlgorithms.cs │ ├── Palindrome.cs │ ├── PatternMatching │ ├── Bitap.cs │ ├── BoyerMoore.cs │ ├── KnuthMorrisPrattSearcher.cs │ ├── NaiveStringSearch.cs │ ├── RabinKarp.cs │ ├── WildCardMatcher.cs │ └── ZblockSubstringSearch.cs │ ├── Permutation.cs │ └── Similarity │ ├── CosineSimilarity.cs │ ├── DamerauLevenshteinDistance.cs │ ├── HammingDistance.cs │ ├── JaccardDistance.cs │ ├── JaccardSimilarity.cs │ ├── JaroSimilarity.cs │ ├── JaroWinklerDistance.cs │ └── OptimalStringAlignment.cs ├── C-Sharp.sln ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DataStructures.Tests ├── AATreeTests.cs ├── AVLTreeTests.cs ├── BinarySearchTreeTests.cs ├── BitArrayTests.cs ├── Cache │ ├── LfuCacheTests.cs │ └── LruCacheTests.cs ├── DataStructures.Tests.csproj ├── DisjointSet │ └── DisjointSetTests.cs ├── Fenwick │ └── BinaryIndexedTreeTests.cs ├── Graph │ └── DirectedWeightedGraphTests.cs ├── Hashing │ ├── HashTableTests.cs │ └── NumberTheory │ │ └── PrimeNumberTests.cs ├── Heap │ ├── BinaryHeapTests.cs │ ├── FibonacciHeaps │ │ └── FibonacciHeapTests.cs │ ├── MinMaxHeapTests.cs │ └── PairingHeap │ │ ├── PairingHeapComparerTests.cs │ │ └── PairingHeapTests.cs ├── InvertedIndexTests.cs ├── LinkedList │ ├── CircularLinkedListTests.cs │ ├── DoublyLinkedListTests.cs │ ├── LinkedListTests.cs │ └── SkipListTests.cs ├── Probabilistic │ ├── BloomFilterTests.cs │ ├── CountMinSketchTests.cs │ └── HyperLogLogTest.cs ├── Queue │ ├── ArrayBasedQueueTests.cs │ ├── ListBasedQueueTests.cs │ └── StackBasedQueueTests.cs ├── RedBlackTreeTests.cs ├── ScapegoatTree │ ├── ExtensionsTests.cs │ ├── ScapegoatTreeNodeTests.cs │ └── ScapegoatTreeTests.cs ├── SegmentTrees │ ├── SegmentTreeApplyTests.cs │ ├── SegmentTreeTests.cs │ └── SegmentTreeUpdateTest.cs ├── SortedListTests.cs ├── Stack │ ├── ArrayBasedStackTests.cs │ ├── ListBasedStackTests.cs │ └── QueueBasedStackTests.cs ├── TimelineTests.cs ├── Tries │ └── TrieTests.cs └── UnrolledList │ ├── UnrolledLinkedListNodeTests.cs │ └── UnrolledLinkedListTests.cs ├── DataStructures ├── AATree │ ├── AATree.cs │ └── AATreeNode.cs ├── AVLTree │ ├── AVLTree.cs │ └── AVLTreeNode.cs ├── BinarySearchTree │ ├── BinarySearchTree.cs │ └── BinarySearchTreeNode.cs ├── BitArray.cs ├── Cache │ ├── LfuCache.cs │ └── LruCache.cs ├── DataStructures.csproj ├── DisjointSet │ ├── DisjointSet.cs │ └── Node.cs ├── Fenwick │ └── BinaryIndexedTree.cs ├── Graph │ ├── DirectedWeightedGraph.cs │ ├── IDirectedWeightedGraph.cs │ └── Vertex.cs ├── Hashing │ ├── Entry.cs │ ├── HashTable.cs │ └── NumberTheory │ │ └── PrimeNumber.cs ├── Heap │ ├── BinaryHeap.cs │ ├── FibonacciHeap │ │ ├── FHeapNode.cs │ │ └── FibonacciHeap.cs │ ├── MinMaxHeap.cs │ └── PairingHeap │ │ ├── PairingHeap.cs │ │ ├── PairingHeapNode.cs │ │ ├── PairingNodeComparer.cs │ │ └── Sorting.cs ├── InvertedIndex.cs ├── LinkedList │ ├── CircularLinkedList │ │ ├── CircularLinkedList.cs │ │ └── CircularLinkedListNode.cs │ ├── DoublyLinkedList │ │ ├── DoublyLinkedList.cs │ │ └── DoublyLinkedListNode.cs │ ├── SinglyLinkedList │ │ ├── SinglyLinkedList.cs │ │ └── SinglyLinkedListNode.cs │ └── SkipList │ │ ├── SkipList.cs │ │ └── SkipListNode.cs ├── Probabilistic │ ├── BloomFilter.cs │ ├── CountMinSketch.cs │ └── HyperLogLog.cs ├── Queue │ ├── ArrayBasedQueue.cs │ ├── ListBasedQueue.cs │ └── StackBasedQueue.cs ├── RedBlackTree │ ├── RedBlackTree.cs │ └── RedBlackTreeNode.cs ├── ScapegoatTree │ ├── Extensions.cs │ ├── Node.cs │ └── ScapegoatTree.cs ├── SegmentTrees │ ├── SegmentTree.cs │ ├── SegmentTreeApply.cs │ └── SegmentTreeUpdate.cs ├── SortedList.cs ├── Stack │ ├── ArrayBasedStack.cs │ ├── ListBasedStack.cs │ └── QueueBasedStack.cs ├── Timeline.cs ├── Tries │ ├── Trie.cs │ └── TrieNode.cs └── UnrolledList │ ├── UnrolledLinkedList.cs │ └── UnrolledLinkedListNode.cs ├── LICENSE ├── README.md ├── Utilities.Tests ├── Extensions │ ├── DictionaryExtensionsTests.cs │ ├── MatrixExtensionsTests.cs │ ├── RandomExtensionsTests.cs │ └── VectorExtensionsTests.cs └── Utilities.Tests.csproj ├── Utilities ├── Exceptions │ └── ItemNotFoundException.cs ├── Extensions │ ├── DictionaryExtensions.cs │ ├── MatrixExtensions.cs │ ├── RandomExtensions.cs │ └── VectorExtensions.cs └── Utilities.csproj ├── stylecop.json └── stylecop.ruleset /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "The Algorithms C#", 3 | "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", 4 | "customizations": { 5 | "vscode": { 6 | "extensions": [ 7 | "ms-dotnettools.csharp", 8 | "ms-dotnettools.csdevkit", 9 | "nunit.nunit-adapter", 10 | "fluentassertions.fluentassertions" 11 | ] 12 | } 13 | }, 14 | "postCreateCommand": "sudo chown -R $(whoami) /workspaces" 15 | } -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @siriak 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: Something works wrong 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | How to reproduce the behavior. Initial conditions, parameters, etc. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Actual behavior** 20 | A clear and concise description of what has happened. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: Add something cool 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | I propose to add [algorithm/data structure] [name]. It helps to solve problems such as [...]. It's best described in book(s), on website(s): [...]. 11 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | - [ ] I have performed a self-review of my code 10 | - [ ] My code follows the style guidelines of this project 11 | - [ ] I have added tests that prove my fix is effective or that my feature works 12 | - [ ] New and existing unit tests pass locally with my changes 13 | - [ ] Comments in areas I changed are up to date 14 | - [ ] I have added comments to hard-to-understand areas of my code 15 | - [ ] I have made corresponding changes to the README.md 16 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v3 10 | with: 11 | fetch-depth: 0 12 | - name: Setup .NET SDK 13 | uses: actions/setup-dotnet@v3 14 | with: 15 | dotnet-version: 8.x 16 | - name: Restore 17 | run: dotnet restore 18 | - name: Build 19 | run: dotnet build --no-restore 20 | - name: Test 21 | run: dotnet test --no-restore --collect "XPlat Code Coverage" 22 | - name: Upload coverage to codecov (tokenless) 23 | if: >- 24 | github.event_name == 'pull_request' && 25 | github.event.pull_request.head.repo.full_name != github.repository 26 | uses: codecov/codecov-action@v4 27 | with: 28 | fail_ci_if_error: true 29 | - name: Upload coverage to codecov (with token) 30 | if: > 31 | github.repository == 'TheAlgorithms/C-Sharp' && 32 | (github.event_name != 'pull_request' || 33 | github.event.pull_request.head.repo.full_name == github.repository) 34 | uses: codecov/codecov-action@v4 35 | with: 36 | token: ${{ secrets.CODECOV_TOKEN }} 37 | fail_ci_if_error: true 38 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: 'Close stale issues and PRs' 2 | on: 3 | schedule: 4 | - cron: '0 0 * * *' 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v4 10 | with: 11 | stale-issue-message: 'This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.' 12 | close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.' 13 | stale-pr-message: 'This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.' 14 | close-pr-message: 'This PR was closed because it has been stalled for 7 days with no activity.' 15 | exempt-issue-labels: 'dont-close' 16 | exempt-pr-labels: 'dont-close' 17 | days-before-stale: 30 18 | days-before-close: 7 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Visual Studio cache/options directory 2 | .vs/ 3 | 4 | # Rider cache/options directory 5 | .idea/ 6 | 7 | # Rider user config file 8 | C-Sharp.sln.DotSettings.user 9 | 10 | # Build results 11 | bin/ 12 | obj/ 13 | TestResults/ 14 | -------------------------------------------------------------------------------- /Algorithms.Tests/Algorithms.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | false 6 | ..\stylecop.ruleset 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | 3 | [assembly: Parallelizable(ParallelScope.Children)] 4 | -------------------------------------------------------------------------------- /Algorithms.Tests/Compressors/TranslatorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Algorithms.DataCompression; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Compressors; 6 | 7 | public static class TranslatorTests 8 | { 9 | [Test] 10 | public static void TranslateCorrectly() 11 | { 12 | // Arrange 13 | var translator = new Translator(); 14 | var dict = new Dictionary 15 | { 16 | { "Hey", "Good day" }, 17 | { " ", " " }, 18 | { "man", "sir" }, 19 | { "!", "." }, 20 | }; 21 | 22 | // Act 23 | var translatedText = translator.Translate("Hey man!", dict); 24 | 25 | // Assert 26 | Assert.That(translatedText, Is.EqualTo("Good day sir.")); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Encoders/BlowfishEncoderTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Encoders; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Encoders; 6 | 7 | // Tests ported from the Java Algorithms repository 8 | 9 | public class BlowfishEncoderTests 10 | { 11 | private const string Key = "aabb09182736ccdd"; 12 | 13 | [Test] 14 | public void BlowfishEncoder_Encryption_ShouldWorkCorrectly() 15 | { 16 | // Arrange 17 | var encoder = new BlowfishEncoder(); 18 | encoder.GenerateKey(Key); 19 | 20 | const string plainText = "123456abcd132536"; 21 | const string cipherText = "d748ec383d3405f7"; 22 | 23 | // Act 24 | var result = encoder.Encrypt(plainText); 25 | 26 | // Assert 27 | result.Should().Be(cipherText); 28 | } 29 | 30 | [Test] 31 | public void BlowfishEncoder_Decryption_ShouldWorkCorrectly() 32 | { 33 | // Arrange 34 | var encoder = new BlowfishEncoder(); 35 | encoder.GenerateKey(Key); 36 | 37 | const string cipherText = "d748ec383d3405f7"; 38 | const string plainText = "123456abcd132536"; 39 | 40 | // Act 41 | var result = encoder.Decrypt(cipherText); 42 | 43 | // Assert 44 | result.Should().Be(plainText); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms.Tests/Encoders/CaesarEncoderTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Encoders; 2 | using NUnit.Framework; 3 | using NUnit.Framework.Internal; 4 | 5 | namespace Algorithms.Tests.Encoders; 6 | 7 | public static class CaesarEncoderTests 8 | { 9 | [Test] 10 | public static void DecodedStringIsTheSame([Random(100)] int key) 11 | { 12 | // Arrange 13 | var encoder = new CaesarEncoder(); 14 | var random = new Randomizer(); 15 | var message = random.GetString(); 16 | 17 | // Act 18 | var encoded = encoder.Encode(message, key); 19 | var decoded = encoder.Decode(encoded, key); 20 | 21 | // Assert 22 | Assert.That(decoded, Is.EqualTo(message)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms.Tests/Encoders/HillEnconderTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Encoders; 2 | using NUnit.Framework; 3 | using NUnit.Framework.Internal; 4 | 5 | namespace Algorithms.Tests.Encoders; 6 | 7 | public static class HillEnconderTests 8 | { 9 | [Test] 10 | [Repeat(100)] 11 | public static void DecodedStringIsTheSame() 12 | { 13 | // Arrange 14 | var encoder = new HillEncoder(); 15 | var random = new Randomizer(); 16 | var message = random.GetString(); 17 | 18 | var key = new double[,] { { 0, 4, 5 }, { 9, 2, -1 }, { 3, 17, 7 } }; 19 | 20 | // Act 21 | var encodedText = encoder.Encode(message, key); 22 | var decodeText = encoder.Decode(encodedText, key); 23 | 24 | // Assert 25 | Assert.That(decodeText, Is.EqualTo(message)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Encoders/NysiisEncoderTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Algorithms.Encoders; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Encoders; 7 | 8 | public class NysiisEncoderTests 9 | { 10 | private static readonly string[] Names = 11 | { 12 | "Jay", "John", "Jane", "Zayne", "Guerra", "Iga", "Cowan", "Louisa", "Arnie", "Olsen", "Corban", "Nava", 13 | "Cynthia Malone", "Amiee MacKee", "MacGyver", "Yasmin Edge", 14 | }; 15 | 16 | private static readonly string[] Expected = 17 | { 18 | "JY", "JAN", "JAN", "ZAYN", "GAR", "IG", "CAN", "LAS", "ARNY", "OLSAN", "CARBAN", "NAV", "CYNTANALAN", 19 | "ANANACY", "MCGYVAR", "YASNANADG", 20 | }; 21 | 22 | private static IEnumerable TestData => Names.Zip(Expected, (l, r) => new[] { l, r }); 23 | 24 | [TestCaseSource(nameof(TestData))] 25 | public void AttemptNysiis(string source, string expected) 26 | { 27 | var enc = new NysiisEncoder(); 28 | var nysiis = enc.Encode(source); 29 | Assert.That(nysiis, Is.EqualTo(expected)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms.Tests/Encoders/SoundexEncoderTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Algorithms.Encoders; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Encoders; 7 | 8 | public static class SoundexEncoderTest 9 | { 10 | private static readonly string[] Names = 11 | { 12 | "Robert", "Rupert", "Rubin", "Ashcraft", "Ashcroft", "Tymczak", "Pfister", "Honeyman", 13 | }; 14 | 15 | private static readonly string[] Expected = { "R163", "R163", "R150", "A261", "A261", "T522", "P236", "H555" }; 16 | 17 | private static IEnumerable TestData => Names.Zip(Expected, (l, r) => new[] { l, r }); 18 | 19 | [TestCaseSource(nameof(TestData))] 20 | public static void AttemptSoundex(string source, string encoded) 21 | { 22 | SoundexEncoder enc = new(); 23 | var nysiis = enc.Encode(source); 24 | Assert.That(encoded, Is.EqualTo(nysiis)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms.Tests/Financial/PresentValueTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Algorithms.Financial; 5 | using FluentAssertions; 6 | using NUnit.Framework; 7 | 8 | namespace Algorithms.Tests.Financial; 9 | 10 | public static class PresentValueTests 11 | { 12 | [TestCase(0.13,new[] { 10.0, 20.70, -293.0, 297.0 },4.69)] 13 | [TestCase(0.07,new[] { -109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, -42739.63)] 14 | [TestCase(0.07, new[] { 109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, 175519.15)] 15 | [TestCase(0.0, new[] { 109129.39, 30923.23, 15098.93, 29734.0, 39.0 }, 184924.55)] 16 | 17 | public static void Present_Value_General_Tests(double discountRate,double[] cashFlow ,double expected) 18 | => 19 | PresentValue.Calculate(discountRate, cashFlow.ToList()) 20 | .Should() 21 | .Be(expected); 22 | 23 | 24 | [TestCase(-1.0, new[] { 10.0, 20.70, -293.0, 297.0 })] 25 | [TestCase(1.0,new double[] {})] 26 | 27 | public static void Present_Value_Exception_Tests(double discountRate, double[] cashFlow) 28 | => Assert.Throws(() => PresentValue.Calculate(discountRate, cashFlow.ToList())); 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms.Tests/Helpers/IntComparer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Tests.Helpers; 4 | 5 | internal class IntComparer : IComparer 6 | { 7 | public int Compare(int x, int y) => x.CompareTo(y); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithms.Tests/Knapsack/NaiveKnapsackSolverTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Algorithms.Knapsack; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Knapsack; 6 | 7 | public static class NaiveKnapsackSolverTests 8 | { 9 | [Test] 10 | public static void TakesHalf( 11 | [Random(0, 1000, 100, Distinct = true)] 12 | int length) 13 | { 14 | //Arrange 15 | var solver = new NaiveKnapsackSolver(); 16 | var items = Enumerable.Repeat(42, 2 * length).ToArray(); 17 | var expectedResult = Enumerable.Repeat(42, length); 18 | 19 | //Act 20 | var result = solver.Solve(items, length, _ => 1, _ => 1); 21 | 22 | //Assert 23 | Assert.That(result, Is.EqualTo(expectedResult)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms.Tests/LinearAlgebra/Distances/ChebyshevTests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using Algorithms.LinearAlgebra.Distances; 3 | using FluentAssertions; 4 | using System; 5 | 6 | namespace Algorithms.Tests.LinearAlgebra.Distances; 7 | 8 | public class ChebyshevTests 9 | { 10 | [TestCase(new[] { 1.0, 1.0 }, new[] { 2.0, 2.0 }, 1.0)] 11 | [TestCase(new[] { 1.0, 1.0, 9.0 }, new[] { 2.0, 2.0, -5.2 }, 14.2)] 12 | [TestCase(new[] { 1.0, 2.0, 3.0 }, new[] { 1.0, 2.0, 3.0 }, 0.0)] 13 | [TestCase(new[] { 1.0, 2.0, 3.0, 4.0 }, new[] { 1.75, 2.25, -3.0, 0.5 }, 6.0)] 14 | public void DistanceTest(double[] point1, double[] point2, double expectedDistance) 15 | { 16 | Chebyshev.Distance(point1, point2).Should().BeApproximately(expectedDistance, 0.01); 17 | } 18 | 19 | [TestCase(new[] { 2.0, 3.0 }, new[] { -1.0 })] 20 | [TestCase(new[] { 1.0 }, new[] { 1.0, 2.0, 3.0 })] 21 | public void DistanceThrowsArgumentExceptionOnDifferentPointDimensions(double[] point1, double[] point2) 22 | { 23 | Action action = () => Chebyshev.Distance(point1, point2); 24 | action.Should().Throw(); 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/AdditionWithoutArithmeticsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using Algorithms.Numeric; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class AdditionWithoutArithmeticTests 9 | { 10 | [TestCase(3, 5, 8)] 11 | [TestCase(13, 5, 18)] 12 | [TestCase(-7, 2, -5)] 13 | [TestCase(0, -7, -7)] 14 | [TestCase(-321, 0, -321)] 15 | public static void CalculateAdditionWithoutArithmetic_Test(int first, int second, int expectedResult) 16 | { 17 | // Act 18 | var result = AdditionWithoutArithmetic.CalculateAdditionWithoutArithmetic(first, second); 19 | 20 | // Assert 21 | Assert.That(result, Is.EqualTo(expectedResult)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/AliquotSumCalculatorTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Numeric; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class AliquotSumCalculatorTests 9 | { 10 | [TestCase(1, 0)] 11 | [TestCase(3, 1)] 12 | [TestCase(25, 6)] 13 | [TestCase(99, 57)] 14 | public static void CalculateSum_SumIsCorrect(int number, int expectedSum) 15 | { 16 | // Arrange 17 | 18 | // Act 19 | var result = AliquotSumCalculator.CalculateAliquotSum(number); 20 | 21 | // Assert 22 | result.Should().Be(expectedSum); 23 | } 24 | 25 | [TestCase(-2)] 26 | public static void CalculateSum_NegativeInput_ExceptionIsThrown(int number) 27 | { 28 | // Arrange 29 | Action act = () => AliquotSumCalculator.CalculateAliquotSum(number); 30 | 31 | // Assert 32 | act.Should().Throw(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/AmicableNumbersTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric; 5 | 6 | public static class AmicableNumbersTest 7 | { 8 | [TestCase(220, 284)] 9 | [TestCase(1184, 1210)] 10 | [TestCase(2620, 2924)] 11 | [TestCase(5020, 5564)] 12 | public static void AmicableNumbersChecker_Test(int x, int y) 13 | { 14 | // Arrange 15 | 16 | // Act 17 | var result = AmicableNumbersChecker.AreAmicableNumbers(x, y); 18 | 19 | // Assert 20 | Assert.That(result, Is.True); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/BinomialCoefficientTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using Algorithms.Numeric; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class BinomialCoefficientTests 9 | { 10 | [TestCase(4, 2, 6)] 11 | [TestCase(7, 3, 35)] 12 | public static void CalculateFromPairs(int n, int k, int expected) 13 | { 14 | // Arrange 15 | 16 | // Act 17 | var result = BinomialCoefficient.Calculate(new BigInteger(n), new BigInteger(k)); 18 | 19 | // Assert 20 | Assert.That(result, Is.EqualTo(new BigInteger(expected))); 21 | } 22 | 23 | [TestCase(3, 7)] 24 | public static void TeoremCalculateThrowsException(int n, int k) 25 | { 26 | // Arrange 27 | 28 | // Act 29 | 30 | // Assert 31 | _ = Assert.Throws(() => BinomialCoefficient.Calculate(new BigInteger(n), new BigInteger(k))); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/CeilTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using Algorithms.Numeric; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class CeilTests 9 | { 10 | [TestCase(0.0, 0)] 11 | [TestCase(1.1, 2)] 12 | [TestCase(1.9, 2)] 13 | [TestCase(1.0, 1)] 14 | [TestCase(-1.1, -1)] 15 | [TestCase(-1.9, -1)] 16 | [TestCase(-1.0, -1)] 17 | [TestCase(1000000000.1, 1000000001)] 18 | [TestCase(1, 1)] 19 | public static void GetsCeilVal(T inputNum, T expected) where T : INumber 20 | { 21 | // Act 22 | var result = Ceil.CeilVal(inputNum); 23 | 24 | // Assert 25 | Assert.That(result, Is.EqualTo(expected)); 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/FactorialTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using Algorithms.Numeric; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class FactorialTests 9 | { 10 | [TestCase(0, "1")] 11 | [TestCase(1, "1")] 12 | [TestCase(4, "24")] 13 | [TestCase(10, "3628800")] 14 | [TestCase(18, "6402373705728000")] 15 | public static void GetsFactorial(int input, string expected) 16 | { 17 | // Arrange 18 | BigInteger expectedBigInt = BigInteger.Parse(expected); 19 | 20 | // Act 21 | var result = Factorial.Calculate(input); 22 | 23 | // Assert 24 | Assert.That(result, Is.EqualTo(expectedBigInt)); 25 | } 26 | 27 | [TestCase(-5)] 28 | [TestCase(-10)] 29 | public static void GetsFactorialExceptionForNegativeNumbers(int num) 30 | { 31 | // Arrange 32 | 33 | // Act 34 | void Act() => Factorial.Calculate(num); 35 | 36 | // Assert 37 | _ = Assert.Throws(Act); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/Factorization/TrialDivisionFactorizerTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric.Factorization; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric.Factorization; 5 | 6 | public static class TrialDivisionFactorizerTests 7 | { 8 | [TestCase(2)] 9 | [TestCase(3)] 10 | [TestCase(29)] 11 | [TestCase(31)] 12 | public static void PrimeNumberFactorizationFails(int p) 13 | { 14 | // Arrange 15 | var factorizer = new TrialDivisionFactorizer(); 16 | 17 | // Act 18 | var success = factorizer.TryFactor(p, out _); 19 | 20 | // Assert 21 | Assert.That(success, Is.False); 22 | } 23 | 24 | [TestCase(4, 2)] 25 | [TestCase(6, 2)] 26 | [TestCase(8, 2)] 27 | [TestCase(9, 3)] 28 | [TestCase(15, 3)] 29 | [TestCase(35, 5)] 30 | [TestCase(49, 7)] 31 | [TestCase(77, 7)] 32 | public static void PrimeNumberFactorizationSucceeds(int n, int expected) 33 | { 34 | // Arrange 35 | var factorizer = new TrialDivisionFactorizer(); 36 | 37 | // Act 38 | var success = factorizer.TryFactor(n, out var factor); 39 | 40 | // Assert 41 | Assert.That(success, Is.True); 42 | Assert.That(factor, Is.EqualTo(expected)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/FloorTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using Algorithms.Numeric; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public static class FloorTests 9 | { 10 | [TestCase(0.0, 0)] 11 | [TestCase(1.1, 1)] 12 | [TestCase(1.9, 1)] 13 | [TestCase(1.0, 1)] 14 | [TestCase(-1.1, -2)] 15 | [TestCase(-1.9, -2)] 16 | [TestCase(-1.0, -1)] 17 | [TestCase(1000000000.1, 1000000000)] 18 | [TestCase(1, 1)] 19 | public static void GetsFloorVal(T inputNum, T expected) where T : INumber 20 | { 21 | // Act 22 | var result = Floor.FloorVal(inputNum); 23 | 24 | // Assert 25 | Assert.That(result, Is.EqualTo(expected)); 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/GaussJordanEliminationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Numeric; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Numeric; 6 | 7 | /// 8 | /// Class for testing Gauss-Jordan Elimination Algorithm. 9 | /// 10 | public static class GaussJordanEliminationTests 11 | { 12 | [Test] 13 | public static void NonSquaredMatrixThrowsException() 14 | { 15 | // Arrange 16 | var solver = new GaussJordanElimination(); 17 | var input = new double[,] { { 2, -1, 5 }, { 0, 2, 1 }, { 3, 17, 7 } }; 18 | 19 | // Act 20 | void Act() => solver.Solve(input); 21 | 22 | // Assert 23 | _ = Assert.Throws(Act); 24 | } 25 | 26 | [Test] 27 | public static void UnableToSolveSingularMatrix() 28 | { 29 | // Arrange 30 | var solver = new GaussJordanElimination(); 31 | var input = new double[,] { { 0, 0, 0 }, { 0, 0, 0 } }; 32 | 33 | // Act 34 | var result = solver.Solve(input); 35 | 36 | // Assert 37 | Assert.That(result, Is.False); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/GreatestCommonDivisor/BinaryGreatestCommonDivisorFinderTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric.GreatestCommonDivisor; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric.GreatestCommonDivisor; 5 | 6 | public static class BinaryGreatestCommonDivisorFinderTests 7 | { 8 | [TestCase(2, 3, 1)] 9 | [TestCase(1, 1, 1)] 10 | [TestCase(13, 17, 1)] 11 | [TestCase(0, 17, 17)] 12 | [TestCase(17, 0, 17)] 13 | [TestCase(17, 17, 17)] 14 | [TestCase(2 * 17, 17, 17)] 15 | [TestCase(0, 0, 0)] 16 | [TestCase(2 * 13 * 17, 4 * 9 * 13, 2 * 13)] 17 | public static void GreatestCommonDivisorCorrect(int a, int b, int expectedGcd) 18 | { 19 | // Arrange 20 | var gcdFinder = new BinaryGreatestCommonDivisorFinder(); 21 | 22 | // Act 23 | var actualGcd = gcdFinder.FindGcd(a, b); 24 | 25 | // Assert 26 | Assert.That(actualGcd, Is.EqualTo(expectedGcd)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinderTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric.GreatestCommonDivisor; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric.GreatestCommonDivisor; 5 | 6 | public static class EuclideanGreatestCommonDivisorFinderTests 7 | { 8 | [TestCase(2, 3, 1)] 9 | [TestCase(1, 1, 1)] 10 | [TestCase(13, 17, 1)] 11 | [TestCase(0, 17, 17)] 12 | [TestCase(17, 0, 17)] 13 | [TestCase(17, 17, 17)] 14 | [TestCase(2 * 17, 17, 17)] 15 | [TestCase(0, 0, int.MaxValue)] 16 | [TestCase(2 * 13 * 17, 4 * 9 * 13, 2 * 13)] 17 | public static void GreatestCommonDivisorCorrect(int a, int b, int expectedGcd) 18 | { 19 | // Arrange 20 | var gcdFinder = new EuclideanGreatestCommonDivisorFinder(); 21 | 22 | // Act 23 | var actualGcd = gcdFinder.FindGcd(a, b); 24 | 25 | // Assert 26 | Assert.That(actualGcd, Is.EqualTo(expectedGcd)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/JosephusProblemTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Numeric; 3 | using NUnit.Framework; 4 | 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public class JosephusProblemTest 9 | { 10 | 11 | [TestCase(10, 0)] 12 | [TestCase(10, -1)] 13 | public void JosephusProblemInvalidStepSize(long groupSize, long step) 14 | { 15 | Assert.Throws(Is.TypeOf() 16 | .And.Message.EqualTo("The step cannot be smaller than 1"), 17 | delegate { JosephusProblem.FindWinner(groupSize, step); }); 18 | } 19 | 20 | [TestCase(10, 12)] 21 | public void JosephusProblemStepSizeGreaterThanGroup(long groupSize, long step) 22 | { 23 | Assert.Throws(Is.TypeOf() 24 | .And.Message.EqualTo("The step cannot be greater than the size of the group"), 25 | delegate { JosephusProblem.FindWinner(groupSize, step); }); 26 | } 27 | 28 | [TestCase(10, 2, 5)] 29 | [TestCase(10, 8, 1)] 30 | [TestCase(254, 18, 92)] 31 | [TestCase(3948, 614, 2160)] 32 | [TestCase(86521, 65903, 29473)] 33 | public void JosephusProblemWinnerCalculation(long groupSize, long step, long position) 34 | { 35 | Assert.That(JosephusProblem.FindWinner(groupSize, step), Is.EqualTo(position)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/KeithNumberTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using NUnit.Framework; 3 | using System; 4 | 5 | namespace Algorithms.Tests.Numeric; 6 | 7 | public static class KeithNumberTest 8 | { 9 | [TestCase(14)] 10 | [TestCase(47)] 11 | [TestCase(197)] 12 | [TestCase(7909)] 13 | public static void KeithNumberWork(int number) 14 | { 15 | // Act 16 | var result = KeithNumberChecker.IsKeithNumber(number); 17 | 18 | // Assert 19 | Assert.That(result, Is.True); 20 | } 21 | 22 | [TestCase(-2)] 23 | public static void KeithNumberShouldThrowEx(int number) 24 | { 25 | // Arrange 26 | 27 | // Assert 28 | Assert.Throws(() => KeithNumberChecker.IsKeithNumber(number)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/KrishnamurthyNumberCheckerTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric; 5 | 6 | public class KrishnamurthyNumberCheckerTests 7 | { 8 | [TestCase(1)] 9 | [TestCase(2)] 10 | [TestCase(145)] 11 | [TestCase(40585)] 12 | public void KrishnamurthyNumberCheckerKnownNumbers(int number) 13 | { 14 | var result = KrishnamurthyNumberChecker.IsKMurthyNumber(number); 15 | Assert.That(result, Is.True); 16 | } 17 | 18 | [TestCase(3)] 19 | [TestCase(4)] 20 | [TestCase(239847)] 21 | [TestCase(12374)] 22 | [TestCase(0)] 23 | [TestCase(-1)] 24 | public void KrishnamurthyNumberCheckerNotKMNumber(int number) 25 | { 26 | var result = KrishnamurthyNumberChecker.IsKMurthyNumber(number); 27 | Assert.That(result, Is.False); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/ModularExponentiationTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using System; 3 | using NUnit.Framework; 4 | using FluentAssertions; 5 | 6 | namespace Algorithms.Tests.Numeric; 7 | 8 | public class ModularExponentiationTest 9 | { 10 | [TestCase(3, 6, 11, 3)] 11 | [TestCase(5, 3, 13, 8)] 12 | [TestCase(2, 7, 17, 9)] 13 | [TestCase(7, 4, 16, 1)] 14 | [TestCase(7, 2, 11, 5)] 15 | [TestCase(4, 13, 497, 445)] 16 | [TestCase(13, 3, 1, 0)] 17 | public void ModularExponentiationCorrect(int b, int e, int m, int expectedRes) 18 | { 19 | var modularExponentiation = new ModularExponentiation(); 20 | var actualRes = modularExponentiation.ModularPow(b, e, m); 21 | actualRes.Should().Be(expectedRes); 22 | } 23 | 24 | [TestCase(17, 7, -3)] 25 | [TestCase(11, 3, -5)] 26 | [TestCase(14, 3, 0)] 27 | public void ModularExponentiationNegativeMod(int b, int e, int m) 28 | { 29 | var modularExponentiation = new ModularExponentiation(); 30 | Action res = () => modularExponentiation.ModularPow(b, e, m); 31 | res.Should().Throw() 32 | .WithMessage(String.Format("{0} is not a positive integer", m)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/NarcissisticNumberTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric; 5 | 6 | public static class NarcissisticNumberTest 7 | { 8 | [TestCase(2, ExpectedResult = true)] 9 | [TestCase(3, ExpectedResult = true)] 10 | [TestCase(28, ExpectedResult = false)] 11 | [TestCase(153, ExpectedResult = true)] 12 | [TestCase(170, ExpectedResult = false)] 13 | [TestCase(371, ExpectedResult = true)] 14 | public static bool NarcissisticNumberWork(int number) 15 | { 16 | // Arrange 17 | 18 | // Act 19 | var result = NarcissisticNumberChecker.IsNarcissistic(number); 20 | 21 | // Assert 22 | return result; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/PerfectNumberTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Numeric; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Numeric; 6 | 7 | public static class PerfectNumberTests 8 | { 9 | [TestCase(6)] 10 | [TestCase(28)] 11 | [TestCase(496)] 12 | [TestCase(8128)] 13 | public static void PerfectNumberWork(int number) 14 | { 15 | // Arrange 16 | 17 | // Act 18 | var result = PerfectNumberChecker.IsPerfectNumber(number); 19 | 20 | // Assert 21 | Assert.That(result, Is.True); 22 | } 23 | 24 | [TestCase(-2)] 25 | public static void PerfectNumberShouldThrowEx(int number) 26 | { 27 | // Arrange 28 | 29 | // Assert 30 | Assert.Throws(() => PerfectNumberChecker.IsPerfectNumber(number)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms.Tests/Numeric/PerfectSquareTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Numeric; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Numeric; 5 | 6 | public static class PerfectSquareTests 7 | { 8 | [TestCase(-4, ExpectedResult = false)] 9 | [TestCase(4, ExpectedResult = true)] 10 | [TestCase(9, ExpectedResult = true)] 11 | [TestCase(10, ExpectedResult = false)] 12 | [TestCase(16, ExpectedResult = true)] 13 | [TestCase(70, ExpectedResult = false)] 14 | [TestCase(81, ExpectedResult = true)] 15 | public static bool IsPerfectSquare_ResultIsCorrect(int number) 16 | { 17 | // Arrange 18 | 19 | // Act 20 | var result = PerfectSquareChecker.IsPerfectSquare(number); 21 | 22 | // Assert 23 | return result; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms.Tests/Other/FermatPrimeCheckerTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Other; 2 | using NUnit.Framework; 3 | using NUnit.Framework.Internal; 4 | 5 | namespace Algorithms.Tests.Other; 6 | 7 | public static class FermatPrimeCheckerTests 8 | { 9 | [TestCase(5, true)] 10 | [TestCase(2633, true)] 11 | [TestCase(9439, true)] 12 | [TestCase(1, false)] 13 | [TestCase(8, false)] 14 | public static void IsProbablePrime(int inputNum, bool expected) 15 | { 16 | // Arrange 17 | var random = new Randomizer(); 18 | var times = random.Next(1, 1000); 19 | 20 | // Act 21 | var result = FermatPrimeChecker.IsPrime(inputNum, times); 22 | 23 | // Assert 24 | Assert.That(result, Is.EqualTo(expected)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms.Tests/Other/GeoLocationTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Other; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Other; 6 | 7 | public static class GeoLocationTests 8 | { 9 | [TestCase(53.430488d, -2.96129d, 53.430488d, -2.96129d, 0d)] 10 | [TestCase(53.430971d, -2.959806d, 53.430242d, -2.960830d, 105d)] 11 | public static void CalculateDistanceFromLatLngTest( 12 | double lat1, 13 | double lng1, 14 | double lat2, 15 | double lng2, 16 | double expectedValue) 17 | { 18 | var result = GeoLocation.CalculateDistanceFromLatLng(lat1, lng1, lat2, lng2); 19 | var actualValue = Convert.ToDouble(result); 20 | 21 | // Assert 22 | Assert.That(actualValue, Is.EqualTo(expectedValue).Within(1d)); // Accept if distance diff is +/-1 meters. 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms.Tests/Other/JulianEasterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using Algorithms.Other; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Other; 7 | 8 | /// 9 | /// A class for testing the Meeus's Julian Easter algorithm. 10 | /// 11 | public static class JulianEasterTest 12 | { 13 | [TestCaseSource(nameof(CalculateCases))] 14 | public static void CalculateTest(int year, DateTime expected) 15 | { 16 | var result = JulianEaster.Calculate(year); 17 | 18 | Assert.That(result, Is.EqualTo(expected)); 19 | } 20 | 21 | private static readonly object[] CalculateCases = 22 | { 23 | new object[] { 1800, new DateTime(1800, 04, 08, 00, 00, 00, DateTimeKind.Utc) }, 24 | new object[] { 1950, new DateTime(1950, 03, 27, 00, 00, 00, DateTimeKind.Utc) }, 25 | new object[] { 1991, new DateTime(1991, 03, 25, 00, 00, 00, DateTimeKind.Utc) }, 26 | new object[] { 2000, new DateTime(2000, 04, 17, 00, 00, 00, DateTimeKind.Utc) }, 27 | new object[] { 2199, new DateTime(2199, 04, 07, 00, 00, 00, DateTimeKind.Utc) } 28 | }; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms.Tests/Other/PollardsRhoFactorizingTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Other; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Other; 5 | 6 | public class PollardsRhoFactorizingTests 7 | { 8 | [TestCase(8051, 97)] 9 | [TestCase(105, 21)] 10 | [TestCase(253, 11)] 11 | [TestCase(10403, 101)] 12 | [TestCase(187, 11)] 13 | public void SimpleTest(int number, int expectedResult) 14 | { 15 | var result = PollardsRhoFactorizing.Calculate(number); 16 | Assert.That(result, Is.EqualTo(expectedResult)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Problems/DynamicProgramming/CoinChange/GenerateChangesDictionaryTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Algorithms.Problems.DynamicProgramming.CoinChange; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Problems.DynamicProgramming.CoinChange; 7 | 8 | [TestFixture] 9 | public class GenerateChangesDictionaryTests 10 | { 11 | [Test] 12 | public void GenerateChangesDictionaryTest_Success() 13 | { 14 | const int coin = 6; 15 | var coins = new[] { 1, 3, 4 }; 16 | var changeDictionary = DynamicCoinChangeSolver.GenerateChangesDictionary(coin, coins); 17 | 18 | changeDictionary[1].SequenceEqual(new[] { 0 }).Should().BeTrue(); 19 | changeDictionary[2].SequenceEqual(new[] { 1 }).Should().BeTrue(); 20 | changeDictionary[3].SequenceEqual(new[] { 0, 2 }).Should().BeTrue(); 21 | changeDictionary[4].SequenceEqual(new[] { 0, 1, 3 }).Should().BeTrue(); 22 | changeDictionary[5].SequenceEqual(new[] { 1, 2, 4 }).Should().BeTrue(); 23 | changeDictionary[6].SequenceEqual(new[] { 2, 3, 5 }).Should().BeTrue(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms.Tests/Problems/DynamicProgramming/CoinChange/GetMinimalNextCoinTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Problems.DynamicProgramming.CoinChange; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Problems.DynamicProgramming.CoinChange; 6 | 7 | public class GetMinimalNextCoinTests 8 | { 9 | [Test] 10 | public void GetMinimalNextCoinTest_Success() 11 | { 12 | const int coin = 6; 13 | var coins = new[] { 1, 3, 4 }; 14 | var exchangeDict = DynamicCoinChangeSolver.GenerateChangesDictionary(coin, coins); 15 | var nextCoin = DynamicCoinChangeSolver.GetMinimalNextCoin(6, exchangeDict); 16 | 17 | nextCoin.Should().Be(3); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Problems/DynamicProgramming/CoinChange/MakeCoinChangeDynamicTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Algorithms.Problems.DynamicProgramming.CoinChange; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Problems.DynamicProgramming.CoinChange; 7 | 8 | [TestFixture] 9 | public class MakeCoinChangeDynamicTests 10 | { 11 | [Test] 12 | public void MakeCoinChangeDynamicTest_Success() 13 | { 14 | DynamicCoinChangeSolver 15 | .MakeCoinChangeDynamic(6, new[] { 1, 3, 4 }) 16 | .SequenceEqual(new[] { 3, 3 }) 17 | .Should().BeTrue(); 18 | 19 | DynamicCoinChangeSolver 20 | .MakeCoinChangeDynamic(8, new[] { 1, 3, 4 }) 21 | .SequenceEqual(new[] { 4, 4 }) 22 | .Should().BeTrue(); 23 | 24 | DynamicCoinChangeSolver 25 | .MakeCoinChangeDynamic(25, new[] { 1, 3, 4, 12, 13, 14 }) 26 | .SequenceEqual(new[] { 13, 12 }) 27 | .Should().BeTrue(); 28 | 29 | DynamicCoinChangeSolver 30 | .MakeCoinChangeDynamic(26, new[] { 1, 3, 4, 12, 13, 14 }) 31 | .SequenceEqual(new[] { 14, 12 }) 32 | .Should().BeTrue(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms.Tests/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistanceTests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using Algorithms.Problems.DynamicProgramming; 3 | 4 | namespace Algorithms.Tests.DynamicProgramming; 5 | 6 | public class LevenshteinDistanceTests 7 | { 8 | [TestCase("kitten", "sitting", 3)] 9 | [TestCase("bob", "bond", 2)] 10 | [TestCase("algorithm", "logarithm", 3)] 11 | [TestCase("star", "", 4)] 12 | [TestCase("", "star", 4)] 13 | [TestCase("abcde", "12345", 5)] 14 | public void Calculate_ReturnsCorrectLevenshteinDistance(string source, string destination, int expectedDistance) 15 | { 16 | var result = LevenshteinDistance.Calculate(source, destination); 17 | Assert.That(result, Is.EqualTo(expectedDistance)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Search/BoyerMooreTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Search; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using NUnit.Framework; 6 | using NUnit.Framework.Internal; 7 | 8 | namespace Algorithms.Tests.Search; 9 | 10 | public class BoyerMoore_Tests 11 | { 12 | [Test] 13 | public void BoyerMoore_Majority_Finder_Test() 14 | { 15 | var elementCount = 1000; 16 | 17 | var rnd = new Random(); 18 | var randomNumbers = new List(); 19 | 20 | while (randomNumbers.Count < elementCount / 2) 21 | { 22 | randomNumbers.Add(rnd.Next(0, elementCount)); 23 | } 24 | 25 | var majorityElement = rnd.Next(0, elementCount); 26 | 27 | randomNumbers.AddRange(Enumerable.Repeat(majorityElement, elementCount / 2 + 1)); 28 | randomNumbers = randomNumbers.OrderBy(x => rnd.Next()).ToList(); 29 | 30 | var expected = majorityElement; 31 | var actual = BoyerMoore.FindMajority(randomNumbers); 32 | 33 | Assert.That(expected, Is.EqualTo(actual)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms.Tests/Search/Helper.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Search; 5 | 6 | public static class Helper 7 | { 8 | public static int[] GetSortedArray(int length) => 9 | Enumerable.Range(0, length) 10 | .Select(_ => TestContext.CurrentContext.Random.Next(1_000_000)) 11 | .OrderBy(x => x) 12 | .ToArray(); 13 | 14 | public static int GetItemIn(int[] arr) => arr[TestContext.CurrentContext.Random.Next(arr.Length)]; 15 | 16 | public static int GetItemNotIn(int[] arr) 17 | { 18 | int item; 19 | do 20 | { 21 | item = TestContext.CurrentContext.Random.Next(arr.Min(), arr.Max() + 1); 22 | } 23 | while (arr.Contains(item)); 24 | 25 | return item; 26 | } 27 | 28 | public static int GetItemSmallerThanAllIn(int[] arr) => arr.Min() - 1; 29 | 30 | public static int GetItemBiggerThanAllIn(int[] arr) => arr.Max() + 1; 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/AllOnesSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Sequences; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | using System; 5 | using System.Linq; 6 | using System.Numerics; 7 | 8 | namespace Algorithms.Tests.Sequences; 9 | public class AllOnesSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new AllOnesSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/AllThreesSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Sequences; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | using System; 5 | using System.Linq; 6 | using System.Numerics; 7 | 8 | namespace Algorithms.Tests.Sequences; 9 | public class AllThreesSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new AllThreesSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/AllTwosSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Sequences; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | using System; 5 | using System.Linq; 6 | using System.Numerics; 7 | 8 | namespace Algorithms.Tests.Sequences; 9 | public class AllTwosSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new AllTwosSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/BinaryPrimeConstantSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class BinaryPrimeConstantSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new BinaryPrimeConstantSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 1, 1, 0, 1, 0, 1, 0, 0, 0 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/BinomialSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class BinomialSequenceTests 10 | { 11 | [Test] 12 | public void First4RowsCorrect() 13 | { 14 | var sequence = new BinomialSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 1, 1, 1, 2, 1, 1, 3, 3, 1 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/CakeNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class CakeNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First46ElementsCorrect() 13 | { 14 | var sequence = new CakeNumbersSequence().Sequence.Take(46); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 17 | 1, 2, 4, 8, 15, 26, 42, 64, 93, 130, 18 | 176, 232, 299, 378, 470, 576, 697, 834, 988, 1160, 19 | 1351, 1562, 1794, 2048, 2325, 2626, 2952, 3304, 3683, 4090, 20 | 4526, 4992, 5489, 6018, 6580, 7176, 7807, 8474, 9178, 9920, 21 | 10701, 11522, 12384, 13288, 14235, 15226 22 | }) 23 | .Should().BeTrue(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/CatalanSequenceTest.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class CatalanSequenceTest 10 | { 11 | [Test] 12 | public void First30ItemsCorrect() 13 | { 14 | var sequence = new CatalanSequence().Sequence.Take(30); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 16 | 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 17 | 91482563640, 343059613650, 1289904147324, 4861946401452, 18367353072152, 18 | 69533550916004, 263747951750360, 1002242216651368}) 19 | .Should().BeTrue(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/CentralPolygonalNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class CentralPolygonalNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First53ElementsCorrect() 13 | { 14 | var sequence = new CentralPolygonalNumbersSequence().Sequence.Take(53); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 17 | 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, 154, 172, 191, 211, 232, 254, 18 | 277, 301, 326, 352, 379, 407, 436, 466, 497, 529, 562, 596, 631, 667, 704, 742, 781, 821, 862, 904, 19 | 947, 991, 1036, 1082, 1129, 1177, 1226, 1276, 1327, 1379, 20 | }) 21 | .Should().BeTrue(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/CubesSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class CubesSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new CubesSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 1, 8, 27, 64, 125, 216, 343, 512, 729 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/DivisorsCountSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class DivisorsCountSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | // These values are taken from https://oeis.org/A000005 for comparison. 15 | var oeisSource = new BigInteger[] 16 | { 17 | 1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2, 18 | 4, 4, 5, 2, 6, 2, 6, 4, 4, 2, 8, 3, 4, 19 | 4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4, 20 | 8, 2, 8, 2, 6, 6, 4, 2, 10, 3, 6, 4, 6, 21 | 2, 8, 4, 8, 4, 4, 2, 12, 2, 4, 6, 7, 4, 22 | 8, 2, 6, 4, 8, 2, 12, 2, 4, 6, 6, 4, 8, 23 | 2, 10, 5, 4, 2, 12, 4, 4, 4, 8, 2, 12, 4, 24 | 6, 4, 4, 4, 12, 2, 6, 6, 9, 2, 8, 2, 8, 25 | }; 26 | 27 | var sequence = new DivisorsCountSequence().Sequence.Take(oeisSource.Length); 28 | sequence.SequenceEqual(oeisSource).Should().BeTrue(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/EuclidNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class EuclidNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new EuclidNumbersSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 2, 3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871 }) 17 | .Should().BeTrue(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/FactorialSequenceTest.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class FactorialSequenceTest 10 | { 11 | [Test] 12 | public void First10ItemsCorrect() 13 | { 14 | var sequence = new FactorialSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/FermatNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class FermatNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First5ElementsCorrect() 13 | { 14 | var sequence = new FermatNumbersSequence().Sequence.Take(5); 15 | sequence.SequenceEqual(new BigInteger[] { 3, 5, 17, 257, 65537 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/FermatPrimesSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class FermatPrimesSequenceTests 10 | { 11 | [Test] 12 | public void All5ElementsCorrect() 13 | { 14 | var sequence = new FermatPrimesSequence().Sequence.Take(5); 15 | sequence.SequenceEqual(new BigInteger[] { 3, 5, 17, 257, 65537 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/FibonacciSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class FibonacciSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new FibonacciSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/GolombsSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class GolombsSequenceTests 10 | { 11 | [Test] 12 | public void First50ElementsCorrect() 13 | { 14 | // Taken from https://oeis.org/A001462 15 | var expected = new BigInteger[] { 16 | 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 17 | 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 18 | 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 19 | 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 20 | 12, 12, 12, 12, 13, 13, 13, 13, 13, 13}; 21 | 22 | var sequence = new GolombsSequence().Sequence.Take(50); 23 | 24 | sequence.SequenceEqual(expected).Should().BeTrue(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/KolakoskiSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class KolakoskiSequenceTests 10 | { 11 | [Test] 12 | public void First100ElementsCorrect() 13 | { 14 | // Taken from https://oeis.org/A000002 15 | var expected = new BigInteger[] 16 | { 17 | 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 18 | 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 19 | 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 20 | 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 21 | 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 22 | 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 23 | 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 24 | 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 25 | 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 26 | 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 27 | }; 28 | 29 | var sequence = new KolakoskiSequence().Sequence.Take(100); 30 | var sequence2 = new KolakoskiSequence2().Sequence.Take(100); 31 | 32 | sequence.Should().Equal(expected); 33 | sequence2.Should().Equal(expected); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/KummerNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class KummerNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new KummerNumbersSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 1, 5, 29, 209, 2309, 30029, 510509, 9699689, 223092869, 6469693229 }) 17 | .Should().BeTrue(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/MatchstickTriangleSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | [TestFixture] 10 | public static class MatchstickTriangleSequenceTests 11 | { 12 | private static BigInteger[] _testList = { 13 | 0, 1, 5, 13, 27, 48, 78, 118, 170, 235, 315, 411, 525, 658, 14 | 812, 988, 1188, 1413, 1665, 1945, 2255, 2596, 2970, 3378, 15 | 3822, 4303, 4823, 5383, 5985, 6630, 7320, 8056, 8840, 9673, 16 | 10557, 11493, 12483, 13528, 14630, 15790, 17010, 18291, 17 | 19635, 21043, 22517, 18 | }; 19 | /// 20 | /// This test uses the list values provided from http://oeis.org/A002717/list. 21 | /// 22 | [Test] 23 | public static void TestOeisList() 24 | { 25 | var sequence = new MatchstickTriangleSequence().Sequence.Take(_testList.Length); 26 | sequence.SequenceEqual(_testList).Should().BeTrue(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/NaturalSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class NaturalSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new NaturalSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/NegativeIntegersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class NegativeIntegersSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new NegativeIntegersSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/NumberOfBooleanFunctionsSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class NumberOfBooleanFunctionsSequenceTests 10 | { 11 | [Test] 12 | public void First5ElementsCorrect() 13 | { 14 | var sequence = new NumberOfBooleanFunctionsSequence().Sequence.Take(5); 15 | sequence.SequenceEqual(new BigInteger[] { 2, 4, 16, 256, 65536 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/NumberOfPrimesByNumberOfDigitsSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class NumberOfPrimesByNumberOfDigitsSequenceTests 10 | { 11 | [Test] 12 | public void First5ElementsCorrect() 13 | { 14 | var sequence = new NumberOfPrimesByNumberOfDigitsSequence().Sequence.Take(5); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 4, 21, 143, 1061 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/NumberOfPrimesByPowersOf10SequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class NumberOfPrimesByPowersOf10SequenceTests 10 | { 11 | [Test] 12 | public void First5ElementsCorrect() 13 | { 14 | var sequence = new NumberOfPrimesByPowersOf10Sequence().Sequence.Take(5); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 4, 25, 168, 1229 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/PowersOf10SequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class PowersOf10SequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new PowersOf10Sequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }) 17 | .Should().BeTrue(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/PowersOf2SequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class PowersOf2SequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new PowersOf2Sequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/PrimePiSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class PrimePiSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new PrimePiSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 1, 2, 2, 3, 3, 4, 4, 4, 4 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/PrimesSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class PrimesSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new PrimesSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/PrimorialNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class PrimorialNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new PrimorialNumbersSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 1, 2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870 }) 17 | .Should().BeTrue(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/RecamansSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class RecamansSequenceTests 10 | { 11 | [Test] 12 | public void First50ElementsCorrect() 13 | { 14 | // Taken from http://oeis.org/A005132 15 | var expected = new BigInteger[] 16 | { 17 | 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 18 | 11, 22, 10, 23, 9, 24, 8, 25, 43, 62, 19 | 42, 63, 41, 18, 42, 17, 43, 16, 44, 15, 20 | 45, 14, 46, 79, 113, 78, 114, 77, 39, 78, 21 | 38, 79, 37, 80, 36, 81, 35, 82, 34, 83, 22 | }; 23 | 24 | var sequence = new RecamansSequence().Sequence.Take(50); 25 | 26 | sequence.Should().Equal(expected); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/SquaresSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class SquaresSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new SquaresSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(new BigInteger[] { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 }) 16 | .Should().BeTrue(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/TetrahedralSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | [TestFixture] 10 | public class TetrahedralSequenceTests 11 | { 12 | private static readonly BigInteger[] TestList = { 13 | 0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 14 | 560, 680, 816, 969, 1140, 1330, 1540, 1771, 2024, 2300, 15 | 2600, 2925, 3276, 3654, 4060, 4495, 4960, 5456, 5984, 6545, 16 | 7140, 7770, 8436, 9139, 9880, 10660, 11480, 12341, 13244, 17 | 14190, 15180, 18 | }; 19 | 20 | /// 21 | /// This test uses the list values provided from http://oeis.org/A000292/list. 22 | /// 23 | [Test] 24 | public void TestOeisList() 25 | { 26 | var sequence = new TetrahedralSequence().Sequence.Take(TestList.Length); 27 | sequence.SequenceEqual(TestList).Should().BeTrue(); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/TetranacciNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class TetranacciNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First35ElementsCorrect() 13 | { 14 | var sequence = new TetranacciNumbersSequence().Sequence.Take(35); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 17 | 1, 1, 1, 1, 4, 7, 13, 25, 49, 94, 181, 349, 673, 1297, 2500, 4819, 9289, 17905, 34513, 66526, 128233, 18 | 247177, 476449, 918385, 1770244, 3412255, 6577333, 12678217, 24438049, 47105854, 90799453, 175021573, 19 | 337364929, 650291809, 1253477764, 20 | }) 21 | .Should().BeTrue(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/ThreeNPlusOneStepsSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class ThreeNPlusOneStepsSequenceTests { 10 | [Test] 11 | public void First50ElementsCorrect() { 12 | var sequence = new ThreeNPlusOneStepsSequence().Sequence.Take(50); 13 | var first50 = new BigInteger[] { 14 | 0, 1, 7, 2, 5, 8, 16, 3, 19, 6, 15 | 14, 9, 9, 17, 17, 4, 12, 20, 20, 7, 16 | 7, 15, 15, 10, 23, 10, 111, 18, 18, 18, 17 | 106, 5, 26, 13, 13, 21, 21, 21, 34, 8, 18 | 109, 8, 29, 16, 16, 16, 104, 11, 24, 24 19 | }; 20 | sequence.SequenceEqual(first50).Should().BeTrue(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/TribonacciNumbersSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class TribonacciNumbersSequenceTests 10 | { 11 | [Test] 12 | public void First37ElementsCorrect() 13 | { 14 | var sequence = new TribonacciNumbersSequence().Sequence.Take(37); 15 | sequence.SequenceEqual(new BigInteger[] 16 | { 17 | 1, 1, 1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201, 2209, 4063, 7473, 13745, 25281, 46499, 85525, 18 | 157305, 289329, 532159, 978793, 1800281, 3311233, 6090307, 11201821, 20603361, 37895489, 69700671, 19 | 128199521, 235795681, 433695873, 797691075, 1467182629, 20 | }) 21 | .Should().BeTrue(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/VanEcksSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class VanEcksSequenceTests 10 | { 11 | [Test] 12 | public void First50ElementsCorrect() 13 | { 14 | // Taken from http://oeis.org/A181391 15 | var expected = new BigInteger[] 16 | { 17 | 0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 18 | 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 19 | 0, 3, 2, 9, 0, 4, 9, 3, 6, 14, 20 | 0, 6, 3, 5, 15, 0, 5, 3, 5, 2, 21 | 17, 0, 6, 11, 0, 3, 8, 0, 3, 3, 22 | }; 23 | 24 | var sequence = new VanEcksSequence().Sequence.Take(50); 25 | 26 | sequence.Should().Equal(expected); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sequences/ZeroSequenceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Numerics; 3 | using Algorithms.Sequences; 4 | using FluentAssertions; 5 | using NUnit.Framework; 6 | 7 | namespace Algorithms.Tests.Sequences; 8 | 9 | public class ZeroSequenceTests 10 | { 11 | [Test] 12 | public void First10ElementsCorrect() 13 | { 14 | var sequence = new ZeroSequence().Sequence.Take(10); 15 | sequence.SequenceEqual(Enumerable.Repeat(BigInteger.Zero, 10)) 16 | .Should().BeTrue(); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/BinaryInsertionSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class BinaryInsertionSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new BinaryInsertionSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/BogoSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class BogoSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted([Random(0, 10, 10, Distinct = true)] int n) 12 | { 13 | // Arrange 14 | var sorter = new BogoSorter(); 15 | var intComparer = new IntComparer(); 16 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 17 | 18 | // Act 19 | sorter.Sort(testArray, intComparer); 20 | Array.Sort(correctArray, intComparer); 21 | 22 | // Assert 23 | Assert.That(correctArray, Is.EqualTo(testArray)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/BubbleSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class BubbleSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new BubbleSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/CocktailSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class CocktailSorterTests 9 | { 10 | [Test] 11 | public static void SortsArray( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new CocktailSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray); 23 | 24 | // Assert 25 | Assert.That(testArray, Is.EqualTo(correctArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/CycleSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class CycleSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new CycleSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray); 23 | 24 | // Assert 25 | Assert.That(testArray, Is.EqualTo(correctArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/ExchangeSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class ExchangeSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new ExchangeSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/HeapSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class HeapSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new HeapSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray); 23 | 24 | // Assert 25 | Assert.That(testArray, Is.EqualTo(correctArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/InsertionSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class InsertionSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new InsertionSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/MedianOfThreeQuickSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class MedianOfThreeQuickSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new MedianOfThreeQuickSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/MergeSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | /// 9 | /// Class for testing merge sorter algorithm. 10 | /// 11 | public static class MergeSorterTests 12 | { 13 | [Test] 14 | public static void TestOnMergeSorter( 15 | [Random(0, 1000, 100, Distinct = true)] 16 | int n) 17 | { 18 | // Arrange 19 | var sorter = new MergeSorter(); 20 | var intComparer = new IntComparer(); 21 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 22 | 23 | // Act 24 | sorter.Sort(testArray, intComparer); 25 | Array.Sort(correctArray); 26 | 27 | // Assert 28 | Assert.That(testArray, Is.EqualTo(correctArray)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/MiddlePointQuickSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class MiddlePointQuickSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new MiddlePointQuickSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/PancakeSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class PancakeSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new PancakeSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/RandomPivotQuickSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class RandomPivotQuickSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new RandomPivotQuickSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/SelectionSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class SelectionSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new SelectionSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Comparison/ShellSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Comparison; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Comparison; 7 | 8 | public static class ShellSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new ShellSorter(); 17 | var intComparer = new IntComparer(); 18 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 19 | 20 | // Act 21 | sorter.Sort(testArray, intComparer); 22 | Array.Sort(correctArray, intComparer); 23 | 24 | // Assert 25 | Assert.That(correctArray, Is.EqualTo(testArray)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Integer/BucketSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Integer; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Integer; 7 | 8 | public static class BucketSorterTests 9 | { 10 | [Test] 11 | public static void ArraySorted( 12 | [Random(0, 1000, 1000, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new BucketSorter(); 17 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 18 | 19 | // Act 20 | sorter.Sort(testArray); 21 | Array.Sort(correctArray); 22 | 23 | // Assert 24 | Assert.That(testArray, Is.EqualTo(correctArray)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Integer/CountingSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Integer; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Integer; 7 | 8 | public static class CountingSorterTests 9 | { 10 | [Test] 11 | public static void SortsNonEmptyArray( 12 | [Random(1, 10000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new CountingSorter(); 17 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 18 | 19 | // Act 20 | sorter.Sort(testArray); 21 | Array.Sort(correctArray); 22 | 23 | // Assert 24 | Assert.That(testArray, Is.EqualTo(correctArray)); 25 | } 26 | 27 | [Test] 28 | public static void SortsEmptyArray() 29 | { 30 | // Arrange 31 | var sorter = new CountingSorter(); 32 | var (correctArray, testArray) = RandomHelper.GetArrays(0); 33 | 34 | // Act 35 | sorter.Sort(testArray); 36 | Array.Sort(correctArray); 37 | 38 | // Assert 39 | Assert.That(testArray, Is.Empty); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/Integer/RadixSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.Integer; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.Integer; 7 | 8 | public static class RadixSorterTests 9 | { 10 | [Test] 11 | public static void SortsArray( 12 | [Random(0, 1000, 100, Distinct = true)] 13 | int n) 14 | { 15 | // Arrange 16 | var sorter = new RadixSorter(); 17 | var (correctArray, testArray) = RandomHelper.GetArrays(n); 18 | 19 | // Act 20 | sorter.Sort(testArray); 21 | Array.Sort(correctArray); 22 | 23 | // Assert 24 | Assert.That(testArray, Is.EqualTo(correctArray)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms.Tests/Sorters/String/MsdRadixStringSorterTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Sorters.String; 3 | using Algorithms.Tests.Helpers; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Sorters.String; 7 | 8 | /// 9 | /// Class for testing MSD radix sorter algorithm. 10 | /// 11 | public static class MsdRadixStringSorterTests 12 | { 13 | [Test] 14 | public static void ArraySorted( 15 | [Random(2, 1000, 100, Distinct = true)] 16 | int n) 17 | { 18 | // Arrange 19 | var sorter = new MsdRadixStringSorter(); 20 | var (correctArray, testArray) = RandomHelper.GetStringArrays(n, 100, false); 21 | 22 | // Act 23 | sorter.Sort(testArray); 24 | Array.Sort(correctArray); 25 | 26 | // Assert 27 | Assert.That(testArray, Is.EqualTo(correctArray)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/GeneralStringAlgorithmsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Strings; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Strings; 6 | 7 | public static class GeneralStringAlgorithmsTests 8 | { 9 | [TestCase("Griffith", 'f', 2)] 10 | [TestCase("Randomwoooord", 'o', 4)] 11 | [TestCase("Control", 'C', 1)] 12 | public static void MaxCountCharIsObtained(string text, char expectedSymbol, int expectedCount) 13 | { 14 | // Arrange 15 | // Act 16 | var (symbol, count) = GeneralStringAlgorithms.FindLongestConsecutiveCharacters(text); 17 | 18 | // Assert 19 | Assert.That(symbol, Is.EqualTo(expectedSymbol)); 20 | Assert.That(count, Is.EqualTo(expectedCount)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/PalindromeTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Strings; 5 | 6 | public static class PalindromeTests 7 | { 8 | [TestCase("Anna")] 9 | [TestCase("A Santa at Nasa")] 10 | public static void TextIsPalindrome_TrueExpected(string text) 11 | { 12 | // Arrange 13 | // Act 14 | var isPalindrome = Palindrome.IsStringPalindrome(text); 15 | 16 | // Assert 17 | Assert.That(isPalindrome, Is.True); 18 | } 19 | 20 | [TestCase("hallo")] 21 | [TestCase("Once upon a time")] 22 | public static void TextNotPalindrome_FalseExpected(string text) 23 | { 24 | // Arrange 25 | // Act 26 | var isPalindrome = Palindrome.IsStringPalindrome(text); 27 | 28 | // Assert 29 | Assert.That(isPalindrome, Is.False); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/PatternMatching/BoyerMoreTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using Algorithms.Strings.PatternMatching; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Strings; 6 | 7 | public class BoyerMooreTests 8 | { 9 | [TestCase("HelloImATestcaseAndIWillPass", "Testcase", 8)] 10 | [TestCase("HelloImATestcaseAndImCaseSensitive", "TestCase", -1)] 11 | [TestCase("Hello Im a testcase and I work with whitespaces", "testcase", 11)] 12 | [TestCase("Hello Im a testcase and I work with numbers like 1 2 3 4", "testcase", 11)] 13 | public void FindFirstOccurrence_IndexCheck(string t, string p, int expectedIndex) 14 | { 15 | var resultIndex = BoyerMoore.FindFirstOccurrence(t, p); 16 | Assert.That(expectedIndex, Is.EqualTo(resultIndex)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/PatternMatching/RabinKarpTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Algorithms.Strings; 3 | using Algorithms.Strings.PatternMatching; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Strings; 7 | 8 | public class RabinKarpTest 9 | { 10 | [TestCase("HelloImATestcaseAndIWillPass", "Testcase", new[] { 8 })] 11 | [TestCase("HelloImATestcaseAndImCaseSensitive", "TestCase", new int[] { })] 12 | [TestCase("Hello Im a testcase and you can use whitespaces", "testcase", new[] { 11 })] 13 | [TestCase("Hello Im a testcase and you can use numbers like 1, 2, 3, etcetera", "etcetera", new[] { 58 })] 14 | [TestCase("HelloImATestcaseAndIHaveTwoOccurrencesOfTestcase", "Testcase", new[] { 8, 40 })] 15 | public void FindAllOccurrences_IndexCheck(string t, string p, int[] expectedIndices) 16 | { 17 | List result = RabinKarp.FindAllOccurrences(t, p); 18 | Assert.That(result, Is.EqualTo(new List(expectedIndices))); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/PatternMatching/WildCardMatcherTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings.PatternMatching; 2 | using NUnit.Framework; 3 | 4 | namespace Algorithms.Tests.Strings.PatternMatching; 5 | 6 | public static class WildCardMatcherTests 7 | { 8 | [TestCase("aab", "c*a*b", true)] 9 | [TestCase("aaa", "aa", false)] 10 | [TestCase("aaa", "a.a", true)] 11 | [TestCase("aaab", "aa*", false)] 12 | [TestCase("aaab", ".*", true)] 13 | [TestCase("a", "bbbb", false)] 14 | [TestCase("", "bbbb", false)] 15 | [TestCase("a", "", false)] 16 | [TestCase("", "", true)] 17 | public static void MatchPattern(string inputString, string pattern, bool expected) 18 | { 19 | // Act 20 | var result = WildCardMatcher.MatchPattern(inputString, pattern); 21 | 22 | // Assert 23 | Assert.That(result, Is.EqualTo(expected)); 24 | } 25 | 26 | [Test] 27 | public static void MatchPatternThrowsArgumentException() 28 | { 29 | // Arrange 30 | var inputString = "abc"; 31 | var pattern = "*abc"; 32 | 33 | // Assert 34 | Assert.Throws(() => WildCardMatcher.MatchPattern(inputString, pattern)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/PatternMatching/ZblockSubstringSearchTest.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using Algorithms.Strings.PatternMatching; 3 | using NUnit.Framework; 4 | 5 | namespace Algorithms.Tests.Strings; 6 | 7 | public class ZblockSubstringSearchTest 8 | { 9 | [TestCase("abc", "abcdef", 1)] 10 | [TestCase("xxx", "abxxxcdexxxf", 2)] 11 | [TestCase("aa", "waapaaxcdaalaabb", 4)] 12 | [TestCase("ABC", "ABAAABCDBBABCDDEBCABC", 3)] 13 | [TestCase("xxx", "abcdefghij", 0)] 14 | [TestCase("aab", "caabxaaaz", 1)] 15 | [TestCase("abc", "xababaxbabcdabx", 1)] 16 | [TestCase("GEEK", "GEEKS FOR GEEKS", 2)] 17 | [TestCase("ground", "Hello, playground!", 1)] 18 | public void Test(string pattern, string text, int expectedOccurences) 19 | { 20 | var occurencesFound = ZblockSubstringSearch.FindSubstring(pattern, text); 21 | Assert.That(occurencesFound, Is.EqualTo(expectedOccurences)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/Similarity/HammingDistanceTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using NUnit.Framework; 3 | using System; 4 | using Algorithms.Strings.Similarity; 5 | 6 | namespace Algorithms.Tests.Strings; 7 | 8 | public class HammingDistanceTests 9 | { 10 | [TestCase("equal", "equal", 0)] 11 | [TestCase("dog", "dig", 1)] 12 | [TestCase("12345", "abcde", 5)] 13 | public void Calculate_ReturnsCorrectHammingDistance(string s1, string s2, int expectedDistance) 14 | { 15 | var result = HammingDistance.Calculate(s1, s2); 16 | Assert.That(result, Is.EqualTo(expectedDistance)); 17 | } 18 | 19 | [Test] 20 | public void Calculate_ThrowsArgumentExceptionWhenStringLengthsDiffer() 21 | { 22 | Assert.Throws(() => HammingDistance.Calculate("123", "12345")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/Similarity/JaccardDistanceTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Strings.Similarity; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Strings.Similarity; 7 | 8 | public class JaccardDistanceTests 9 | { 10 | private readonly JaccardDistance jaccard = new JaccardDistance(); 11 | private readonly double precision = 0.0001; 12 | 13 | [TestCase("left", null)] 14 | [TestCase(null, "right")] 15 | [TestCase(null, null)] 16 | public void Calculate_WhenStringsAreNull_ThrowsArgumentNullException(string left, string right) 17 | { 18 | Action action = () => jaccard.Calculate(left, right); 19 | action.Should().Throw(); 20 | } 21 | 22 | 23 | [TestCase("", "", 0.0d)] 24 | [TestCase("left", "", 1.0d)] 25 | [TestCase("", "right", 1.0d)] 26 | [TestCase("frog", "fog", 0.25d)] 27 | [TestCase("fly", "ant", 1.0d)] 28 | [TestCase("elephant", "hippo", 0.777777d)] 29 | [TestCase("ABC Corporation", "ABC Corp", 0.36363d)] 30 | public void Calculate_WhenProvidedWithStrings_CalculatesCorrectDistance(string left, string right, double expected) 31 | { 32 | var distance = jaccard.Calculate(left, right); 33 | 34 | distance.Should().BeApproximately(expected, precision); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/Similarity/JaccardSimilarityTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Strings.Similarity; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Strings.Similarity; 7 | 8 | public class JaccardSimilarityTests 9 | { 10 | private readonly JaccardSimilarity jaccard = new JaccardSimilarity(); 11 | private readonly double precision = 0.0001; 12 | 13 | [TestCase("left", null)] 14 | [TestCase(null, "right")] 15 | [TestCase(null, null)] 16 | public void Calculate_WhenStringsAreNull_ThrowsArgumentNullException(string left, string right) 17 | { 18 | Action action = () => jaccard.Calculate(left, right); 19 | action.Should().Throw(); 20 | } 21 | 22 | [TestCase("", "", 1.0d)] 23 | [TestCase("left", "", 0.0d)] 24 | [TestCase("", "right", 0.0d)] 25 | [TestCase("frog", "fog", 0.75d)] 26 | [TestCase("fly", "ant", 0.0d)] 27 | [TestCase("elephant", "hippo", 0.22222d)] 28 | [TestCase("ABC Corporation", "ABC Corp", 0.636363d)] 29 | public void Calculate_WhenProvidedWithStrings_CalculatesTheCorrectDistance(string left, string right, double expected) 30 | { 31 | var similarity = jaccard.Calculate(left, right); 32 | 33 | similarity.Should().BeApproximately(expected, precision); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/Similarity/JaroSimilarityTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using Algorithms.Strings.Similarity; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Strings; 7 | 8 | public class JaroSimilarityTests 9 | { 10 | [TestCase("equal", "equal", 1)] 11 | [TestCase("abc", "123", 0)] 12 | [TestCase("FAREMVIEL", "FARMVILLE", 0.88d)] 13 | [TestCase("CRATE", "TRACE", 0.73d)] 14 | [TestCase("CRATE11111", "CRTAE11111", 0.96d)] 15 | [TestCase("a", "a", 1)] 16 | [TestCase("", "", 1)] 17 | public void Calculate_ReturnsCorrectJaroSimilarity(string s1, string s2, double expected) 18 | { 19 | JaroSimilarity.Calculate(s1, s2).Should().BeApproximately(expected, 0.01); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Algorithms.Tests/Strings/Similarity/JaroWinklerDistanceTests.cs: -------------------------------------------------------------------------------- 1 | using Algorithms.Strings; 2 | using Algorithms.Strings.Similarity; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace Algorithms.Tests.Strings; 7 | 8 | public class JaroWinklerDistanceTests 9 | { 10 | [TestCase("equal", "equal", 0)] 11 | [TestCase("abc", "123", 1)] 12 | [TestCase("Winkler", "Welfare", 0.33)] 13 | [TestCase("faremviel", "farmville", 0.08)] 14 | [TestCase("", "", 0)] 15 | public void Calculate_ReturnsCorrectJaroWinklerDistance(string s1, string s2, double expected) 16 | { 17 | JaroWinklerDistance.Calculate(s1, s2).Should().BeApproximately(expected, 0.01); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Algorithms/Algorithms.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | ..\stylecop.ruleset 6 | true 7 | enable 8 | 9 | 10 | 11 | ./bin/Algorithms.xml 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | all 23 | runtime; build; native; contentfiles; analyzers; buildtransitive 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Algorithms/Crypto/Exceptions/CryptoException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Crypto.Exceptions; 4 | 5 | /// 6 | /// Represents errors that occur during cryptographic operations. 7 | /// 8 | public class CryptoException : Exception 9 | { 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | public CryptoException() 14 | { 15 | } 16 | 17 | /// 18 | /// Initializes a new instance of the class with a specified error message. 19 | /// 20 | /// The message that describes the error. 21 | public CryptoException(string message) 22 | : base(message) 23 | { 24 | } 25 | 26 | /// 27 | /// Initializes a new instance of the class with a specified error message 28 | /// and a reference to the inner exception that is the cause of this exception. 29 | /// 30 | /// The message that describes the error. 31 | /// The exception that is the cause of the current exception. 32 | public CryptoException(string message, Exception inner) 33 | : base(message, inner) 34 | { 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/DataCompression/Translator.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | 4 | namespace Algorithms.DataCompression; 5 | 6 | /// 7 | /// Provides method for text conversion by key mapping. 8 | /// 9 | public class Translator 10 | { 11 | /// 12 | /// Converts the input text according to the translation keys. 13 | /// 14 | /// Input text. 15 | /// Translation keys used for text matching. 16 | /// Converted text according to the translation keys. 17 | public string Translate(string text, Dictionary translationKeys) 18 | { 19 | var sb = new StringBuilder(); 20 | 21 | var start = 0; 22 | for (var i = 0; i < text.Length; i++) 23 | { 24 | var key = text.Substring(start, i - start + 1); 25 | if (translationKeys.ContainsKey(key)) 26 | { 27 | _ = sb.Append(translationKeys[key]); 28 | start = i + 1; 29 | } 30 | } 31 | 32 | return sb.ToString(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Encoders/IEncoder.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Encoders; 2 | 3 | /// 4 | /// Encodes and decodes text based on specified key. 5 | /// 6 | /// Type of the key. 7 | public interface IEncoder 8 | { 9 | /// 10 | /// Encodes text using specified key. 11 | /// 12 | /// Text to be encoded. 13 | /// Key that will be used to encode the text. 14 | /// Encoded text. 15 | string Encode(string text, TKey key); 16 | 17 | /// 18 | /// Decodes text that was encoded using specified key. 19 | /// 20 | /// Text to be decoded. 21 | /// Key that was used to encode the text. 22 | /// Decoded text. 23 | string Decode(string text, TKey key); 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/Financial/PresentValue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Algorithms.Financial; 6 | 7 | /// 8 | /// PresentValue is the value of an expected income stream determined as of the date of valuation. 9 | /// 10 | public static class PresentValue 11 | { 12 | public static double Calculate(double discountRate, List cashFlows) 13 | { 14 | if (discountRate < 0) 15 | { 16 | throw new ArgumentException("Discount rate cannot be negative"); 17 | } 18 | 19 | if (cashFlows.Count == 0) 20 | { 21 | throw new ArgumentException("Cash flows list cannot be empty"); 22 | } 23 | 24 | double presentValue = cashFlows.Select((t, i) => t / Math.Pow(1 + discountRate, i)).Sum(); 25 | 26 | return Math.Round(presentValue, 2); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/Graph/Dijkstra/DistanceModel.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.Graph; 2 | 3 | namespace Algorithms.Graph.Dijkstra; 4 | 5 | /// 6 | /// Entity which represents the Dijkstra shortest distance. 7 | /// Contains: Vertex, Previous Vertex and minimal distance from start vertex. 8 | /// 9 | /// Generic parameter. 10 | public class DistanceModel 11 | { 12 | public Vertex? Vertex { get; } 13 | 14 | public Vertex? PreviousVertex { get; set; } 15 | 16 | public double Distance { get; set; } 17 | 18 | public DistanceModel(Vertex? vertex, Vertex? previousVertex, double distance) 19 | { 20 | Vertex = vertex; 21 | PreviousVertex = previousVertex; 22 | Distance = distance; 23 | } 24 | 25 | public override string ToString() => 26 | $"Vertex: {Vertex} - Distance: {Distance} - Previous: {PreviousVertex}"; 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/Graph/IGraphSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using DataStructures.Graph; 3 | 4 | namespace Algorithms.Graph; 5 | 6 | public interface IGraphSearch 7 | { 8 | /// 9 | /// Traverses graph from start vertex. 10 | /// 11 | /// Graph instance. 12 | /// Vertex that search starts from. 13 | /// Action that needs to be executed on each graph vertex. 14 | void VisitAll(IDirectedWeightedGraph graph, Vertex startVertex, Action>? action = null); 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/Knapsack/BranchAndBoundNode.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Knapsack; 2 | 3 | public class BranchAndBoundNode 4 | { 5 | // isTaken --> true = the item where index = level is taken, vice versa 6 | public bool IsTaken { get; } 7 | 8 | // cumulativeWeight --> um of weight of item associated in each nodes starting from root to this node (only item that is taken) 9 | public int CumulativeWeight { get; set; } 10 | 11 | // cumulativeValue --> sum of value of item associated in each nodes starting from root to this node (only item that is taken) 12 | public double CumulativeValue { get; set; } 13 | 14 | // upperBound --> largest possible value after taking/not taking the item associated to this node (fractional) 15 | public double UpperBound { get; set; } 16 | 17 | // level --> level of the node in the tree structure 18 | public int Level { get; } 19 | 20 | // parent node 21 | public BranchAndBoundNode? Parent { get; } 22 | 23 | public BranchAndBoundNode(int level, bool taken, BranchAndBoundNode? parent = null) 24 | { 25 | Level = level; 26 | IsTaken = taken; 27 | Parent = parent; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/Knapsack/IHeuristicKnapsackSolver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Knapsack; 4 | 5 | /// 6 | /// Solves knapsack problem using some heuristics 7 | /// Sum of values of taken items -> max 8 | /// Sum of weights of taken items. <= capacity. 9 | /// 10 | /// Type of items in knapsack. 11 | public interface IHeuristicKnapsackSolver 12 | { 13 | /// 14 | /// Solves knapsack problem using some heuristics 15 | /// Sum of values of taken items -> max 16 | /// Sum of weights of taken items. <= capacity. 17 | /// 18 | /// All items to choose from. 19 | /// How much weight we can take. 20 | /// Maps item to its weight. 21 | /// Maps item to its value. 22 | /// Items that were chosen. 23 | T[] Solve(T[] items, double capacity, Func weightSelector, Func valueSelector); 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/Knapsack/IKnapsackSolver.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Knapsack; 2 | 3 | /// 4 | /// Solves knapsack problem: 5 | /// to maximize sum of values of taken items, 6 | /// while sum of weights of taken items is less than capacity. 7 | /// 8 | /// Type of items in knapsack. 9 | public interface IKnapsackSolver : IHeuristicKnapsackSolver 10 | { 11 | } 12 | -------------------------------------------------------------------------------- /Algorithms/Knapsack/NaiveKnapsackSolver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Algorithms.Knapsack; 5 | 6 | /// 7 | /// Greedy heurictic solver. 8 | /// 9 | /// Type of items in knapsack. 10 | public class NaiveKnapsackSolver : IHeuristicKnapsackSolver 11 | { 12 | /// 13 | /// TODO. 14 | /// 15 | /// TODO. 2. 16 | /// TODO. 3. 17 | /// TODO. 4. 18 | /// TODO. 5. 19 | /// TODO. 6. 20 | public T[] Solve(T[] items, double capacity, Func weightSelector, Func valueSelector) 21 | { 22 | var weight = 0d; 23 | var left = new List(); 24 | 25 | foreach (var item in items) 26 | { 27 | var weightDelta = weightSelector(item); 28 | if (weight + weightDelta <= capacity) 29 | { 30 | weight += weightDelta; 31 | left.Add(item); 32 | } 33 | } 34 | 35 | return left.ToArray(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/LinearAlgebra/Distances/Chebyshev.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Algorithms.LinearAlgebra.Distances; 5 | 6 | /// 7 | /// Implementation of Chebyshev distance. 8 | /// It is the maximum absolute difference between the measures in all dimensions of two points. 9 | /// In other words, it is the maximum distance one has to travel along any coordinate axis to get from one point to another. 10 | /// 11 | /// It is commonly used in various fields such as chess, warehouse logistics, and more. 12 | /// 13 | public static class Chebyshev 14 | { 15 | /// 16 | /// Calculate Chebyshev distance for two N-Dimensional points. 17 | /// 18 | /// First N-Dimensional point. 19 | /// Second N-Dimensional point. 20 | /// Calculated Chebyshev distance. 21 | public static double Distance(double[] point1, double[] point2) 22 | { 23 | if (point1.Length != point2.Length) 24 | { 25 | throw new ArgumentException("Both points should have the same dimensionality"); 26 | } 27 | 28 | // distance = max(|x1-y1|, |x2-y2|, ..., |xn-yn|) 29 | return point1.Zip(point2, (x1, x2) => Math.Abs(x1 - x2)).Max(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/LinearAlgebra/Distances/Euclidean.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Algorithms.LinearAlgebra.Distances; 5 | 6 | /// 7 | /// Implementation for Euclidean distance. 8 | /// 9 | public static class Euclidean 10 | { 11 | /// 12 | /// Calculate Euclidean distance for two N-Dimensional points. 13 | /// 14 | /// First N-Dimensional point. 15 | /// Second N-Dimensional point. 16 | /// Calculated Euclidean distance. 17 | public static double Distance(double[] point1, double[] point2) 18 | { 19 | if (point1.Length != point2.Length) 20 | { 21 | throw new ArgumentException("Both points should have the same dimensionality"); 22 | } 23 | 24 | // distance = sqrt((x1-y1)^2 + (x2-y2)^2 + ... + (xn-yn)^2) 25 | return Math.Sqrt(point1.Zip(point2, (x1, x2) => (x1 - x2) * (x1 - x2)).Sum()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/LinearAlgebra/Distances/Manhattan.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Algorithms.LinearAlgebra.Distances; 5 | 6 | /// 7 | /// Implementation fo Manhattan distance. 8 | /// It is the sum of the lengths of the projections of the line segment between the points onto the coordinate axes. 9 | /// In other words, it is the sum of absolute difference between the measures in all dimensions of two points. 10 | /// 11 | /// Its commonly used in regression analysis. 12 | /// 13 | public static class Manhattan 14 | { 15 | /// 16 | /// Calculate Manhattan distance for two N-Dimensional points. 17 | /// 18 | /// First N-Dimensional point. 19 | /// Second N-Dimensional point. 20 | /// Calculated Manhattan distance. 21 | public static double Distance(double[] point1, double[] point2) 22 | { 23 | if (point1.Length != point2.Length) 24 | { 25 | throw new ArgumentException("Both points should have the same dimensionality"); 26 | } 27 | 28 | // distance = |x1-y1| + |x2-y2| + ... + |xn-yn| 29 | return point1.Zip(point2, (x1, x2) => Math.Abs(x1 - x2)).Sum(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/NewtonSquareRoot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace Algorithms; 5 | 6 | public static class NewtonSquareRoot 7 | { 8 | public static BigInteger Calculate(BigInteger number) 9 | { 10 | if (number < 0) 11 | { 12 | throw new ArgumentException("Cannot calculate the square root of a negative number."); 13 | } 14 | 15 | if (number == 0) 16 | { 17 | return BigInteger.Zero; 18 | } 19 | 20 | var bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(number, 2))); 21 | BigInteger root = BigInteger.One << (bitLength / 2); 22 | 23 | while (!IsSquareRoot(number, root)) 24 | { 25 | root += number / root; 26 | root /= 2; 27 | } 28 | 29 | return root; 30 | } 31 | 32 | private static bool IsSquareRoot(BigInteger number, BigInteger root) 33 | { 34 | var lowerBound = root * root; 35 | return number >= lowerBound && number <= lowerBound + root + root; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Numeric/AdditionWithoutArithmetic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Numeric; 5 | 6 | /// 7 | /// Add the integers without arithmetic operation. 8 | /// 9 | public static class AdditionWithoutArithmetic 10 | { 11 | /// 12 | /// Returns the sum of two integers. 13 | /// 14 | /// First number to add. 15 | /// Second number to add. 16 | /// Sum of the two numbers. 17 | public static int CalculateAdditionWithoutArithmetic(int first, int second) 18 | { 19 | while (second != 0) 20 | { 21 | int c = first & second; // Carry 22 | first ^= second; // Sum without carry 23 | second = c << 1; // Carry shifted left 24 | } 25 | 26 | return first; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Algorithms/Numeric/AmicableNumbersChecker.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Numeric; 2 | 3 | /// 4 | /// Amicable numbers are two different natural numbers related in such a way that the sum of the proper divisors of 5 | /// each is equal to the other number. That is, σ(a)=b+a and σ(b)=a+b, where σ(n) is equal to the sum of positive divisors of n (see also divisor function). 6 | /// See here for more info. 7 | /// 8 | public static class AmicableNumbersChecker 9 | { 10 | /// 11 | /// Checks if two numbers are amicable or not. 12 | /// 13 | /// First number to check. 14 | /// Second number to check. 15 | /// True if they are amicable numbers. False if not. 16 | public static bool AreAmicableNumbers(int x, int y) 17 | { 18 | return SumOfDivisors(x) == y && SumOfDivisors(y) == x; 19 | } 20 | 21 | private static int SumOfDivisors(int number) 22 | { 23 | var sum = 0; /* sum of its positive divisors */ 24 | for (var i = 1; i < number; ++i) 25 | { 26 | if (number % i == 0) 27 | { 28 | sum += i; 29 | } 30 | } 31 | 32 | return sum; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Numeric/Ceil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Numeric; 5 | 6 | /// 7 | /// Perform ceiling operation on a number. 8 | /// 9 | public static class Ceil 10 | { 11 | /// 12 | /// Returns the smallest integer greater than or equal to the number. 13 | /// 14 | /// Type of number. 15 | /// Number to find the ceiling of. 16 | /// Ceiling value of the number. 17 | public static T CeilVal(T inputNum) where T : INumber 18 | { 19 | T intPart = T.CreateChecked(Convert.ToInt32(inputNum)); 20 | 21 | return inputNum > intPart ? intPart + T.One : intPart; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/Numeric/Factorial.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Numeric; 5 | 6 | /// 7 | /// The factorial of a positive integer n, denoted by n!, 8 | /// is the product of all positive integers less than or equal to n. 9 | /// 10 | public static class Factorial 11 | { 12 | /// 13 | /// Calculates factorial of a integer number. 14 | /// 15 | /// Integer Input number. 16 | /// Factorial of integer input number. 17 | public static BigInteger Calculate(int inputNum) 18 | { 19 | // Convert integer input to BigInteger 20 | BigInteger num = new BigInteger(inputNum); 21 | 22 | // Don't calculate factorial if input is a negative number. 23 | if (BigInteger.Compare(num, BigInteger.Zero) < 0) 24 | { 25 | throw new ArgumentException("Only for num >= 0"); 26 | } 27 | 28 | // Factorial of numbers greater than 0. 29 | BigInteger result = BigInteger.One; 30 | 31 | for (BigInteger i = BigInteger.One; BigInteger.Compare(i, num) <= 0; i = BigInteger.Add(i, BigInteger.One)) 32 | { 33 | result = BigInteger.Multiply(result, i); 34 | } 35 | 36 | return result; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Numeric/Factorization/IFactorizer.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Numeric.Factorization; 2 | 3 | /// 4 | /// Finds a factor of a given number or returns false if it's prime. 5 | /// 6 | public interface IFactorizer 7 | { 8 | /// 9 | /// Finds a factor of a given number or returns false if it's prime. 10 | /// 11 | /// Integer to factor. 12 | /// Found factor. 13 | /// if factor is found, if is prime. 14 | bool TryFactor(int n, out int factor); 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/Numeric/Factorization/TrialDivisionFactorizer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Algorithms.Numeric.Factorization; 5 | 6 | /// 7 | /// Factors number using trial division algorithm. 8 | /// 9 | public class TrialDivisionFactorizer : IFactorizer 10 | { 11 | /// 12 | /// Finds the smallest non trivial factor (i.e.: 1 < factor <= sqrt()) of a given number or returns false if it's prime. 13 | /// 14 | /// Integer to factor. 15 | /// Found factor. 16 | /// if factor is found, if is prime. 17 | public bool TryFactor(int n, out int factor) 18 | { 19 | n = Math.Abs(n); 20 | factor = Enumerable.Range(2, (int)Math.Sqrt(n) - 1).FirstOrDefault(i => n % i == 0); 21 | return factor != 0; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/Numeric/Floor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Numeric; 5 | 6 | /// 7 | /// Perform floor operation on a number. 8 | /// 9 | public static class Floor 10 | { 11 | /// 12 | /// Returns the largest integer less than or equal to the number. 13 | /// 14 | /// Type of number. 15 | /// Number to find the floor of. 16 | /// Floor value of the number. 17 | public static T FloorVal(T inputNum) where T : INumber 18 | { 19 | T intPart = T.CreateChecked(Convert.ToInt32(inputNum)); 20 | 21 | return inputNum < intPart ? intPart - T.One : intPart; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Algorithms/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinder.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Numeric.GreatestCommonDivisor; 2 | 3 | /// 4 | /// TODO. 5 | /// 6 | public class EuclideanGreatestCommonDivisorFinder : IGreatestCommonDivisorFinder 7 | { 8 | /// 9 | /// Finds greatest common divisor for numbers a and b 10 | /// using euclidean algorithm. 11 | /// 12 | /// TODO. 13 | /// TODO. 2. 14 | /// Greatest common divisor. 15 | public int FindGcd(int a, int b) 16 | { 17 | if (a == 0 && b == 0) 18 | { 19 | return int.MaxValue; 20 | } 21 | 22 | if (a == 0 || b == 0) 23 | { 24 | return a + b; 25 | } 26 | 27 | var aa = a; 28 | var bb = b; 29 | var cc = aa % bb; 30 | 31 | while (cc != 0) 32 | { 33 | aa = bb; 34 | bb = cc; 35 | cc = aa % bb; 36 | } 37 | 38 | return bb; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Numeric/GreatestCommonDivisor/IGreatestCommonDivisorFinder.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Numeric.GreatestCommonDivisor; 2 | 3 | public interface IGreatestCommonDivisorFinder 4 | { 5 | int FindGcd(int a, int b); 6 | } 7 | -------------------------------------------------------------------------------- /Algorithms/Numeric/JosephusProblem.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | public static class JosephusProblem 6 | { 7 | /// 8 | /// Calculates the winner in the Josephus problem. 9 | /// 10 | /// The number of people in the initial circle. 11 | /// The count of each step. k-1 people are skipped and the k-th is executed. 12 | /// The 1-indexed position where the player must choose in order to win the game. 13 | public static long FindWinner(long n, long k) 14 | { 15 | if (k <= 0) 16 | { 17 | throw new ArgumentException("The step cannot be smaller than 1"); 18 | } 19 | 20 | if (k > n) 21 | { 22 | throw new ArgumentException("The step cannot be greater than the size of the group"); 23 | } 24 | 25 | long winner = 0; 26 | for (long stepIndex = 1; stepIndex <= n; ++stepIndex) 27 | { 28 | winner = (winner + k) % stepIndex; 29 | } 30 | 31 | return winner + 1; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Numeric/KrishnamurthyNumberChecker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | /// 6 | /// A Krishnamurthy number is a number whose sum of the factorial of digits 7 | /// is equal to the number itself. 8 | /// 9 | /// For example, 145 is a Krishnamurthy number since: 1! + 4! + 5! = 1 + 24 + 120 = 145. 10 | /// 11 | public static class KrishnamurthyNumberChecker 12 | { 13 | /// 14 | /// Check if a number is Krishnamurthy number or not. 15 | /// 16 | /// The number to check. 17 | /// True if the number is Krishnamurthy, false otherwise. 18 | public static bool IsKMurthyNumber(int n) 19 | { 20 | int sumOfFactorials = 0; 21 | int tmp = n; 22 | 23 | if (n <= 0) 24 | { 25 | return false; 26 | } 27 | 28 | while (n != 0) 29 | { 30 | int factorial = (int)Factorial.Calculate(n % 10); 31 | sumOfFactorials += factorial; 32 | n = n / 10; 33 | } 34 | 35 | return tmp == sumOfFactorials; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Numeric/ModularExponentiation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | /// 6 | /// Modular exponentiation is a type of exponentiation performed over a modulus 7 | /// Modular exponentiation c is: c = b^e mod m where b is base, e is exponent, m is modulus 8 | /// (Wiki: https://en.wikipedia.org/wiki/Modular_exponentiation). 9 | /// 10 | public class ModularExponentiation 11 | { 12 | /// 13 | /// Performs Modular Exponentiation on b, e, m. 14 | /// 15 | /// Base. 16 | /// Exponent. 17 | /// Modulus. 18 | /// Modular Exponential. 19 | public int ModularPow(int b, int e, int m) 20 | { 21 | // initialize result in variable res 22 | int res = 1; 23 | if (m == 1) 24 | { 25 | // 1 divides every number 26 | return 0; 27 | } 28 | 29 | if (m <= 0) 30 | { 31 | // exponential not defined in this case 32 | throw new ArgumentException(string.Format("{0} is not a positive integer", m)); 33 | } 34 | 35 | for (int i = 0; i < e; i++) 36 | { 37 | res = (res * b) % m; 38 | } 39 | 40 | return res; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Numeric/NarcissisticNumberChecker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | /// 6 | /// A Narcissistic number is equal to the sum of the cubes of its digits. For example, 370 is a 7 | /// Narcissistic number because 3*3*3 + 7*7*7 + 0*0*0 = 370. 8 | /// 9 | public static class NarcissisticNumberChecker 10 | { 11 | /// 12 | /// Checks if a number is a Narcissistic number or not. 13 | /// 14 | /// Number to check. 15 | /// True if is a Narcissistic number; False otherwise. 16 | public static bool IsNarcissistic(int number) 17 | { 18 | var sum = 0; 19 | var temp = number; 20 | var numberOfDigits = 0; 21 | while (temp != 0) 22 | { 23 | numberOfDigits++; 24 | temp /= 10; 25 | } 26 | 27 | temp = number; 28 | while (number > 0) 29 | { 30 | var remainder = number % 10; 31 | var power = (int)Math.Pow(remainder, numberOfDigits); 32 | 33 | sum += power; 34 | number /= 10; 35 | } 36 | 37 | return sum == temp; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Numeric/PerfectNumberChecker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | /// 6 | /// In number theory, a perfect number is a positive integer that is equal to the sum of its positive 7 | /// divisors, excluding the number itself.For instance, 6 has divisors 1, 2 and 3 (excluding 8 | /// itself), and 1 + 2 + 3 = 6, so 6 is a perfect number. 9 | /// 10 | public static class PerfectNumberChecker 11 | { 12 | /// 13 | /// Checks if a number is a perfect number or not. 14 | /// 15 | /// Number to check. 16 | /// True if is a perfect number; False otherwise. 17 | /// Error number is not on interval (0.0; int.MaxValue). 18 | public static bool IsPerfectNumber(int number) 19 | { 20 | if (number < 0) 21 | { 22 | throw new ArgumentException($"{nameof(number)} cannot be negative"); 23 | } 24 | 25 | var sum = 0; /* sum of its positive divisors */ 26 | for (var i = 1; i < number; ++i) 27 | { 28 | if (number % i == 0) 29 | { 30 | sum += i; 31 | } 32 | } 33 | 34 | return sum == number; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Numeric/PerfectSquareChecker.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Numeric; 4 | 5 | /// 6 | /// A perfect square is an element of algebraic structure that is equal to the square of another element. 7 | /// 8 | public static class PerfectSquareChecker 9 | { 10 | /// 11 | /// Checks if a number is a perfect square or not. 12 | /// 13 | /// Number too check. 14 | /// True if is a perfect square; False otherwise. 15 | public static bool IsPerfectSquare(int number) 16 | { 17 | if (number < 0) 18 | { 19 | return false; 20 | } 21 | 22 | var sqrt = (int)Math.Sqrt(number); 23 | return sqrt * sqrt == number; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Algorithms/Other/JulianEaster.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | 4 | namespace Algorithms.Other; 5 | 6 | /// 7 | /// Date of Easter calculated with Meeus's Julian algorithm. 8 | /// The algorithm is described in Jean Meeus' Astronomical Algorithms (1991, p. 69). 9 | /// 10 | public static class JulianEaster 11 | { 12 | /// 13 | /// Calculates the date of Easter. 14 | /// 15 | /// Year to calculate the date of Easter. 16 | /// Date of Easter as a DateTime. 17 | public static DateTime Calculate(int year) 18 | { 19 | var a = year % 4; 20 | var b = year % 7; 21 | var c = year % 19; 22 | var d = (19 * c + 15) % 30; 23 | var e = (2 * a + 4 * b - d + 34) % 7; 24 | var month = (int)Math.Floor((d + e + 114) / 31M); 25 | var day = ((d + e + 114) % 31) + 1; 26 | 27 | DateTime easter = new(year, month, day, 00, 00, 00, DateTimeKind.Utc); 28 | 29 | return easter; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Other/PollardsRhoFactorizing.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Algorithms.Numeric.GreatestCommonDivisor; 3 | 4 | namespace Algorithms.Other; 5 | 6 | /// Implementation of the Pollard's rho algorithm. 7 | /// Algorithm for integer factorization. 8 | /// Wiki: https://en.wikipedia.org/wiki/Pollard's_rho_algorithm. 9 | /// 10 | public static class PollardsRhoFactorizing 11 | { 12 | public static int Calculate(int number) 13 | { 14 | var x = 2; 15 | var y = 2; 16 | var d = 1; 17 | var p = number; 18 | var i = 0; 19 | var gcd = new BinaryGreatestCommonDivisorFinder(); 20 | 21 | while (d == 1) 22 | { 23 | x = Fun_g(x, p); 24 | y = Fun_g(Fun_g(y, p), p); 25 | d = gcd.FindGcd(Math.Abs(x - y), p); 26 | i++; 27 | } 28 | 29 | return d; 30 | } 31 | 32 | private static int Fun_g(int x, int p) 33 | { 34 | return (x * x + 1) % p; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Problems/StableMarriage/Accepter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Problems.StableMarriage; 4 | 5 | public class Accepter 6 | { 7 | public Proposer? EngagedTo { get; set; } 8 | 9 | public List PreferenceOrder { get; set; } = new(); 10 | 11 | public bool PrefersOverCurrent(Proposer newProposer) => 12 | EngagedTo is null || 13 | PreferenceOrder.IndexOf(newProposer) < PreferenceOrder.IndexOf(EngagedTo); 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Problems/StableMarriage/Proposer.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Problems.StableMarriage; 4 | 5 | public class Proposer 6 | { 7 | public Accepter? EngagedTo { get; set; } 8 | 9 | public LinkedList PreferenceOrder { get; set; } = new(); 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/RecommenderSystem/ISimilarityCalculator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Algorithms.RecommenderSystem 8 | { 9 | public interface ISimilarityCalculator 10 | { 11 | double CalculateSimilarity(Dictionary user1Ratings, Dictionary user2Ratings); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Search/AStar/NodeState.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Search.AStar; 2 | 3 | /// 4 | /// The states the nodes can have. 5 | /// 6 | public enum NodeState 7 | { 8 | /// 9 | /// TODO. 10 | /// 11 | Unconsidered = 0, 12 | 13 | /// 14 | /// TODO. 15 | /// 16 | Open = 1, 17 | 18 | /// 19 | /// TODO. 20 | /// 21 | Closed = 2, 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/Search/AStar/PathfindingException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Search.AStar; 4 | 5 | /// 6 | /// A pathfinding exception is thrown when the Pathfinder encounters a critical error and can not continue. 7 | /// 8 | public class PathfindingException : Exception 9 | { 10 | public PathfindingException(string message) 11 | : base(message) 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Sequences/AllOnesSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// The all ones sequence. 9 | /// 10 | /// 11 | /// OEIS: https://oeis.org/A000012. 12 | /// 13 | /// 14 | public class AllOnesSequence : ISequence 15 | { 16 | /// 17 | /// Gets all ones sequence. 18 | /// 19 | public IEnumerable Sequence 20 | { 21 | get 22 | { 23 | while (true) 24 | { 25 | yield return 1; 26 | } 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Algorithms/Sequences/AllThreesSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// The all threes sequence. 9 | /// 10 | /// 11 | /// OEIS: https://oeis.org/A010701. 12 | /// 13 | /// 14 | public class AllThreesSequence : ISequence 15 | { 16 | public IEnumerable Sequence 17 | { 18 | get 19 | { 20 | while (true) 21 | { 22 | yield return 3; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Sequences/AllTwosSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// The all twos sequence. 9 | /// 10 | /// 11 | /// OEIS: https://oeis.org/A007395. 12 | /// 13 | /// 14 | public class AllTwosSequence : ISequence 15 | { 16 | public IEnumerable Sequence 17 | { 18 | get 19 | { 20 | while (true) 21 | { 22 | yield return 2; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Sequences/BinaryPrimeConstantSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of binary prime constant 9 | /// (Characteristic function of primes: 1 if n is prime, else 0). 10 | /// 11 | /// 12 | /// Wikipedia: https://wikipedia.org/wiki/Prime_constant. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A010051. 16 | /// 17 | /// 18 | public class BinaryPrimeConstantSequence : ISequence 19 | { 20 | /// 21 | /// Gets sequence of binary prime constant. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | ISequence primes = new PrimesSequence(); 28 | var n = new BigInteger(0); 29 | 30 | foreach (var p in primes.Sequence) 31 | { 32 | for (n++; n < p; n++) 33 | { 34 | yield return 0; 35 | } 36 | 37 | yield return 1; 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Sequences/CakeNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Cake numbers: maximal number of pieces resulting from n planar cuts through a cube 9 | /// (or cake): C(n+1,3) + n + 1. 10 | /// 11 | /// 12 | /// OEIS: https://oeis.org/A000125. 13 | /// 14 | /// 15 | public class CakeNumbersSequence : ISequence 16 | { 17 | public IEnumerable Sequence 18 | { 19 | get 20 | { 21 | var n = new BigInteger(0); 22 | while (true) 23 | { 24 | var next = (BigInteger.Pow(n, 3) + 5 * n + 6) / 6; 25 | n++; 26 | yield return next; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Sequences/CatalanSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Catalan numbers: C[n+1] = (2*(2*n+1)*C[n])/(n+2). 9 | /// 10 | /// 11 | /// Wikipedia: https://en.wikipedia.org/wiki/Catalan_number. 12 | /// 13 | /// 14 | /// OEIS:http://oeis.org/A000108. 15 | /// 16 | /// 17 | public class CatalanSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of Catalan numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | // initialize the first element (1) and define it's enumerator (0) 27 | var catalan = new BigInteger(1); 28 | var n = 0; 29 | while (true) 30 | { 31 | yield return catalan; 32 | catalan = (2 * (2 * n + 1) * catalan) / (n + 2); 33 | n++; 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Sequences/CentralPolygonalNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Central polygonal numbers (the Lazy Caterer's sequence): n(n+1)/2 + 1; or, maximal number of pieces 9 | /// formed when slicing a pancake with n cuts. 10 | /// 11 | /// 12 | /// OEIS: https://oeis.org/A000124. 13 | /// 14 | /// 15 | public class CentralPolygonalNumbersSequence : ISequence 16 | { 17 | public IEnumerable Sequence 18 | { 19 | get 20 | { 21 | var n = new BigInteger(0); 22 | while (true) 23 | { 24 | var next = n * (n + 1) / 2 + 1; 25 | n++; 26 | yield return next; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Algorithms/Sequences/CubesSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of cube numbers. 9 | /// 10 | /// 11 | /// Wikipedia: https://en.wikipedia.org/wiki/Cube_(algebra). 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000578. 15 | /// 16 | /// 17 | public class CubesSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of cube numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = BigInteger.Zero; 27 | 28 | while (true) 29 | { 30 | yield return n * n * n; 31 | n++; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/DivisorsCountSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of the number of divisors of n, starting with 1. 9 | /// 10 | /// 11 | /// OEIS: https://oeis.org/A000005. 12 | /// 13 | /// 14 | public class DivisorsCountSequence : ISequence 15 | { 16 | /// 17 | /// Gets sequence of number of divisors for n, starting at 1. 18 | /// 19 | public IEnumerable Sequence 20 | { 21 | get 22 | { 23 | yield return BigInteger.One; 24 | for (var n = new BigInteger(2); ; n++) 25 | { 26 | var count = 2; 27 | for (var k = 2; k < n; k++) 28 | { 29 | BigInteger.DivRem(n, k, out var remainder); 30 | if (remainder == 0) 31 | { 32 | count++; 33 | } 34 | } 35 | 36 | yield return count; 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Sequences/EuclidNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of Euclid numbers: 1 + product of the first n primes. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Euclid_number. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A006862. 15 | /// 16 | /// 17 | public class EuclidNumbersSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of Euclid numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var primorialNumbers = new PrimorialNumbersSequence().Sequence; 27 | 28 | foreach (var n in primorialNumbers) 29 | { 30 | yield return n + 1; 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Sequences/FactorialSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of factorial numbers. 9 | /// 10 | /// 11 | /// Wikipedia: https://en.wikipedia.org/wiki/Factorial. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000142. 15 | /// 16 | /// 17 | public class FactorialSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of factorial numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = 0; 27 | var factorial = new BigInteger(1); 28 | while (true) 29 | { 30 | yield return factorial; 31 | n++; 32 | factorial *= n; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Sequences/FermatNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of Fermat numbers: a(n) = 2^(2^n) + 1. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Fermat_number. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000215. 15 | /// 16 | /// 17 | public class FermatNumbersSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of Fermat numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(2); 27 | 28 | while (true) 29 | { 30 | yield return n + 1; 31 | n *= n; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/FermatPrimesSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Sequence of Fermat primes: primes of the form 2^(2^k) + 1, for some k >= 0. 10 | /// 11 | /// 12 | /// Wikipedia: https://wikipedia.org/wiki/Fermat_number. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A019434. 16 | /// 17 | /// 18 | public class FermatPrimesSequence : ISequence 19 | { 20 | /// 21 | /// Gets sequence of Fermat primes. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | var fermatNumbers = new FermatNumbersSequence().Sequence.Take(5); 28 | 29 | foreach (var n in fermatNumbers) 30 | { 31 | yield return n; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/FibonacciSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Fibonacci sequence. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Fibonacci_number. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000045. 15 | /// 16 | /// 17 | public class FibonacciSequence : ISequence 18 | { 19 | /// 20 | /// Gets Fibonacci sequence. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | yield return 0; 27 | yield return 1; 28 | BigInteger previous = 0; 29 | BigInteger current = 1; 30 | while (true) 31 | { 32 | var next = previous + current; 33 | previous = current; 34 | current = next; 35 | yield return next; 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Algorithms/Sequences/GolombsSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Golomb's sequence. a(n) is the number of times n occurs in the sequence, starting with a(1) = 1. 9 | /// 10 | /// 11 | /// Wikipedia: https://en.wikipedia.org/wiki/Golomb_sequence. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A001462. 15 | /// 16 | /// 17 | public class GolombsSequence : ISequence 18 | { 19 | /// 20 | /// Gets Golomb's sequence. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | yield return 1; 27 | yield return 2; 28 | yield return 2; 29 | 30 | var queue = new Queue(); 31 | queue.Enqueue(2); 32 | 33 | for (var i = 3; ; i++) 34 | { 35 | var repetitions = queue.Dequeue(); 36 | for (var j = 0; j < repetitions; j++) 37 | { 38 | queue.Enqueue(i); 39 | yield return i; 40 | } 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Sequences/ISequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// Common interface for all integer sequences. 8 | /// 9 | public interface ISequence 10 | { 11 | /// 12 | /// Gets sequence as enumerable. 13 | /// 14 | IEnumerable Sequence { get; } 15 | } 16 | -------------------------------------------------------------------------------- /Algorithms/Sequences/KolakoskiSequence2.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Kolakoski sequence; n-th element is the length of the n-th run in the sequence itself. 10 | /// 11 | /// 12 | /// Wikipedia: https://en.wikipedia.org/wiki/Kolakoski_sequence. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A000002. 16 | /// 17 | /// 18 | public class KolakoskiSequence2 : ISequence 19 | { 20 | /// 21 | /// Gets Kolakoski sequence. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | yield return 1; 28 | yield return 2; 29 | yield return 2; 30 | 31 | var inner = new KolakoskiSequence2().Sequence.Skip(2); 32 | var nextElement = 1; 33 | foreach (var runLength in inner) 34 | { 35 | yield return nextElement; 36 | if (runLength > 1) 37 | { 38 | yield return nextElement; 39 | } 40 | 41 | nextElement = 1 + nextElement % 2; 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Algorithms/Sequences/KummerNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Sequence of Kummer numbers (also called Euclid numbers of the second kind): 10 | /// -1 + product of first n consecutive primes. 11 | /// 12 | /// 13 | /// Wikipedia: https://wikipedia.org/wiki/Euclid_number. 14 | /// 15 | /// 16 | /// OEIS: https://oeis.org/A057588. 17 | /// 18 | /// 19 | public class KummerNumbersSequence : ISequence 20 | { 21 | /// 22 | /// Gets sequence of Kummer numbers. 23 | /// 24 | public IEnumerable Sequence 25 | { 26 | get 27 | { 28 | var primorialNumbers = new PrimorialNumbersSequence().Sequence.Skip(1); 29 | 30 | foreach (var n in primorialNumbers) 31 | { 32 | yield return n - 1; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Sequences/NaturalSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of natural numbers. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Natural_number. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000027. 15 | /// 16 | /// 17 | public class NaturalSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of natural numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(1); 27 | while (true) 28 | { 29 | yield return n++; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Sequences/NegativeIntegersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of negative integers. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Negative_number. 12 | /// 13 | /// 14 | /// OEIS: http://oeis.org/A001478. 15 | /// 16 | /// 17 | public class NegativeIntegersSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of negative integers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(-1); 27 | 28 | while (true) 29 | { 30 | yield return n--; 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Algorithms/Sequences/NumberOfBooleanFunctionsSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of number of truth tables generated by Boolean expressions of n variables 9 | /// (Double exponentials of 2: a(n) = 2^(2^n)). 10 | /// 11 | /// 12 | /// Wikipedia: https://wikipedia.org/wiki/Truth_table. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A001146. 16 | /// 17 | /// 18 | public class NumberOfBooleanFunctionsSequence : ISequence 19 | { 20 | /// 21 | /// Gets sequence of number Of Boolean functions. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | var n = new BigInteger(2); 28 | 29 | while (true) 30 | { 31 | yield return n; 32 | n *= n; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Sequences/NumberOfPrimesByNumberOfDigitsSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Number of primes with n digits 9 | /// (The number of primes between 10^(n-1) and 10^n). 10 | /// 11 | /// 12 | /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A006879. 16 | /// 17 | /// 18 | public class NumberOfPrimesByNumberOfDigitsSequence : ISequence 19 | { 20 | /// 21 | /// Gets sequence of number of primes. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | ISequence primes = new PrimesSequence(); 28 | var powerOf10 = new BigInteger(1); 29 | var counter = new BigInteger(0); 30 | 31 | foreach (var p in primes.Sequence) 32 | { 33 | if (p > powerOf10) 34 | { 35 | yield return counter; 36 | counter = 0; 37 | powerOf10 *= 10; 38 | } 39 | 40 | counter++; 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Sequences/NumberOfPrimesByPowersOf10Sequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of number of primes less than 10^n (with at most n digits). 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A006880. 15 | /// 16 | /// 17 | public class NumberOfPrimesByPowersOf10Sequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of numbers of primes. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | ISequence primes = new PrimesSequence(); 27 | var powerOf10 = new BigInteger(1); 28 | var counter = new BigInteger(0); 29 | 30 | foreach (var p in primes.Sequence) 31 | { 32 | if (p > powerOf10) 33 | { 34 | yield return counter; 35 | powerOf10 *= 10; 36 | } 37 | 38 | counter++; 39 | } 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Sequences/PowersOf10Sequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of powers of 10: a(n) = 10^n. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Power_of_10. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A011557. 15 | /// 16 | /// 17 | public class PowersOf10Sequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of powers of 10. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(1); 27 | 28 | while (true) 29 | { 30 | yield return n; 31 | n *= 10; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/PowersOf2Sequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of powers of 2: a(n) = 2^n. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Power_of_two. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000079. 15 | /// 16 | /// 17 | public class PowersOf2Sequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of powers of 2. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(1); 27 | 28 | while (true) 29 | { 30 | yield return n; 31 | n *= 2; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/PrimePiSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of number of primes less than or equal to n (PrimePi(n)). 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Prime-counting_function. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A000720. 15 | /// 16 | /// 17 | public class PrimePiSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of number of primes. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | ISequence primes = new PrimesSequence(); 27 | var n = new BigInteger(0); 28 | var counter = new BigInteger(0); 29 | 30 | foreach (var p in primes.Sequence) 31 | { 32 | for (n++; n < p; n++) 33 | { 34 | yield return counter; 35 | } 36 | 37 | yield return ++counter; 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Sequences/PrimesSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Sequence of prime numbers. 10 | /// 11 | /// 12 | /// Wikipedia: https://wikipedia.org/wiki/Prime_number. 13 | /// 14 | /// 15 | /// OEIS: https://oeis.org/A000040. 16 | /// 17 | /// 18 | public class PrimesSequence : ISequence 19 | { 20 | /// 21 | /// Gets sequence of prime numbers. 22 | /// 23 | public IEnumerable Sequence 24 | { 25 | get 26 | { 27 | yield return 2; 28 | var primes = new List 29 | { 30 | 2, 31 | }; 32 | var n = new BigInteger(3); 33 | 34 | while (true) 35 | { 36 | if (primes.All(p => n % p != 0)) 37 | { 38 | yield return n; 39 | primes.Add(n); 40 | } 41 | 42 | n += 2; 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Sequences/PrimorialNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of primorial numbers: product of first n primes. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Primorial. 12 | /// 13 | /// 14 | /// OEIS: https://oeis.org/A002110. 15 | /// 16 | /// 17 | public class PrimorialNumbersSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of primorial numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var primes = new PrimesSequence().Sequence; 27 | var n = new BigInteger(1); 28 | 29 | foreach (var p in primes) 30 | { 31 | yield return n; 32 | n *= p; 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Algorithms/Sequences/SquaresSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// Sequence of square numbers. 9 | /// 10 | /// 11 | /// Wikipedia: https://wikipedia.org/wiki/Square_number. 12 | /// 13 | /// 14 | /// OEIS: http://oeis.org/A000290. 15 | /// 16 | /// 17 | public class SquaresSequence : ISequence 18 | { 19 | /// 20 | /// Gets sequence of square numbers. 21 | /// 22 | public IEnumerable Sequence 23 | { 24 | get 25 | { 26 | var n = new BigInteger(0); 27 | 28 | while (true) 29 | { 30 | yield return n * n; 31 | n++; 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Algorithms/Sequences/TetranacciNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Tetranacci numbers: a(n) = a(n-1) + a(n-2) + a(n-3) + a(n-4) with a(0) = a(1) = a(2) = a(3) = 1. 10 | /// 11 | /// 12 | /// OEIS: https://oeis.org/A000288. 13 | /// 14 | /// 15 | public class TetranacciNumbersSequence : ISequence 16 | { 17 | public IEnumerable Sequence 18 | { 19 | get 20 | { 21 | var buffer = Enumerable.Repeat(BigInteger.One, 4).ToArray(); 22 | while (true) 23 | { 24 | yield return buffer[0]; 25 | var next = buffer[0] + buffer[1] + buffer[2] + buffer[3]; 26 | buffer[0] = buffer[1]; 27 | buffer[1] = buffer[2]; 28 | buffer[2] = buffer[3]; 29 | buffer[3] = next; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Sequences/TribonacciNumbersSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Numerics; 4 | 5 | namespace Algorithms.Sequences; 6 | 7 | /// 8 | /// 9 | /// Tribonacci numbers: a(n) = a(n-1) + a(n-2) + a(n-3) with a(0)=a(1)=a(2)=1. 10 | /// 11 | /// 12 | /// OEIS: https://oeis.org/A000213. 13 | /// 14 | /// 15 | public class TribonacciNumbersSequence : ISequence 16 | { 17 | public IEnumerable Sequence 18 | { 19 | get 20 | { 21 | var buffer = Enumerable.Repeat(BigInteger.One, 4).ToArray(); 22 | while (true) 23 | { 24 | yield return buffer[0]; 25 | var next = buffer[0] + buffer[1] + buffer[2]; 26 | buffer[0] = buffer[1]; 27 | buffer[1] = buffer[2]; 28 | buffer[2] = next; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Sequences/ZeroSequence.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Numerics; 3 | 4 | namespace Algorithms.Sequences; 5 | 6 | /// 7 | /// 8 | /// The zero sequence. 9 | /// 10 | /// 11 | /// OEIS: https://oeis.org/A000004. 12 | /// 13 | /// 14 | public class ZeroSequence : ISequence 15 | { 16 | public IEnumerable Sequence 17 | { 18 | get 19 | { 20 | while (true) 21 | { 22 | yield return 0; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Shufflers/FisherYatesShuffler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Shufflers; 4 | 5 | /// 6 | /// Fisher-Yates shuffle is a simple shuffling algorithm, 7 | /// which is usually used to shuffle a deck of cards. 8 | /// 9 | /// Type array input. 10 | public class FisherYatesShuffler : IShuffler 11 | { 12 | /// 13 | /// Shuffles input array using Fisher-Yates algorithm. 14 | /// The algorithm starts shuffling from the last element 15 | /// and swap elements one by one. We use random index to 16 | /// choose element we use in swap operation. 17 | /// 18 | /// Array to shuffle. 19 | /// Random generator seed. Used to repeat the shuffle. 20 | public void Shuffle(T[] array, int? seed = null) 21 | { 22 | var random = seed is null ? new Random() : new Random(seed.Value); 23 | 24 | for (var i = array.Length - 1; i > 0; i--) 25 | { 26 | var j = random.Next(0, i + 1); 27 | 28 | (array[i], array[j]) = (array[j], array[i]); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Shufflers/IShuffler.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Shufflers; 2 | 3 | /// 4 | /// Shuffles array. 5 | /// 6 | /// Type of array item. 7 | public interface IShuffler 8 | { 9 | /// 10 | /// Shuffles array. 11 | /// 12 | /// Array to Shuffle. 13 | void Shuffle(T[] array, int? seed = null); 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/ExchangeSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.Comparison; 4 | 5 | /// 6 | /// Class that implements exchange sort algorithm. 7 | /// 8 | /// Type of array element. 9 | public class ExchangeSorter : IComparisonSorter 10 | { 11 | /// 12 | /// Sorts array using specified comparer, 13 | /// internal, in-place, stable, 14 | /// time complexity: O(n^2), 15 | /// space complexity: O(1), 16 | /// where n - array length. 17 | /// 18 | /// Array to sort. 19 | /// Compares elements. 20 | public void Sort(T[] array, IComparer comparer) 21 | { 22 | for (var i = 0; i < array.Length - 1; i++) 23 | { 24 | for (var j = i + 1; j < array.Length; j++) 25 | { 26 | if (comparer.Compare(array[i], array[j]) > 0) 27 | { 28 | (array[j], array[i]) = (array[i], array[j]); 29 | } 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/IComparisonSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.Comparison; 4 | 5 | /// 6 | /// Sorts array in ascending order using comparison sort. 7 | /// 8 | /// Type of array item. 9 | public interface IComparisonSorter 10 | { 11 | /// 12 | /// Sorts array in ascending order. 13 | /// 14 | /// Array to sort. 15 | /// Comparer to compare items of . 16 | void Sort(T[] array, IComparer comparer); 17 | } 18 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/InsertionSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.Comparison; 4 | 5 | /// 6 | /// Class that implements insertion sort algorithm. 7 | /// 8 | /// Type of array element. 9 | public class InsertionSorter : IComparisonSorter 10 | { 11 | /// 12 | /// Sorts array using specified comparer, 13 | /// internal, in-place, stable, 14 | /// time complexity: O(n^2), 15 | /// space complexity: O(1), 16 | /// where n - array length. 17 | /// 18 | /// Array to sort. 19 | /// Compares elements. 20 | public void Sort(T[] array, IComparer comparer) 21 | { 22 | for (var i = 1; i < array.Length; i++) 23 | { 24 | for (var j = i; j > 0 && comparer.Compare(array[j], array[j - 1]) < 0; j--) 25 | { 26 | var temp = array[j - 1]; 27 | array[j - 1] = array[j]; 28 | array[j] = temp; 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/MiddlePointQuickSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.Comparison; 4 | 5 | /// 6 | /// Sorts arrays using quicksort (selecting middle point as a pivot). 7 | /// 8 | /// Type of array element. 9 | public sealed class MiddlePointQuickSorter : QuickSorter 10 | { 11 | protected override T SelectPivot(T[] array, IComparer comparer, int left, int right) => 12 | array[left + (right - left) / 2]; 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/RandomPivotQuickSorter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Algorithms.Sorters.Comparison; 5 | 6 | /// 7 | /// Sorts arrays using quicksort (selecting random point as a pivot). 8 | /// 9 | /// Type of array element. 10 | public sealed class RandomPivotQuickSorter : QuickSorter 11 | { 12 | private readonly Random random = new(); 13 | 14 | protected override T SelectPivot(T[] array, IComparer comparer, int left, int right) => 15 | array[random.Next(left, right + 1)]; 16 | } 17 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/SelectionSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.Comparison; 4 | 5 | /// 6 | /// Class that implements selection sort algorithm. 7 | /// 8 | /// Type of array element. 9 | public class SelectionSorter : IComparisonSorter 10 | { 11 | /// 12 | /// Sorts array using specified comparer, 13 | /// internal, in-place, stable, 14 | /// time complexity: O(n^2), 15 | /// space complexity: O(1), 16 | /// where n - array length. 17 | /// 18 | /// Array to sort. 19 | /// Compares elements. 20 | public void Sort(T[] array, IComparer comparer) 21 | { 22 | for (var i = 0; i < array.Length - 1; i++) 23 | { 24 | var jmin = i; 25 | for (var j = i + 1; j < array.Length; j++) 26 | { 27 | if (comparer.Compare(array[jmin], array[j]) > 0) 28 | { 29 | jmin = j; 30 | } 31 | } 32 | 33 | var t = array[i]; 34 | array[i] = array[jmin]; 35 | array[jmin] = t; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Comparison/TimSorterSettings.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Sorters.Comparison; 2 | 3 | public class TimSorterSettings 4 | { 5 | public int MinMerge { get; } 6 | 7 | public int MinGallop { get; } 8 | 9 | public TimSorterSettings(int minMerge = 32, int minGallop = 7) 10 | { 11 | MinMerge = minMerge; 12 | MinGallop = minGallop; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Algorithms/Sorters/External/IExternalSorter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Algorithms.Sorters.External; 4 | 5 | public interface IExternalSorter 6 | { 7 | /// 8 | /// Sorts elements in sequential storage in ascending order. 9 | /// 10 | /// Memory that contains array to sort and will contain the result. 11 | /// Temporary memory for working purposes. 12 | void Sort(ISequentialStorage mainMemory, ISequentialStorage temporaryMemory, IComparer comparer); 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Sorters/External/ISequentialStorage.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Sorters.External; 2 | 3 | public interface ISequentialStorage 4 | { 5 | public int Length { get; } 6 | 7 | ISequentialStorageReader GetReader(); 8 | 9 | ISequentialStorageWriter GetWriter(); 10 | } 11 | -------------------------------------------------------------------------------- /Algorithms/Sorters/External/ISequentialStorageReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Sorters.External; 4 | 5 | public interface ISequentialStorageReader : IDisposable 6 | { 7 | T Read(); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithms/Sorters/External/ISequentialStorageWriter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Sorters.External; 4 | 5 | public interface ISequentialStorageWriter : IDisposable 6 | { 7 | void Write(T value); 8 | } 9 | -------------------------------------------------------------------------------- /Algorithms/Sorters/Integer/IIntegerSorter.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Sorters.Integer; 2 | 3 | /// 4 | /// Sorts array of integers without comparing them. 5 | /// 6 | public interface IIntegerSorter 7 | { 8 | /// 9 | /// Sorts array in ascending order. 10 | /// 11 | /// Array to sort. 12 | void Sort(int[] array); 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Sorters/String/IStringSorter.cs: -------------------------------------------------------------------------------- 1 | namespace Algorithms.Sorters.String; 2 | 3 | /// 4 | /// Sorts array of strings without comparing them. 5 | /// 6 | public interface IStringSorter 7 | { 8 | /// 9 | /// Sorts array in ascending order. 10 | /// 11 | /// Array to sort. 12 | void Sort(string[] array); 13 | } 14 | -------------------------------------------------------------------------------- /Algorithms/Strings/GeneralStringAlgorithms.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Strings; 4 | 5 | /// 6 | /// Implements simple algorithms on strings. 7 | /// 8 | public static class GeneralStringAlgorithms 9 | { 10 | /// 11 | /// Finds character that creates longest consecutive substring with single character. 12 | /// 13 | /// String to find in. 14 | /// Tuple containing char and number of times it appeared in a row. 15 | public static Tuple FindLongestConsecutiveCharacters(string input) 16 | { 17 | var maxChar = input[0]; 18 | 19 | var max = 1; 20 | var current = 1; 21 | 22 | for (var i = 1; i < input.Length; i++) 23 | { 24 | if (input[i] == input[i - 1]) 25 | { 26 | current++; 27 | if (current > max) 28 | { 29 | max = current; 30 | maxChar = input[i]; 31 | } 32 | } 33 | else 34 | { 35 | current = 1; 36 | } 37 | } 38 | 39 | return new Tuple(maxChar, max); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Algorithms/Strings/Permutation.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Algorithms.Strings; 5 | 6 | public static class Permutation 7 | { 8 | /// 9 | /// Returns every anagram of a given word. 10 | /// 11 | /// List of anagrams. 12 | public static List GetEveryUniquePermutation(string word) 13 | { 14 | if (word.Length < 2) 15 | { 16 | return new List 17 | { 18 | word, 19 | }; 20 | } 21 | 22 | var result = new HashSet(); 23 | 24 | for (var i = 0; i < word.Length; i++) 25 | { 26 | var temp = GetEveryUniquePermutation(word.Remove(i, 1)); 27 | 28 | result.UnionWith(temp.Select(subPerm => word[i] + subPerm)); 29 | } 30 | 31 | return result.ToList(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Strings/Similarity/HammingDistance.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms.Strings.Similarity; 4 | 5 | /// 6 | /// 7 | /// Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. 8 | /// Time complexity is O(n) where n is the length of the string. 9 | /// 10 | /// 11 | /// Wikipedia: https://en.wikipedia.org/wiki/Hamming_distance. 12 | /// 13 | /// 14 | public static class HammingDistance 15 | { 16 | /// 17 | /// Calculates Hamming distance between two strings of equal length. 18 | /// 19 | /// First string. 20 | /// Second string. 21 | /// Levenshtein distance between source and target strings. 22 | public static int Calculate(string s1, string s2) 23 | { 24 | if(s1.Length != s2.Length) 25 | { 26 | throw new ArgumentException("Strings must be equal length."); 27 | } 28 | 29 | var distance = 0; 30 | for (var i = 0; i < s1.Length; i++) 31 | { 32 | distance += s1[i] != s2[i] ? 1 : 0; 33 | } 34 | 35 | return distance; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /DataStructures.Tests/DataStructures.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | ..\stylecop.ruleset 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | all 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /DataStructures.Tests/DisjointSet/DisjointSetTests.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.DisjointSet; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace DataStructures.Tests.DisjointSet; 6 | 7 | [TestFixture] 8 | public class DisjointSetTests 9 | { 10 | [Test] 11 | public static void MakeSetDataInitializationTest() 12 | { 13 | DisjointSet ds = new(); 14 | var one = ds.MakeSet(1); 15 | var two = ds.MakeSet(2); 16 | one.Data.Should().Be(1); 17 | two.Data.Should().Be(2); 18 | } 19 | [Test] 20 | public static void UnionTest() 21 | { 22 | DisjointSet ds = new(); 23 | var one = ds.MakeSet(1); 24 | var two = ds.MakeSet(2); 25 | var three = ds.MakeSet(3); 26 | ds.UnionSet(one, two); 27 | ds.FindSet(one).Should().Be(ds.FindSet(two)); 28 | ds.UnionSet(one, three); 29 | ds.FindSet(two).Should().Be(ds.FindSet(three)); 30 | (one.Rank + two.Rank + three.Rank).Should().Be(1); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DataStructures.Tests/Fenwick/BinaryIndexedTreeTests.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.Fenwick; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace DataStructures.Tests.Fenwick; 6 | 7 | [TestFixture] 8 | internal class BinaryIndexedTreeTests 9 | { 10 | [Test] 11 | public void GetSum_CreateBITAndRequestSum_ReturnCorrect() 12 | { 13 | int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; 14 | var tree = new BinaryIndexedTree(array); 15 | var expectedSum = 12; 16 | 17 | var resultedSum = tree.GetSum(5); 18 | 19 | resultedSum.Should().Be(expectedSum); 20 | } 21 | 22 | [Test] 23 | public void UpdateTree_UpdateTreeAndRequestSum_GetSum() 24 | { 25 | int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; 26 | var tree = new BinaryIndexedTree(array); 27 | var expectedSum = 18; 28 | 29 | array[3] += 6; 30 | tree.UpdateTree(3, 6); 31 | 32 | var resultedSum = tree.GetSum(5); 33 | resultedSum.Should().Be(expectedSum); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /DataStructures.Tests/Heap/PairingHeap/PairingHeapComparerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using DataStructures.Heap.PairingHeap; 3 | using FluentAssertions; 4 | using NUnit.Framework; 5 | 6 | namespace DataStructures.Tests.Heap.PairingHeap; 7 | 8 | internal class PairingHeapComparerTests 9 | { 10 | [Test] 11 | public void Compare_CheckAscending_ReturnNegative() 12 | { 13 | var minHeap = new PairingNodeComparer(Sorting.Ascending, Comparer.Default); 14 | var node1 = new PairingHeapNode(10); 15 | var node2 = new PairingHeapNode(20); 16 | 17 | var items = minHeap.Compare(node1.Value, node2.Value); 18 | 19 | items.Should().Be(-1); 20 | } 21 | 22 | [Test] 23 | public void Compare_CheckAscending_ReturnPositive() 24 | { 25 | var minHeap = new PairingNodeComparer(Sorting.Descending, Comparer.Default); 26 | var node1 = new PairingHeapNode(10); 27 | var node2 = new PairingHeapNode(20); 28 | 29 | var items = minHeap.Compare(node1.Value, node2.Value); 30 | 31 | items.Should().Be(1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DataStructures.Tests/InvertedIndexTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace DataStructures.Tests; 6 | 7 | public class InvertedIndexTests 8 | { 9 | [Test] 10 | public void Or_GetSourcesWithAtLeastOneFromList_ReturnAllSources() 11 | { 12 | var index = new InvertedIndex(); 13 | var source1 = "one star is sparkling bright"; 14 | var source2 = "two stars are sparkling even brighter"; 15 | index.AddToIndex(nameof(source1), source1); 16 | index.AddToIndex(nameof(source2), source2); 17 | 18 | var or = index.Or(new List { "star", "sparkling" }); 19 | 20 | or.Should().BeEquivalentTo(nameof(source1), nameof(source2)); 21 | } 22 | 23 | [Test] 24 | public void And_GetSourcesWithAllInsideList_ReturnFirstSource() 25 | { 26 | var index = new InvertedIndex(); 27 | var source1 = "one star is sparkling bright"; 28 | var source2 = "two stars are sparkling even brighter"; 29 | index.AddToIndex(nameof(source1), source1); 30 | index.AddToIndex(nameof(source2), source2); 31 | 32 | var and = index.And(new List { "star", "sparkling" }); 33 | 34 | and.Should().BeEquivalentTo(nameof(source1)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /DataStructures.Tests/SegmentTrees/SegmentTreeApplyTests.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.SegmentTrees; 2 | using NUnit.Framework; 3 | 4 | namespace DataStructures.Tests.SegmentTrees; 5 | 6 | [TestFixture] 7 | public class SegmentTreeApplyTests 8 | { 9 | private readonly SegmentTreeApply testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); 10 | 11 | [Test] 12 | public void Apply_Query_Update_Query_Test() 13 | { 14 | Assert.That(testTree.Query(1, 4), Is.EqualTo(22)); 15 | testTree.Apply(0, 3, 2); 16 | Assert.That(testTree.Operand, Is.EqualTo(new[] { 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 })); 17 | Assert.That(testTree.Query(1, 4), Is.EqualTo(36)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /DataStructures.Tests/SegmentTrees/SegmentTreeTests.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.SegmentTrees; 2 | using NUnit.Framework; 3 | 4 | namespace DataStructures.Tests.SegmentTrees; 5 | 6 | [TestFixture] 7 | public class SegmentTreeTests 8 | { 9 | private readonly SegmentTree testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); 10 | 11 | [Test] 12 | public void TreeArray_Test() 13 | { 14 | int[] expectedArray = { 0, 39, 22, 17, 17, 5, 15, 2, 8, 9, 1, 4, 8, 7, 2, 0 }; 15 | Assert.That(testTree.Tree, Is.EqualTo(expectedArray)); 16 | } 17 | 18 | [TestCase(1, 4, 22)] 19 | [TestCase(2, 2, 1)] 20 | public void Query_Test(int left, int right, int expectedValue) 21 | { 22 | Assert.That(testTree.Query(left, right), Is.EqualTo(expectedValue)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DataStructures.Tests/SegmentTrees/SegmentTreeUpdateTest.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.SegmentTrees; 2 | using NUnit.Framework; 3 | 4 | namespace DataStructures.Tests.SegmentTrees; 5 | 6 | [TestFixture] 7 | public class SegmentTreeUpdateTests 8 | { 9 | [SetUp] 10 | public void Init() 11 | { 12 | testTree = new SegmentTreeUpdate(new[] { 8, 9, 1, 4, 8, 7, 2 }); 13 | } 14 | 15 | private SegmentTreeUpdate testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); 16 | 17 | [TestCase(2, 3, 1, 4, 24)] 18 | [TestCase(0, 3, 1, 4, 22)] 19 | public void Update_Test(int node, int value, int left, int right, int aftQuery) 20 | { 21 | testTree.Update(node, value); 22 | Assert.That(aftQuery, Is.EqualTo(testTree.Query(left, right))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DataStructures.Tests/UnrolledList/UnrolledLinkedListTests.cs: -------------------------------------------------------------------------------- 1 | using DataStructures.UnrolledList; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | 5 | namespace DataStructures.Tests.UnrolledList; 6 | 7 | public class UnrolledLinkedListTests 8 | { 9 | [Test] 10 | public void Insert_LinkArrayToLinkedList_ReturnArrayHaveSameItems() 11 | { 12 | var linkedList = new UnrolledLinkedList(6); 13 | var contest = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; 14 | foreach (var number in contest) 15 | { 16 | linkedList.Insert(number); 17 | } 18 | 19 | var result = linkedList.GetRolledItems(); 20 | 21 | result.Should().BeEquivalentTo(contest); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DataStructures/AATree/AATreeNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.AATree; 2 | 3 | /// 4 | /// Generic node class for AATree. 5 | /// 6 | /// Type of key for node. 7 | public class AaTreeNode 8 | { 9 | /// 10 | /// Initializes a new instance of the class. 11 | /// 12 | /// The initial key of this node. 13 | /// The level of this node. See for more details. 14 | public AaTreeNode(TKey key, int level) 15 | { 16 | Key = key; 17 | Level = level; 18 | } 19 | 20 | /// 21 | /// Gets or Sets key for this node. 22 | /// 23 | public TKey Key { get; set; } 24 | 25 | /// 26 | /// Gets or Sets level for this node. 27 | /// 28 | public int Level { get; set; } 29 | 30 | /// 31 | /// Gets or sets the left subtree of this node. 32 | /// 33 | public AaTreeNode? Left { get; set; } 34 | 35 | /// 36 | /// Gets or sets the right subtree of this node. 37 | /// 38 | public AaTreeNode? Right { get; set; } 39 | } 40 | -------------------------------------------------------------------------------- /DataStructures/BinarySearchTree/BinarySearchTreeNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.BinarySearchTree; 2 | 3 | /// 4 | /// Generic node class for BinarySearchTree. 5 | /// Keys for each node are immutable. 6 | /// 7 | /// Type of key for the node. Keys must implement IComparable. 8 | public class BinarySearchTreeNode 9 | { 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | /// The key of this node. 14 | public BinarySearchTreeNode(TKey key) => Key = key; 15 | 16 | /// 17 | /// Gets the key for this node. 18 | /// 19 | public TKey Key { get; } 20 | 21 | /// 22 | /// Gets or sets the reference to a child node that precedes/comes before this node. 23 | /// 24 | public BinarySearchTreeNode? Left { get; set; } 25 | 26 | /// 27 | /// Gets or sets the reference to a child node that follows/comes after this node. 28 | /// 29 | public BinarySearchTreeNode? Right { get; set; } 30 | } 31 | -------------------------------------------------------------------------------- /DataStructures/DataStructures.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | ..\stylecop.ruleset 6 | true 7 | enable 8 | 9 | 10 | 11 | ./bin/DataStructures.xml 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /DataStructures/DisjointSet/Node.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.DisjointSet; 2 | 3 | /// 4 | /// node class to be used by disjoint set to represent nodes in Disjoint Set forest. 5 | /// 6 | /// generic type for data to be stored. 7 | public class Node 8 | { 9 | public int Rank { get; set; } 10 | 11 | public Node Parent { get; set; } 12 | 13 | public T Data { get; set; } 14 | 15 | public Node(T data) 16 | { 17 | Data = data; 18 | Parent = this; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /DataStructures/Graph/IDirectedWeightedGraph.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace DataStructures.Graph; 4 | 5 | public interface IDirectedWeightedGraph 6 | { 7 | int Count { get; } 8 | 9 | Vertex?[] Vertices { get; } 10 | 11 | void AddEdge(Vertex startVertex, Vertex endVertex, double weight); 12 | 13 | Vertex AddVertex(T data); 14 | 15 | bool AreAdjacent(Vertex startVertex, Vertex endVertex); 16 | 17 | double AdjacentDistance(Vertex startVertex, Vertex endVertex); 18 | 19 | IEnumerable?> GetNeighbors(Vertex vertex); 20 | 21 | void RemoveEdge(Vertex startVertex, Vertex endVertex); 22 | 23 | void RemoveVertex(Vertex vertex); 24 | } 25 | -------------------------------------------------------------------------------- /DataStructures/Hashing/Entry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using DataStructures.Hashing.NumberTheory; 5 | 6 | namespace DataStructures.Hashing; 7 | 8 | /// 9 | /// Entry in the hash table. 10 | /// 11 | /// Type of the key. 12 | /// Type of the value. 13 | /// 14 | /// This class is used to store the key-value pairs in the hash table. 15 | /// 16 | public class Entry 17 | { 18 | public TKey? Key { get; set; } 19 | 20 | public TValue? Value { get; set; } 21 | 22 | public Entry(TKey key, TValue value) 23 | { 24 | Key = key; 25 | Value = value; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /DataStructures/Heap/PairingHeap/PairingHeapNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.Heap.PairingHeap; 2 | 3 | /// 4 | /// Node represented the value and connections. 5 | /// 6 | /// Type, supported comparing. 7 | public class PairingHeapNode 8 | { 9 | public PairingHeapNode(T value) 10 | { 11 | Value = value; 12 | } 13 | 14 | public T Value { get; set; } 15 | 16 | public PairingHeapNode ChildrenHead { get; set; } = null!; 17 | 18 | public bool IsHeadChild => Previous != null && Previous.ChildrenHead == this; 19 | 20 | public PairingHeapNode Previous { get; set; } = null!; 21 | 22 | public PairingHeapNode Next { get; set; } = null!; 23 | } 24 | -------------------------------------------------------------------------------- /DataStructures/Heap/PairingHeap/PairingNodeComparer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace DataStructures.Heap.PairingHeap; 5 | 6 | /// 7 | /// Node comparer. 8 | /// 9 | /// Node type. 10 | public class PairingNodeComparer : IComparer where T : IComparable 11 | { 12 | private readonly bool isMax; 13 | private readonly IComparer nodeComparer; 14 | 15 | public PairingNodeComparer(Sorting sortDirection, IComparer comparer) 16 | { 17 | isMax = sortDirection == Sorting.Descending; 18 | nodeComparer = comparer; 19 | } 20 | 21 | public int Compare(T? x, T? y) 22 | { 23 | return !isMax 24 | ? CompareNodes(x, y) 25 | : CompareNodes(y, x); 26 | } 27 | 28 | private int CompareNodes(T? one, T? second) 29 | { 30 | return nodeComparer.Compare(one, second); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /DataStructures/Heap/PairingHeap/Sorting.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.Heap.PairingHeap; 2 | 3 | public enum Sorting 4 | { 5 | /// 6 | /// Ascending order. 7 | /// 8 | Ascending = 0, 9 | 10 | /// 11 | /// Descending order. 12 | /// 13 | Descending = 1, 14 | } 15 | -------------------------------------------------------------------------------- /DataStructures/LinkedList/CircularLinkedList/CircularLinkedListNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.LinkedList.CircularLinkedList 2 | { 3 | /// 4 | /// Represents a node in the Circular Linked List. 5 | /// Each node contains generic data and a reference to the next node. 6 | /// 7 | /// The type of the data stored in the node. 8 | /// 9 | /// Initializes a new instance of the class. 10 | /// 11 | /// The data to be stored in the node. 12 | public class CircularLinkedListNode(T data) 13 | { 14 | /// 15 | /// Gets or sets the data for the node. 16 | /// 17 | public T Data { get; set; } = data; 18 | 19 | /// 20 | /// Gets or sets the reference to the next node in the list. 21 | /// 22 | public CircularLinkedListNode? Next { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /DataStructures/LinkedList/DoublyLinkedList/DoublyLinkedListNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.LinkedList.DoublyLinkedList; 2 | 3 | /// 4 | /// Generic node class for Doubly Linked List. 5 | /// 6 | /// Generic type. 7 | public class DoublyLinkedListNode 8 | { 9 | /// 10 | /// Initializes a new instance of the class. 11 | /// 12 | /// Data to be stored in this node. 13 | public DoublyLinkedListNode(T data) => Data = data; 14 | 15 | /// 16 | /// Gets the data stored on this node. 17 | /// 18 | public T Data { get; } 19 | 20 | /// 21 | /// Gets or sets the reference to the next node in the Doubly Linked List. 22 | /// 23 | public DoublyLinkedListNode? Next { get; set; } 24 | 25 | /// 26 | /// Gets or sets the reference to the previous node in the Doubly Linked List. 27 | /// 28 | public DoublyLinkedListNode? Previous { get; set; } 29 | } 30 | -------------------------------------------------------------------------------- /DataStructures/LinkedList/SinglyLinkedList/SinglyLinkedListNode.cs: -------------------------------------------------------------------------------- 1 | namespace DataStructures.LinkedList.SinglyLinkedList; 2 | 3 | public class SinglyLinkedListNode 4 | { 5 | public SinglyLinkedListNode(T data) 6 | { 7 | Data = data; 8 | Next = null; 9 | } 10 | 11 | public T Data { get; } 12 | 13 | public SinglyLinkedListNode? Next { get; set; } 14 | } 15 | -------------------------------------------------------------------------------- /DataStructures/LinkedList/SkipList/SkipListNode.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | 3 | namespace DataStructures.LinkedList.SkipList; 4 | 5 | [DebuggerDisplay("Key = {Key}, Height = {Height}, Value = {Value}")] 6 | internal class SkipListNode 7 | { 8 | public SkipListNode(int key, TValue? value, int height) 9 | { 10 | Key = key; 11 | Value = value; 12 | Height = height; 13 | Next = new SkipListNode[height]; 14 | } 15 | 16 | public int Key { get; } 17 | 18 | public TValue? Value { get; set; } 19 | 20 | public SkipListNode[] Next { get; } 21 | 22 | public int Height { get; } 23 | } 24 | -------------------------------------------------------------------------------- /Utilities.Tests/Extensions/RandomExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | using Utilities.Extensions; 5 | 6 | namespace Utilities.Tests.Extensions; 7 | 8 | public class RandomExtensionsTests 9 | { 10 | [Test] 11 | public void NextVector_ShouldReturnNormalizedVector() 12 | { 13 | var random = new Random(0); 14 | 15 | var result = random.NextVector(10); 16 | 17 | result.Length.Should().Be(10); 18 | result.Magnitude().Should().BeApproximately(1.0, 1e-6); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Utilities.Tests/Utilities.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | false 6 | ..\stylecop.ruleset 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Utilities/Exceptions/ItemNotFoundException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Utilities.Exceptions; 4 | 5 | /// 6 | /// Signs that sequence doesn't contain any items that one was looking for. 7 | /// 8 | public class ItemNotFoundException : Exception 9 | { 10 | } 11 | -------------------------------------------------------------------------------- /Utilities/Extensions/DictionaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Utilities.Extensions; 5 | 6 | public static class DictionaryExtensions 7 | { 8 | /// 9 | /// Adds the specified key value tuples to the dictionary. 10 | /// 11 | /// The dictionary. 12 | /// The collection of key value tuples to add. 13 | /// The type of the keys in the dictionary. 14 | /// The type of the values in the dictionary. 15 | /// 16 | /// A key from the already exists in . 17 | /// 18 | public static void AddMany( 19 | this Dictionary keys, 20 | IEnumerable<(TKey Key, TValue Value)> enumerable) where TKey : notnull 21 | { 22 | foreach (var (key, value) in enumerable) 23 | { 24 | keys.Add(key, value); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Utilities/Extensions/RandomExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Utilities.Extensions; 5 | 6 | public static class RandomExtensions 7 | { 8 | /// 9 | /// Returns a random normalized vector of the specified size. 10 | /// 11 | /// The random number generator. 12 | /// The size of the vector to return. 13 | /// A random normalized vector. 14 | public static double[] NextVector(this Random rand, int size) 15 | { 16 | var vector = Enumerable.Range(0, size) 17 | .Select(_ => rand.NextDouble()).ToArray(); 18 | var norm = vector.Magnitude(); 19 | return vector.Select(x => x / norm).ToArray(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Utilities/Utilities.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | ..\stylecop.ruleset 6 | true 7 | enable 8 | 9 | 10 | 11 | ./bin/Utilities.xml 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | all 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /stylecop.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", 3 | "settings": { 4 | "indentation": { 5 | "useTabs": false 6 | }, 7 | "layoutRules": { 8 | "newlineAtEndOfFile": "require" 9 | }, 10 | "orderingRules": { 11 | "blankLinesBetweenUsingGroups": "omit", 12 | "usingDirectivesPlacement": "outsideNamespace" 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /stylecop.ruleset: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------