Showing preview only (2,068K chars total). Download the full file or copy to clipboard to get everything.
Repository: TheAlgorithms/C-Sharp
Branch: master
Commit: 96e2905cab7b
Files: 627
Total size: 1.9 MB
Directory structure:
gitextract_zwg869o3/
├── .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/
│ ├── 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/
│ │ ├── AutokeyEncorder.cs
│ │ ├── BlowfishEncoder.cs
│ │ ├── CaesarEncoder.cs
│ │ ├── FeistelCipher.cs
│ │ ├── HillEncoder.cs
│ │ ├── IEncoder.cs
│ │ ├── NysiisEncoder.cs
│ │ ├── SoundexEncoder.cs
│ │ └── VigenereEncoder.cs
│ ├── Financial/
│ │ └── PresentValue.cs
│ ├── GlobalUsings.cs
│ ├── Graph/
│ │ ├── ArticulationPoints.cs
│ │ ├── BellmanFord.cs
│ │ ├── BipartiteGraph.cs
│ │ ├── BreadthFirstSearch.cs
│ │ ├── BreadthFirstTreeTraversal.cs
│ │ ├── Bridges.cs
│ │ ├── DepthFirstSearch.cs
│ │ ├── Dijkstra/
│ │ │ ├── DijkstraAlgorithm.cs
│ │ │ └── DistanceModel.cs
│ │ ├── FloydWarshall.cs
│ │ ├── IGraphSearch.cs
│ │ ├── Kosaraju.cs
│ │ ├── MinimumSpanningTree/
│ │ │ ├── Kruskal.cs
│ │ │ └── PrimMatrix.cs
│ │ ├── TarjanStronglyConnectedComponents.cs
│ │ └── TopologicalSort.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
│ ├── MachineLearning/
│ │ ├── KNearestNeighbors.cs
│ │ ├── LinearRegression.cs
│ │ └── LogisticRegression.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
│ │ ├── DoubleFactorial.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
│ │ ├── PrimeChecker.cs
│ │ ├── Pseudoinverse/
│ │ │ └── PseudoInverse.cs
│ │ ├── Relu.cs
│ │ ├── RungeKuttaMethod.cs
│ │ ├── Series/
│ │ │ └── Maclaurin.cs
│ │ ├── Sigmoid.cs
│ │ ├── SoftMax.cs
│ │ ├── SumOfDigits.cs
│ │ └── Tanh.cs
│ ├── Other/
│ │ ├── BoyerMooreMajorityVote.cs
│ │ ├── DecisionsConvolutions.cs
│ │ ├── FermatPrimeChecker.cs
│ │ ├── FloodFill.cs
│ │ ├── GaussOptimization.cs
│ │ ├── GeoLocation.cs
│ │ ├── Geofence.cs
│ │ ├── Geohash.cs
│ │ ├── Int2Binary.cs
│ │ ├── JulianEaster.cs
│ │ ├── KadanesAlgorithm.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
│ │ ├── GraphColoring/
│ │ │ └── GraphColoringSolver.cs
│ │ ├── JobScheduling/
│ │ │ ├── IntervalSchedulingSolver.cs
│ │ │ └── Job.cs
│ │ ├── KnightTour/
│ │ │ └── OpenKnightTour.cs
│ │ ├── NQueens/
│ │ │ └── BacktrackingNQueensSolver.cs
│ │ ├── StableMarriage/
│ │ │ ├── Accepter.cs
│ │ │ ├── GaleShapley.cs
│ │ │ └── Proposer.cs
│ │ └── TravelingSalesman/
│ │ └── TravelingSalesmanSolver.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
│ │ ├── LINQShuffler.cs
│ │ ├── NaiveShuffler.cs
│ │ └── RecursiveShuffler.cs
│ ├── Sorters/
│ │ ├── Comparison/
│ │ │ ├── BasicTimSorter.cs
│ │ │ ├── BinaryInsertionSorter.cs
│ │ │ ├── BogoSorter.cs
│ │ │ ├── BubbleSorter.cs
│ │ │ ├── CocktailSorter.cs
│ │ │ ├── CombSorter.cs
│ │ │ ├── CycleSorter.cs
│ │ │ ├── ExchangeSorter.cs
│ │ │ ├── GnomeSorter.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
│ │ ├── InfixToPostfix.cs
│ │ ├── NextGreaterElement.cs
│ │ └── ReverseStack.cs
│ └── Strings/
│ ├── GeneralStringAlgorithms.cs
│ ├── ManachersAlgorithm.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
├── 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/
│ │ ├── AutokeyEncoderTests.cs
│ │ ├── BlowfishEncoderTests.cs
│ │ ├── CaesarEncoderTests.cs
│ │ ├── FeistelCipherTest.cs
│ │ ├── HillEnconderTests.cs
│ │ ├── NysiisEncoderTests.cs
│ │ ├── SoundexEncoderTest.cs
│ │ └── VigenereEncoderTests.cs
│ ├── Financial/
│ │ └── PresentValueTests.cs
│ ├── GlobalUsings.cs
│ ├── Graph/
│ │ ├── ArticulationPointsTests.cs
│ │ ├── BellmanFordTests.cs
│ │ ├── BipartiteGraphTests.cs
│ │ ├── BreadthFirstSearchTests.cs
│ │ ├── BreadthFirstTreeTraversalTests.cs
│ │ ├── BridgesTests.cs
│ │ ├── DepthFirstSearchTests.cs
│ │ ├── Dijkstra/
│ │ │ └── DijkstraTests.cs
│ │ ├── FloydWarshallTests.cs
│ │ ├── KosarajuTests.cs
│ │ ├── MinimumSpanningTree/
│ │ │ ├── KruskalTests.cs
│ │ │ └── PrimMatrixTests.cs
│ │ ├── TarjanStronglyConnectedComponentsTests.cs
│ │ └── TopologicalSortTests.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
│ ├── MachineLearning/
│ │ ├── KNearestNeighborsTests.cs
│ │ ├── LinearRegressionTests.cs
│ │ └── LogisticRegressionTests.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
│ │ ├── DoubleFactorialTests.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
│ │ ├── PrimeNumberTest.cs
│ │ ├── PseudoInverse/
│ │ │ └── PseudoInverseTests.cs
│ │ ├── ReluTest.cs
│ │ ├── RungeKuttaMethodTest.cs
│ │ ├── SigmoidTests.cs
│ │ ├── SoftMaxTests.cs
│ │ ├── SumOfDigitsTest.cs
│ │ └── TanhTest.cs
│ ├── Other/
│ │ ├── BoyerMooreMajorityVoteTests.cs
│ │ ├── DecisionsConvolutionsTest.cs
│ │ ├── FermatPrimeCheckerTests.cs
│ │ ├── FloodFillTest.cs
│ │ ├── GaussOptimizationTest.cs
│ │ ├── GeoLocationTests.cs
│ │ ├── GeofenceTests.cs
│ │ ├── GeohashTests.cs
│ │ ├── Int2BinaryTests.cs
│ │ ├── JulianEasterTests.cs
│ │ ├── KadanesAlgorithmTests.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
│ │ ├── GraphColoring/
│ │ │ └── GraphColoringSolverTests.cs
│ │ ├── JobScheduling/
│ │ │ └── IntervalSchedulingSolverTests.cs
│ │ ├── KnightTour/
│ │ │ └── OpenKnightTourTests.cs
│ │ ├── NQueens/
│ │ │ └── BacktrackingNQueensSolverTests.cs
│ │ ├── StableMarriage/
│ │ │ └── GaleShapleyTests.cs
│ │ └── TravelingSalesman/
│ │ └── TravelingSalesmanSolverTests.cs
│ ├── RecommenderSystem/
│ │ └── CollaborativeFilteringTests.cs
│ ├── Search/
│ │ ├── AStarTests.cs
│ │ ├── 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
│ │ ├── LINQShufflerTests.cs
│ │ ├── NaiveShufflerTests.cs
│ │ └── RecursiveShufflerTests.cs
│ ├── Sorters/
│ │ ├── Comparison/
│ │ │ ├── BasicTeamSorterTests.cs
│ │ │ ├── BinaryInsertionSorterTests.cs
│ │ │ ├── BogoSorterTests.cs
│ │ │ ├── BubbleSorterTests.cs
│ │ │ ├── CocktailSorterTests.cs
│ │ │ ├── CombSorterTests.cs
│ │ │ ├── CycleSorterTests.cs
│ │ │ ├── ExchangeSorterTests.cs
│ │ │ ├── GnomeSorterTests.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
│ │ ├── InfixToPostfixTests.cs
│ │ ├── NextGreaterElementTests.cs
│ │ └── ReverseStackTests.cs
│ └── Strings/
│ ├── GeneralStringAlgorithmsTests.cs
│ ├── ManachersAlgorithmTests.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
├── C-Sharp.sln
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── DataStructures/
│ ├── AATree/
│ │ ├── AATree.cs
│ │ └── AATreeNode.cs
│ ├── AVLTree/
│ │ ├── AVLTree.cs
│ │ └── AVLTreeNode.cs
│ ├── BTree/
│ │ ├── BTree.cs
│ │ └── BTreeNode.cs
│ ├── Bag/
│ │ ├── Bag.cs
│ │ └── BagNode.cs
│ ├── BinarySearchTree/
│ │ ├── BinarySearchTree.cs
│ │ └── BinarySearchTreeNode.cs
│ ├── BitArray.cs
│ ├── Cache/
│ │ ├── LfuCache.cs
│ │ └── LruCache.cs
│ ├── DataStructures.csproj
│ ├── Deque/
│ │ └── Deque.cs
│ ├── DisjointSet/
│ │ ├── DisjointSet.cs
│ │ └── Node.cs
│ ├── Fenwick/
│ │ └── BinaryIndexedTree.cs
│ ├── GlobalUsings.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
├── DataStructures.Tests/
│ ├── AATreeTests.cs
│ ├── AVLTreeTests.cs
│ ├── BTreeTests.cs
│ ├── BagTests.cs
│ ├── BinarySearchTreeTests.cs
│ ├── BitArrayTests.cs
│ ├── Cache/
│ │ ├── LfuCacheTests.cs
│ │ └── LruCacheTests.cs
│ ├── DataStructures.Tests.csproj
│ ├── Deque/
│ │ └── DequeTests.cs
│ ├── DisjointSet/
│ │ └── DisjointSetTests.cs
│ ├── Fenwick/
│ │ └── BinaryIndexedTreeTests.cs
│ ├── GlobalUsings.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
├── LICENSE
├── README.md
├── Utilities/
│ ├── Exceptions/
│ │ └── ItemNotFoundException.cs
│ ├── Extensions/
│ │ ├── DictionaryExtensions.cs
│ │ ├── MatrixExtensions.cs
│ │ ├── RandomExtensions.cs
│ │ └── VectorExtensions.cs
│ ├── GlobalUsings.cs
│ └── Utilities.csproj
├── Utilities.Tests/
│ ├── Extensions/
│ │ ├── DictionaryExtensionsTests.cs
│ │ ├── MatrixExtensionsTests.cs
│ │ ├── RandomExtensionsTests.cs
│ │ └── VectorExtensionsTests.cs
│ ├── GlobalUsings.cs
│ └── Utilities.Tests.csproj
├── stylecop.json
└── stylecop.ruleset
================================================
FILE CONTENTS
================================================
================================================
FILE: .devcontainer/devcontainer.json
================================================
{
"name": "The Algorithms C#",
"image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm",
"customizations": {
"vscode": {
"extensions": [
"ms-dotnettools.csharp",
"ms-dotnettools.csdevkit",
"nunit.nunit-adapter",
"fluentassertions.fluentassertions"
]
}
},
"postCreateCommand": "sudo chown -R $(whoami) /workspaces"
}
================================================
FILE: .editorconfig
================================================
[*]
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
# Microsoft .NET properties
csharp_new_line_before_members_in_object_initializers = false
csharp_preferred_modifier_order = public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion
csharp_space_after_cast = false
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
dotnet_naming_rule.private_constants_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_constants_rule.severity = warning
dotnet_naming_rule.private_constants_rule.style = upper_camel_case_style
dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols
dotnet_naming_rule.private_instance_fields_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_instance_fields_rule.severity = warning
dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style
dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols
dotnet_naming_rule.private_static_fields_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_static_fields_rule.severity = warning
dotnet_naming_rule.private_static_fields_rule.style = lower_camel_case_style_1
dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols
dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_static_readonly_rule.severity = warning
dotnet_naming_rule.private_static_readonly_rule.style = upper_camel_case_style
dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols
dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule.severity = warning
dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_style.lower_camel_case_style_1.capitalization = camel_case
dotnet_naming_style.lower_camel_case_style_1.required_prefix = _
dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case
dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field
dotnet_naming_symbols.private_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static
dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = static,readonly
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_qualification_for_event = false:suggestion
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
# ReSharper properties
resharper_autodetect_indent_settings = true
resharper_braces_for_dowhile = required_for_multiline_statement
resharper_braces_for_fixed = required_for_multiline_statement
resharper_braces_for_for = required_for_multiline_statement
resharper_braces_for_foreach = required_for_multiline_statement
resharper_braces_for_ifelse = required_for_multiline_statement
resharper_braces_for_lock = required_for_multiline_statement
resharper_braces_for_using = required_for_multiline_statement
resharper_braces_for_while = required_for_multiline_statement
resharper_constructor_or_destructor_body = expression_body
resharper_csharp_insert_final_newline = true
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_lines = false
resharper_local_function_body = expression_body
resharper_method_or_operator_body = expression_body
resharper_new_line_before_while = true
resharper_place_attribute_on_same_line = false
resharper_space_after_cast = false
resharper_space_within_single_line_array_initializer_braces = true
resharper_trailing_comma_in_multiline_lists = true
resharper_use_indent_from_vs = false
# ReSharper inspection severities
resharper_arrange_redundant_parentheses_highlighting = hint
resharper_arrange_this_qualifier_highlighting = hint
resharper_arrange_trailing_comma_in_multiline_lists_highlighting = suggestion
resharper_arrange_type_member_modifiers_highlighting = hint
resharper_arrange_type_modifiers_highlighting = hint
resharper_built_in_type_reference_style_for_member_access_highlighting = hint
resharper_built_in_type_reference_style_highlighting = hint
resharper_redundant_base_qualifier_highlighting = warning
resharper_suggest_var_or_type_built_in_types_highlighting = hint
resharper_suggest_var_or_type_elsewhere_highlighting = hint
resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
[{*.har,*.inputactions,*.jsb2,*.jsb3,*.json,.babelrc,.eslintrc,.stylelintrc,bowerrc,jest.config}]
indent_style = space
indent_size = 2
[{*.yaml,*.yml}]
indent_style = space
indent_size = 2
[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,fs,fsi,fsscript,fsx,hlsl,hlsli,hlslinc,master,ml,mli,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}]
indent_style = space
indent_size = 4
tab_width = 4
================================================
FILE: .github/CODEOWNERS
================================================
* @siriak
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: Something works wrong
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
How to reproduce the behavior. Initial conditions, parameters, etc.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Actual behavior**
A clear and concise description of what has happened.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: Add something cool
labels: enhancement
assignees: ''
---
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): [...].
================================================
FILE: .github/pull_request_template.md
================================================
<!--
Please include a summary of the change.
Please also include relevant motivation and context (if applicable).
Put 'x' in between square brackets to mark an item as complete.
[x] means checked checkbox
[ ] means unchecked checkbox
-->
- [ ] I have performed a self-review of my code
- [ ] My code follows the style guidelines of this project
- [ ] I have added tests that prove my fix is effective or that my feature works
- [ ] New and existing unit tests pass locally with my changes
- [ ] Comments in areas I changed are up to date
- [ ] I have added comments to hard-to-understand areas of my code
- [ ] I have made corresponding changes to the README.md
================================================
FILE: .github/workflows/ci.yml
================================================
name: CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup .NET SDK
uses: actions/setup-dotnet@v3
with:
dotnet-version: 8.x
- name: Restore
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-restore --collect "XPlat Code Coverage"
- name: Upload coverage to codecov (tokenless)
if: >-
github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name != github.repository
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
- name: Upload coverage to codecov (with token)
if: >
github.repository == 'TheAlgorithms/C-Sharp' &&
(github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository)
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: true
================================================
FILE: .github/workflows/stale.yml
================================================
name: 'Close stale issues and PRs'
on:
schedule:
- cron: '0 0 * * *'
jobs:
stale:
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v4
with:
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.'
close-issue-message: 'This issue was closed because it has been stalled for 7 days with no activity.'
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.'
close-pr-message: 'This PR was closed because it has been stalled for 7 days with no activity.'
exempt-issue-labels: 'dont-close'
exempt-pr-labels: 'dont-close'
days-before-stale: 30
days-before-close: 7
================================================
FILE: .gitignore
================================================
# Visual Studio cache/options directory
.vs/
# Rider cache/options directory
.idea/
# Rider user config file
C-Sharp.sln.DotSettings.user
# Build results
bin/
obj/
TestResults/
================================================
FILE: Algorithms/Algorithms.csproj
================================================
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<CodeAnalysisRuleSet>..\stylecop.ruleset</CodeAnalysisRuleSet>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>./bin/Algorithms.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<AdditionalFiles Include="..\stylecop.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.88.8" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux.NoDependencies" Version="2.88.8" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DataStructures\DataStructures.csproj" />
<ProjectReference Include="..\Utilities\Utilities.csproj" />
</ItemGroup>
</Project>
================================================
FILE: Algorithms/Crypto/Digests/AsconDigest.cs
================================================
using System.Runtime.CompilerServices;
using Algorithms.Crypto.Utils;
namespace Algorithms.Crypto.Digests;
/// <summary>
/// Implements the Ascon cryptographic hash algorithm, providing both the standard Ascon-Hash and the Ascon-HashA variants.
/// </summary>
/// <remarks>
/// The <see cref="AsconDigest"/> class implements the Ascon hash function, a lightweight cryptographic algorithm designed for
/// resource-constrained environments such as IoT devices. It provides two variants:
/// <list type="bullet">
/// <item>
/// <description>
/// <see cref="AsconParameters.AsconHash"/>: The standard Ascon-Hash variant with 12 rounds of the permutation function for enhanced security.
/// </description>
/// </item>
/// <item>
/// <description>
/// <see cref="AsconParameters.AsconHashA"/>: A performance-optimized variant with 8 rounds of the permutation function, offering a trade-off between security and performance.
/// </description>
/// </item>
/// </list>
/// <br />
/// The AsconDigest processes data in 8-byte blocks, accumulating input until a block is complete, at which point it applies
/// the permutation function to update the internal state. After all data has been processed, the hash value can be finalized
/// and retrieved.
/// <br />
/// Ascon was designed to meet the requirements of lightweight cryptography, making it ideal for devices with limited computational power.
/// </remarks>
public class AsconDigest : IDigest
{
public enum AsconParameters
{
/// <summary>
/// Represents the Ascon Hash variant, the standard cryptographic hashing function of the Ascon family.
/// </summary>
/// <remarks>
/// AsconHash is the primary hashing algorithm in the Ascon family. It is designed for efficiency and security
/// in resource-constrained environments, such as IoT devices, and provides high resistance to cryptanalytic attacks.
/// This variant uses 12 rounds of the permutation function for increased security.
/// </remarks>
AsconHash,
/// <summary>
/// Represents the Ascon HashA variant, an alternative variant of the Ascon hashing function with fewer permutation rounds.
/// </summary>
/// <remarks>
/// AsconHashA is a variant of the Ascon hashing function that uses fewer rounds (8 rounds) of the permutation function,
/// trading off some security for improved performance in specific scenarios. It is still designed to be secure for many
/// applications, but it operates faster in environments where computational resources are limited.
/// </remarks>
AsconHashA,
}
/// <summary>
/// Specifies the Ascon variant being used (either Ascon-Hash or Ascon-HashA). This defines the cryptographic algorithm's behavior.
/// </summary>
private readonly AsconParameters asconParameters;
/// <summary>
/// The number of permutation rounds applied in the Ascon cryptographic process. This is determined by the selected Ascon variant.
/// </summary>
private readonly int asconPbRounds;
/// <summary>
/// Internal buffer that temporarily stores input data before it is processed in 8-byte blocks. The buffer is cleared after each block is processed.
/// </summary>
private readonly byte[] buffer = new byte[8];
/// <summary>
/// Internal state variable <c>x0</c> used in the cryptographic permutation function. This is updated continuously as input data is processed.
/// </summary>
private ulong x0;
/// <summary>
/// Internal state variable <c>x1</c> used in the cryptographic permutation function. This, along with other state variables, is updated during each round.
/// </summary>
private ulong x1;
/// <summary>
/// Internal state variable <c>x2</c> used in the cryptographic permutation function. It helps track the evolving state of the digest.
/// </summary>
private ulong x2;
/// <summary>
/// Internal state variable <c>x3</c> used in the cryptographic permutation function, contributing to the mixing and non-linearity of the state.
/// </summary>
private ulong x3;
/// <summary>
/// Internal state variable <c>x4</c> used in the cryptographic permutation function. This, along with <c>x0</c> to <c>x3</c>, ensures cryptographic security.
/// </summary>
private ulong x4;
/// <summary>
/// Tracks the current position within the <c>buffer</c> array. When <c>bufferPosition</c> reaches 8, the buffer is processed and reset.
/// </summary>
private int bufferPosition;
/// <summary>
/// Initializes a new instance of the <see cref="AsconDigest"/> class with the specified Ascon parameters.
/// </summary>
/// <param name="parameters">The Ascon variant to use, either <see cref="AsconParameters.AsconHash"/> or <see cref="AsconParameters.AsconHashA"/>.</param>
/// <remarks>
/// This constructor sets up the digest by selecting the appropriate number of permutation rounds based on the Ascon variant.
/// <list type="bullet">
/// <item><description>For <see cref="AsconParameters.AsconHash"/>, 12 permutation rounds are used.</description></item>
/// <item><description>For <see cref="AsconParameters.AsconHashA"/>, 8 permutation rounds are used.</description></item>
/// </list>
/// If an unsupported parameter is provided, the constructor throws an <see cref="ArgumentException"/> to indicate that the parameter is invalid.
/// The internal state of the digest is then reset to prepare for processing input data.
/// </remarks>
/// <exception cref="ArgumentException">Thrown when an invalid parameter setting is provided for Ascon Hash.</exception>
public AsconDigest(AsconParameters parameters)
{
// Set the Ascon parameter (AsconHash or AsconHashA) for this instance.
asconParameters = parameters;
// Determine the number of permutation rounds based on the Ascon variant.
asconPbRounds = parameters switch
{
AsconParameters.AsconHash => 12, // 12 rounds for Ascon-Hash variant.
AsconParameters.AsconHashA => 8, // 8 rounds for Ascon-HashA variant.
_ => throw new ArgumentException("Invalid parameter settings for Ascon Hash"), // Throw exception for invalid parameter.
};
// Reset the internal state to prepare for new input.
Reset();
}
/// <summary>
/// Gets the name of the cryptographic algorithm based on the selected Ascon parameter.
/// </summary>
/// <value>
/// A string representing the name of the algorithm variant, either "Ascon-Hash" or "Ascon-HashA".
/// </value>
/// <remarks>
/// This property determines the algorithm name based on the selected Ascon variant when the instance was initialized.
/// It supports two variants:
/// <list type="bullet">
/// <item><description>"Ascon-Hash" for the <see cref="AsconParameters.AsconHash"/> variant.</description></item>
/// <item><description>"Ascon-HashA" for the <see cref="AsconParameters.AsconHashA"/> variant.</description></item>
/// </list>
/// If an unsupported or unknown parameter is used, the property throws an <see cref="InvalidOperationException"/>.
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if an unknown Ascon parameter is encountered.</exception>
public string AlgorithmName
{
get
{
return asconParameters switch
{
AsconParameters.AsconHash => "Ascon-Hash", // Return "Ascon-Hash" for AsconHash variant.
AsconParameters.AsconHashA => "Ascon-HashA", // Return "Ascon-HashA" for AsconHashA variant.
_ => throw new InvalidOperationException(), // Throw an exception for unknown Ascon parameters.
};
}
}
/// <summary>
/// Gets the size of the resulting hash produced by the digest, in bytes.
/// </summary>
/// <returns>The size of the hash, which is 32 bytes (256 bits) for this digest implementation.</returns>
/// <remarks>
/// This method returns the fixed size of the hash output produced by the digest algorithm. In this implementation,
/// the digest produces a 256-bit hash, which corresponds to 32 bytes. This is typical for cryptographic hash functions
/// that aim to provide a high level of security by generating a large output size.
/// </remarks>
public int GetDigestSize() => 32;
/// <summary>
/// Gets the internal block size of the digest in bytes.
/// </summary>
/// <returns>The internal block size of the digest, which is 8 bytes (64 bits).</returns>
/// <remarks>
/// This method returns the block size that the digest algorithm uses when processing input data. The input is processed
/// in chunks (blocks) of 8 bytes at a time. This block size determines how the input data is split and processed in multiple
/// steps before producing the final hash.
/// </remarks>
public int GetByteLength() => 8;
/// <summary>
/// Updates the cryptographic state by processing a single byte of input and adding it to the internal buffer.
/// </summary>
/// <param name="input">The byte to be added to the internal buffer and processed.</param>
/// <remarks>
/// This method collects input bytes in an internal buffer. Once the buffer is filled (reaching 8 bytes), the buffer is processed
/// by converting it into a 64-bit unsigned integer in big-endian format and XORing it with the internal state variable <c>x0</c>.
/// After processing the buffer, the permutation function <see cref="P(int)"/> is applied to mix the internal state, and the buffer position is reset to zero.
/// <br/><br/>
/// If the buffer has not yet reached 8 bytes, the method simply adds the input byte to the buffer and waits for further input.
/// </remarks>
public void Update(byte input)
{
// Add the input byte to the buffer.
buffer[bufferPosition] = input;
// If the buffer is not full (less than 8 bytes), increment the buffer position and return early.
if (++bufferPosition != 8)
{
return; // Wait for more input to fill the buffer before processing.
}
// Once the buffer is full (8 bytes), convert the buffer to a 64-bit integer (big-endian) and XOR it with the state.
x0 ^= ByteEncodingUtils.BigEndianToUint64(buffer, 0);
// Apply the permutation function to mix the state.
P(asconPbRounds);
// Reset the buffer position for the next block of input.
bufferPosition = 0;
}
/// <summary>
/// Updates the cryptographic state by processing a segment of input data from a byte array, starting at a specified offset and length.
/// </summary>
/// <param name="input">The byte array containing the input data to be processed.</param>
/// <param name="inOff">The offset in the input array where processing should begin.</param>
/// <param name="inLen">The number of bytes from the input array to process.</param>
/// <remarks>
/// This method ensures that the input data is valid by checking the array length, starting from the provided offset,
/// and making sure it is long enough to accommodate the specified length. It then processes the data by converting
/// the relevant section of the byte array to a <see cref="ReadOnlySpan{T}"/> and delegating the actual block update to
/// the <see cref="BlockUpdate(ReadOnlySpan{byte})"/> method for further processing.
/// </remarks>
/// <exception cref="ArgumentException">
/// Thrown if the input data is too short, starting from <paramref name="inOff"/> and for the length <paramref name="inLen"/>.
/// </exception>
public void BlockUpdate(byte[] input, int inOff, int inLen)
{
// Validate the input data to ensure there is enough data to process from the specified offset and length.
ValidationUtils.CheckDataLength(input, inOff, inLen, "input buffer too short");
// Convert the input byte array into a ReadOnlySpan<byte> and delegate the processing to the span-based method.
BlockUpdate(input.AsSpan(inOff, inLen));
}
/// <summary>
/// Processes the input data by updating the internal cryptographic state, handling both partial and full blocks.
/// </summary>
/// <param name="input">A read-only span of bytes representing the input data to be processed.</param>
/// <remarks>
/// This method processes the input data in chunks of 8 bytes. It manages the internal buffer to accumulate data
/// until there are enough bytes to process a full 8-byte block. When the buffer is full or enough input is provided,
/// it XORs the buffered data with the internal state variable <c>x0</c> and applies the permutation function
/// <see cref="P"/> to update the cryptographic state.
/// <br/><br/>
/// If the input contains more than 8 bytes, the method continues to process full 8-byte blocks in a loop until
/// the input is exhausted. Any remaining bytes (less than 8) are stored in the internal buffer for future processing.
/// </remarks>
public void BlockUpdate(ReadOnlySpan<byte> input)
{
// Calculate the number of available bytes left in the buffer before it reaches 8 bytes.
var available = 8 - bufferPosition;
// If the input length is smaller than the remaining space in the buffer, copy the input into the buffer.
if (input.Length < available)
{
input.CopyTo(buffer.AsSpan(bufferPosition)); // Copy the small input into the buffer.
bufferPosition += input.Length; // Update the buffer position.
return; // Return early since we don't have enough data to process a full block.
}
// If there is data in the buffer, but it isn't full, fill it and process the full 8-byte block.
if (bufferPosition > 0)
{
// Copy enough bytes from the input to complete the buffer.
input[..available].CopyTo(buffer.AsSpan(bufferPosition));
// XOR the full buffer with the internal state (x0) and apply the permutation.
x0 ^= ByteEncodingUtils.BigEndianToUint64(buffer);
P(asconPbRounds); // Apply the permutation rounds.
// Update the input to exclude the bytes we've already processed from the buffer.
input = input[available..];
}
// Process full 8-byte blocks directly from the input.
while (input.Length >= 8)
{
// XOR the next 8-byte block from the input with the internal state and apply the permutation.
x0 ^= ByteEncodingUtils.BigEndianToUint64(input);
P(asconPbRounds);
// Move to the next 8-byte chunk in the input.
input = input[8..];
}
// Copy any remaining bytes (less than 8) into the buffer to store for future processing.
input.CopyTo(buffer);
bufferPosition = input.Length; // Update the buffer position to reflect the remaining unprocessed data.
}
/// <summary>
/// Finalizes the cryptographic hash computation, absorbing any remaining data, applying the final permutation,
/// and writing the resulting hash to the specified position in the provided output byte array.
/// </summary>
/// <param name="output">The byte array where the final 32-byte hash will be written.</param>
/// <param name="outOff">The offset in the output array at which to start writing the hash.</param>
/// <returns>The size of the hash (32 bytes).</returns>
/// <remarks>
/// This method finalizes the hash computation by converting the output array to a <see cref="Span{T}"/> and
/// calling the <see cref="DoFinal(Span{byte})"/> method. It provides flexibility in placing the result in an
/// existing byte array with a specified offset.
/// </remarks>
/// <exception cref="ArgumentException">Thrown if the output buffer is too small to hold the resulting hash.</exception>
public int DoFinal(byte[] output, int outOff)
{
// Call the Span-based DoFinal method with the output byte array and offset.
return DoFinal(output.AsSpan(outOff));
}
/// <summary>
/// Finalizes the cryptographic hash computation, absorbing any remaining data, applying the final permutation, and
/// writing the resulting hash to the provided output buffer.
/// </summary>
/// <param name="output">A span of bytes where the final 32-byte hash will be written.</param>
/// <returns>The size of the hash (32 bytes).</returns>
/// <remarks>
/// This method completes the hash computation by absorbing any remaining input data, applying the final permutation,
/// and extracting the state variables to produce the final hash. The method processes the state in 8-byte chunks,
/// writing the result into the output buffer in big-endian format. After the final permutation is applied, the internal
/// state is reset to prepare for a new hashing session.
/// </remarks>
/// <exception cref="ArgumentException">Thrown if the output buffer is too small to hold the resulting hash.</exception>
public int DoFinal(Span<byte> output)
{
// Validate that the output buffer is at least 32 bytes in length.
ValidationUtils.CheckOutputLength(output, 32, "output buffer too short");
// Absorb any remaining input and apply the final permutation.
AbsorbAndFinish();
// Convert the first part of the state (x0) to big-endian format and write it to the output.
ByteEncodingUtils.UInt64ToBigEndian(x0, output);
// Loop to process the remaining parts of the internal state (x1, x2, etc.).
for (var i = 0; i < 3; ++i)
{
// Move to the next 8-byte segment in the output buffer.
output = output[8..];
// Apply the permutation rounds to mix the state.
P(asconPbRounds);
// Convert the updated state variable (x0) to big-endian format and write it to the output.
ByteEncodingUtils.UInt64ToBigEndian(x0, output);
}
// Reset the internal state for the next hash computation.
Reset();
// Return the size of the hash (32 bytes).
return 32;
}
/// <summary>
/// Computes the cryptographic hash of the input byte array and returns the result as a lowercase hexadecimal string.
/// </summary>
/// <param name="input">The input byte array to be hashed.</param>
/// <returns>A string containing the computed hash in lowercase hexadecimal format.</returns>
/// <remarks>
/// This method takes a byte array as input, processes it to compute the Ascon hash, and returns the result as a hexadecimal string.
/// It internally converts the byte array to a <see cref="Span{T}"/> and delegates the actual hashing to the
/// <see cref="Digest(Span{byte})"/> method.
/// </remarks>
public string Digest(byte[] input)
{
return Digest(input.AsSpan());
}
/// <summary>
/// Computes the cryptographic hash of the input span of bytes and returns the result as a lowercase hexadecimal string.
/// </summary>
/// <param name="input">A span of bytes representing the input data to be hashed.</param>
/// <returns>A string containing the computed hash in lowercase hexadecimal format.</returns>
/// <remarks>
/// This method processes the input span using the Ascon cryptographic algorithm to compute the hash. It accumulates
/// the input, applies the necessary permutations and internal state updates, and finally produces a hash in the form
/// of a 32-byte array. The result is then converted into a lowercase hexadecimal string using <see cref="BitConverter"/>.
/// </remarks>
public string Digest(Span<byte> input)
{
// Update the internal state with the input data.
BlockUpdate(input);
// Create an array to hold the final hash output (32 bytes).
var output = new byte[GetDigestSize()];
// Finalize the hash computation and store the result in the output array.
DoFinal(output, 0);
// Convert the hash (byte array) to a lowercase hexadecimal string.
return BitConverter.ToString(output).Replace("-", string.Empty).ToLowerInvariant();
}
/// <summary>
/// Resets the internal state of the Ascon cryptographic hash algorithm to its initial state based on the selected variant.
/// </summary>
/// <remarks>
/// This method clears the internal buffer and resets the buffer position to zero. Depending on the specified
/// Ascon variant (<see cref="AsconParameters.AsconHash"/> or <see cref="AsconParameters.AsconHashA"/>), it also reinitializes
/// the internal state variables (<c>x0</c>, <c>x1</c>, <c>x2</c>, <c>x3</c>, <c>x4</c>) to their starting values.
/// <br/><br/>
/// The reset is necessary to prepare the hash function for a new message. It ensures that previous messages do not
/// affect the new one and that the internal state is consistent with the algorithm’s specification for the selected variant.
/// </remarks>
public void Reset()
{
// Clear the buffer to remove any leftover data from previous operations.
Array.Clear(buffer, 0, buffer.Length);
// Reset the buffer position to zero to start processing fresh input.
bufferPosition = 0;
// Initialize the internal state variables (x0, x1, x2, x3, x4) based on the selected Ascon variant.
switch (asconParameters)
{
// If using the AsconHashA variant, set the specific initial state values for x0 through x4.
case AsconParameters.AsconHashA:
x0 = 92044056785660070UL;
x1 = 8326807761760157607UL;
x2 = 3371194088139667532UL;
x3 = 15489749720654559101UL;
x4 = 11618234402860862855UL;
break;
// If using the AsconHash variant, set the specific initial state values for x0 through x4.
case AsconParameters.AsconHash:
x0 = 17191252062196199485UL;
x1 = 10066134719181819906UL;
x2 = 13009371945472744034UL;
x3 = 4834782570098516968UL;
x4 = 3787428097924915520UL;
break;
// If an unknown Ascon variant is encountered, throw an exception.
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Finalizes the absorption phase of the cryptographic hash by padding the buffer and applying the final permutation round.
/// </summary>
/// <remarks>
/// This method is called when the input data has been fully absorbed into the internal state, and it needs to be finalized.
/// The buffer is padded with a specific value (0x80) to signify the end of the data, and the remaining portion of the buffer is
/// XORed with the internal state variable <c>x0</c>. After padding, the final permutation round is applied using 12 rounds of
/// the permutation function <see cref="P(int)"/>. This ensures the internal state is fully mixed and the cryptographic hash
/// is securely finalized.
/// </remarks>
private void AbsorbAndFinish()
{
// Pad the buffer with 0x80 to indicate the end of the data.
buffer[bufferPosition] = 0x80;
// XOR the buffer (after padding) with the internal state x0, but only the relevant portion of the buffer is considered.
// The (56 - (bufferPosition << 3)) shifts ensure that only the unprocessed part of the buffer is XORed into x0.
x0 ^= ByteEncodingUtils.BigEndianToUint64(buffer, 0) & (ulong.MaxValue << (56 - (bufferPosition << 3)));
// Apply 12 rounds of the permutation function to fully mix and finalize the internal state.
P(12);
}
/// <summary>
/// Executes the cryptographic permutation function by applying a sequence of rounds that transform the internal state variables.
/// </summary>
/// <param name="numberOfRounds">
/// The number of rounds to execute. If set to 12, additional rounds are performed with specific constants to enhance the security of the transformation.
/// </param>
/// <remarks>
/// In the Ascon cryptographic algorithm, the permutation function <c>P</c> transforms the internal state over multiple rounds.
/// This method applies a set of round constants, each of which alters the state variables (<c>x0</c>, <c>x1</c>, <c>x2</c>, <c>x3</c>, <c>x4</c>) differently,
/// ensuring that the transformation introduces non-linearity and diffusion, which are essential for cryptographic security.
/// <br/><br/>
/// When <paramref name="numberOfRounds"/> is set to 12, the method first applies four unique round constants.
/// Afterward, it applies a fixed set of six additional constants regardless of the number of rounds.
/// </remarks>
private void P(int numberOfRounds)
{
if (numberOfRounds == 12)
{
Round(0xf0UL);
Round(0xe1UL);
Round(0xd2UL);
Round(0xc3UL);
}
Round(0xb4UL);
Round(0xa5UL);
Round(0x96UL);
Round(0x87UL);
Round(0x78UL);
Round(0x69UL);
Round(0x5aUL);
Round(0x4bUL);
}
/// <summary>
/// Executes a single round of the cryptographic permutation function, transforming the internal state
/// variables <c>x0</c>, <c>x1</c>, <c>x2</c>, <c>x3</c>, and <c>x4</c> using XOR, AND, and NOT operations, along with circular bit rotations.
/// This function is designed to introduce diffusion and non-linearity into the state for cryptographic security.
/// </summary>
/// <param name="circles">
/// A 64-bit unsigned integer constant that influences the round's transformation. Each round uses a unique value of this constant
/// to ensure that the transformation applied to the state differs for each round.
/// </param>
/// <remarks>
/// The <c>Round</c> function uses a series of bitwise operations (XOR, AND, NOT) and circular bit rotations to mix
/// the internal state. Each transformation step introduces non-linearity and ensures that small changes in the input or state
/// variables propagate widely across the internal state, enhancing the security of the cryptographic process.
/// <br/><br/>
/// The round constant (<paramref name="circles"/>) plays a crucial role in altering the state at each round, ensuring
/// that each round contributes uniquely to the overall cryptographic transformation. Circular rotations are applied using
/// <see cref="LongUtils.RotateRight(ulong, int)"/> to spread bits throughout the 64-bit word.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Round(ulong circles)
{
// Step 1: Perform XOR and AND operations to mix inputs and state variables
var t0 = x0 ^ x1 ^ x2 ^ x3 ^ circles ^ (x1 & (x0 ^ x2 ^ x4 ^ circles));
var t1 = x0 ^ x2 ^ x3 ^ x4 ^ circles ^ ((x1 ^ x2 ^ circles) & (x1 ^ x3));
var t2 = x1 ^ x2 ^ x4 ^ circles ^ (x3 & x4);
var t3 = x0 ^ x1 ^ x2 ^ circles ^ (~x0 & (x3 ^ x4));
var t4 = x1 ^ x3 ^ x4 ^ ((x0 ^ x4) & x1);
// Step 2: Apply circular right shifts and update the internal state variables
x0 = t0 ^ LongUtils.RotateRight(t0, 19) ^ LongUtils.RotateRight(t0, 28);
x1 = t1 ^ LongUtils.RotateRight(t1, 39) ^ LongUtils.RotateRight(t1, 61);
x2 = ~(t2 ^ LongUtils.RotateRight(t2, 1) ^ LongUtils.RotateRight(t2, 6));
x3 = t3 ^ LongUtils.RotateRight(t3, 10) ^ LongUtils.RotateRight(t3, 17);
x4 = t4 ^ LongUtils.RotateRight(t4, 7) ^ LongUtils.RotateRight(t4, 41);
}
}
================================================
FILE: Algorithms/Crypto/Digests/IDigest.cs
================================================
namespace Algorithms.Crypto.Digests;
/// <summary>
/// Interface for message digest algorithms, providing methods to update, finalize, and reset the digest state.
/// </summary>
public interface IDigest
{
/// <summary>
/// Gets the name of the digest algorithm (e.g., "SHA-256").
/// </summary>
string AlgorithmName { get; }
/// <summary>
/// Gets the size of the digest in bytes (e.g., 32 bytes for SHA-256).
/// </summary>
/// <returns>The size of the digest in bytes.</returns>
int GetDigestSize();
/// <summary>
/// Gets the byte length of the internal buffer used by the digest.
/// </summary>
/// <returns>The byte length of the internal buffer.</returns>
int GetByteLength();
/// <summary>
/// Updates the digest with a single byte of input data.
/// </summary>
/// <param name="input">The byte to add to the digest.</param>
void Update(byte input);
/// <summary>
/// Updates the digest with a portion of a byte array.
/// </summary>
/// <param name="input">The byte array containing the input data.</param>
/// <param name="inOff">The offset within the array to start reading from.</param>
/// <param name="inLen">The length of data to read from the array.</param>
void BlockUpdate(byte[] input, int inOff, int inLen);
/// <summary>
/// Updates the digest with a portion of input data from a <see cref="ReadOnlySpan{T}"/> of bytes.
/// </summary>
/// <param name="input">The <see cref="ReadOnlySpan{T}"/> containing the input data.</param>
void BlockUpdate(ReadOnlySpan<byte> input);
/// <summary>
/// Completes the digest calculation and stores the result in the specified byte array.
/// </summary>
/// <param name="output">The byte array to store the final digest.</param>
/// <param name="outOff">The offset within the array to start writing the digest.</param>
/// <returns>The number of bytes written to the output array.</returns>
int DoFinal(byte[] output, int outOff);
/// <summary>
/// Completes the digest calculation and stores the result in the specified <see cref="Span{T}"/> of bytes.
/// </summary>
/// <param name="output">The <see cref="Span{T}"/> to store the final digest.</param>
/// <returns>The number of bytes written to the output span.</returns>
int DoFinal(Span<byte> output);
string Digest(byte[] input);
string Digest(Span<byte> input);
/// <summary>
/// Resets the digest to its initial state, clearing all data accumulated so far.
/// </summary>
void Reset();
}
================================================
FILE: Algorithms/Crypto/Digests/Md2Digest.cs
================================================
namespace Algorithms.Crypto.Digests;
/// <summary>
/// MD2 is a cryptographic hash function that takes an input message and produces a 128-bit output, also called a message
/// digest or a hash.
/// <para>
/// A hash function has two main properties: it is easy to compute the hash from the input, but it is hard to find the
/// input from the hash or to find two different inputs that produce the same hash.
/// </para>
/// <para>
/// MD2 works by first padding the input message to a multiple of 16 bytes and adding a 16-byte checksum to it. Then, it
/// uses a 48-byte auxiliary block and a 256-byte S-table (a fixed permutation of the numbers 0 to 255) to process the
/// message in 16-byte blocks.
/// </para>
/// <para>
/// For each block, it updates the auxiliary block by XORing it with the message block and then applying the S-table 18
/// times. After all blocks are processed, the first 16 bytes of the auxiliary block become the hash value.
/// </para>
/// </summary>
public class Md2Digest
{
// The S-table is a set of constants generated by shuffling the integers 0 through 255 using a variant of
// Durstenfeld's algorithm with a pseudorandom number generator based on decimal digits of pi.
private static readonly byte[] STable =
[
41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19,
98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202,
30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18,
190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122,
169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33,
128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3,
255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198,
79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241,
69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2,
27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38,
44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82,
106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74,
120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57,
242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10,
49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20,
];
// The X buffer is a 48-byte auxiliary block used to compute the message digest.
private readonly byte[] xBuffer = new byte[48];
// The M buffer is a 16-byte auxiliary block that keeps 16 byte blocks from the input data.
private readonly byte[] mBuffer = new byte[16];
// The checksum buffer
private readonly byte[] checkSum = new byte[16];
private int xBufferOffset;
private int mBufferOffset;
/// <summary>
/// Computes the MD2 hash of the input byte array.
/// </summary>
/// <param name="input">The input byte array to be hashed.</param>
/// <returns>The MD2 hash as a byte array.</returns>
public byte[] Digest(byte[] input)
{
Update(input, 0, input.Length);
// Pad the input to a multiple of 16 bytes.
var paddingByte = (byte)(mBuffer.Length - mBufferOffset);
for (var i = mBufferOffset; i < mBuffer.Length; i++)
{
mBuffer[i] = paddingByte;
}
// Process the checksum of the padded input.
ProcessCheckSum(mBuffer);
// Process the first block of the padded input.
ProcessBlock(mBuffer);
// Process the second block of the padded input, which is the checksum.
ProcessBlock(checkSum);
// Copy the first 16 bytes of the auxiliary block to the output.
var digest = new byte[16];
xBuffer.AsSpan(xBufferOffset, 16).CopyTo(digest);
// Reset the internal state for reuse.
Reset();
return digest;
}
/// <summary>
/// Resets the engine to its initial state.
/// </summary>
private void Reset()
{
xBufferOffset = 0;
for (var i = 0; i != xBuffer.Length; i++)
{
xBuffer[i] = 0;
}
mBufferOffset = 0;
for (var i = 0; i != mBuffer.Length; i++)
{
mBuffer[i] = 0;
}
for (var i = 0; i != checkSum.Length; i++)
{
checkSum[i] = 0;
}
}
/// <summary>
/// Performs the compression step of MD2 hash algorithm.
/// </summary>
/// <param name="block">The 16 bytes block to be compressed.</param>
/// <remarks>
/// the compression step is designed to achieve diffusion and confusion, two properties that make it hard to reverse
/// or analyze the hash function. Diffusion means that changing one bit of the input affects many bits of the output,
/// and confusion means that there is no apparent relation between the input and the output.
/// </remarks>
private void ProcessBlock(byte[] block)
{
// Copying and XORing: The input block is copied to the second and third parts of the internal state, while XORing
// the input block with the first part of the internal state.
// By copying the input block to the second and third parts of the internal state, the compression step ensures
// that each input block contributes to the final output digest.
// By XORing the input block with the first part of the internal state, the compression step introduces a non-linear
// transformation that depends on both the input and the previous state. This makes it difficult to deduce the input
// or the state from the output, or vice versa.
for (var i = 0; i < 16; i++)
{
xBuffer[i + 16] = block[i];
xBuffer[i + 32] = (byte)(block[i] ^ xBuffer[i]);
}
var tmp = 0;
// Mixing: The internal state is mixed using the substitution table for 18 rounds. Each round consists of looping
// over the 48 bytes of the internal state and updating each byte by XORing it with a value from the substitution table.
// The mixing process ensures that each byte of the internal state is affected by every byte of the input block and
// every byte of the substitution table. This creates a high degree of diffusion and confusion, which makes it hard
// to find collisions or preimages for the hash function.
for (var j = 0; j < 18; j++)
{
for (var k = 0; k < 48; k++)
{
tmp = xBuffer[k] ^= STable[tmp];
tmp &= 0xff;
}
tmp = (tmp + j) % 256;
}
}
/// <summary>
/// Performs the checksum step of MD2 hash algorithm.
/// </summary>
/// <param name="block">The 16 bytes block to calculate the checksum.</param>
/// <remarks>
/// The checksum step ensures that changing any bit of the input message will change about half of the bits of the
/// checksum, making it harder to find collisions or preimages.
/// </remarks>
private void ProcessCheckSum(byte[] block)
{
// Assign the last element of checksum to the variable last. This is the initial value of the checksum.
var last = checkSum[15];
for (var i = 0; i < 16; i++)
{
// Compute the XOR of the current element of the mBuffer array and the last value, and uses it as an index
// to access an element of STable. This is a substitution operation that maps each byte to another byte using
// the STable.
var map = STable[(mBuffer[i] ^ last) & 0xff];
// Compute the XOR of the current element of checkSum and the substituted byte, and stores it back to the
// checksum. This is a mixing operation that updates the checksum value with the input data.
checkSum[i] ^= map;
// Assign the updated element of checksum to last. This is to keep track of the last checksum value for the
// next iteration.
last = checkSum[i];
}
}
/// <summary>
/// Update the message digest with a single byte.
/// </summary>
/// <param name="input">The input byte to digest.</param>
private void Update(byte input)
{
mBuffer[mBufferOffset++] = input;
}
/// <summary>
/// Update the message digest with a block of bytes.
/// </summary>
/// <param name="input">The byte array containing the data.</param>
/// <param name="inputOffset">The offset into the byte array where the data starts.</param>
/// <param name="length">The length of the data.</param>
private void Update(byte[] input, int inputOffset, int length)
{
// process whole words
while (length >= 16)
{
Array.Copy(input, inputOffset, mBuffer, 0, 16);
ProcessCheckSum(mBuffer);
ProcessBlock(mBuffer);
length -= 16;
inputOffset += 16;
}
while (length > 0)
{
Update(input[inputOffset]);
inputOffset++;
length--;
}
}
}
================================================
FILE: Algorithms/Crypto/Exceptions/CryptoException.cs
================================================
namespace Algorithms.Crypto.Exceptions;
/// <summary>
/// Represents errors that occur during cryptographic operations.
/// </summary>
public class CryptoException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CryptoException"/> class.
/// </summary>
public CryptoException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CryptoException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public CryptoException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CryptoException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="inner">The exception that is the cause of the current exception.</param>
public CryptoException(string message, Exception inner)
: base(message, inner)
{
}
}
================================================
FILE: Algorithms/Crypto/Exceptions/DataLengthException.cs
================================================
namespace Algorithms.Crypto.Exceptions;
/// <summary>
/// Represents errors that occur when the length of data in a cryptographic operation is invalid or incorrect.
/// </summary>
public class DataLengthException : CryptoException
{
/// <summary>
/// Initializes a new instance of the <see cref="DataLengthException"/> class.
/// </summary>
public DataLengthException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLengthException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public DataLengthException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataLengthException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="inner">The exception that is the cause of the current exception.</param>
public DataLengthException(string message, Exception inner)
: base(message, inner)
{
}
}
================================================
FILE: Algorithms/Crypto/Exceptions/OutputLengthException.cs
================================================
namespace Algorithms.Crypto.Exceptions;
/// <summary>
/// Represents an exception that is thrown when the output buffer length is insufficient for a cryptographic operation.
/// </summary>
/// <remarks>
/// The <see cref="OutputLengthException"/> is a specific subclass of <see cref="DataLengthException"/>. It is used in cryptographic
/// operations to signal that the provided output buffer does not have enough space to store the required output. This exception is
/// typically thrown when encryption, hashing, or other cryptographic operations require more space than what has been allocated in
/// the output buffer.
/// <br />
/// This exception provides constructors for creating the exception with a custom message, an inner exception, or both. By inheriting
/// from <see cref="DataLengthException"/>, it can be handled similarly in cases where both input and output length issues may arise.
/// </remarks>
public class OutputLengthException : DataLengthException
{
/// <summary>
/// Initializes a new instance of the <see cref="OutputLengthException"/> class.
/// </summary>
/// <remarks>
/// This constructor initializes a new instance of the <see cref="OutputLengthException"/> class without any additional message or inner exception.
/// It is commonly used when a generic output length issue needs to be raised without specific details.
/// </remarks>
public OutputLengthException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OutputLengthException"/> class with a specified error message.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <remarks>
/// This constructor allows for a custom error message to be provided, giving more detail about the specific issue with the output length.
/// </remarks>
public OutputLengthException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OutputLengthException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="inner">The exception that is the cause of the current exception.</param>
/// <remarks>
/// This constructor allows for both a custom message and an inner exception, which can be useful for propagating
/// the underlying cause of the error. For example, if the output buffer length is too short due to incorrect calculations,
/// the root cause (e.g., an <see cref="ArgumentException"/>) can be passed in as the inner exception.
/// </remarks>
public OutputLengthException(string message, Exception inner)
: base(message, inner)
{
}
}
================================================
FILE: Algorithms/Crypto/Paddings/IBlockCipherPadding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// A common interface that all block cipher padding schemes should follow.
/// </summary>
public interface IBlockCipherPadding
{
/// <summary>
/// Adds padding bytes to the end of the given block of the data and returns the number of bytes that were added.
/// </summary>
/// <param name="inputData">The input data array that needs padding.</param>
/// <param name="inputOffset">The offset in the input array where the padding should start.</param>
/// <returns>The number of bytes added.</returns>
/// <remarks>
/// This method expects that the input parameter <paramref name="inputData"/> contains the last block of plain text
/// that needs to be padded. This means that the value of <paramref name="inputData"/> has to have the same value as
/// the last block of plain text. The reason for this is that some modes such as the <see cref="TbcPadding"/> base the
/// padding value on the last byte of the plain text.
/// </remarks>
public int AddPadding(byte[] inputData, int inputOffset);
/// <summary>
/// Removes the padding bytes from the given block of data and returns the original data as a new array.
/// </summary>
/// <param name="inputData">The input data array containing the padding.</param>
/// <returns>The input data without the padding as a new byte array.</returns>
/// <exception cref="ArgumentException">Thrown when the input data has invalid padding.</exception>
public byte[] RemovePadding(byte[] inputData);
/// <summary>
/// Gets the number of padding bytes in the input data.
/// </summary>
/// <param name="input">The input data array that has padding.</param>
/// <returns>The number of padding bytes in the input data.</returns>
/// <exception cref="ArgumentException">Thrown when the input data has invalid padding.</exception>
public int GetPaddingCount(byte[] input);
}
================================================
FILE: Algorithms/Crypto/Paddings/Iso10126D2Padding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// <para>
/// This class implements the ISO10126d2 padding scheme, which is a standard way of padding data to fit a certain block
/// size.
/// </para>
/// <para>
/// ISO10126d2 padding adds N-1 random bytes and one byte of value N to the end of the data, where N is the number of
/// bytes needed to reach the block size. For example, if the block size is 16 bytes, and the data is 10 bytes long, then
/// 5 random bytes and a byte with value 6 will be added to the end of data. This way the padded data will be 16 bytes
/// long and can be encrypted or decrypted by a block cipher algorithm.
/// </para>
/// <para>
/// The padding can easily be removed after decryption by looking at the last byte and discarding that many bytes from
/// the end of the data.
/// </para>
/// </summary>
public class Iso10126D2Padding : IBlockCipherPadding
{
/// <summary>
/// Adds random padding to the input data array to make it a multiple of the block size according to the
/// ISO10126d2 standard.
/// </summary>
/// <param name="inputData">The input data array that needs to be padded.</param>
/// <param name="inputOffset">The offset in the input data array where the padding should start.</param>
/// <returns>The number of bytes added as padding.</returns>
/// <exception cref="ArgumentException">
/// Thrown when there is not enough space in the input array for padding.
/// </exception>
public int AddPadding(byte[] inputData, int inputOffset)
{
// Calculate how many bytes need to be added to reach the next multiple of block size.
var code = (byte)(inputData.Length - inputOffset);
if (code == 0 || inputOffset + code > inputData.Length)
{
throw new ArgumentException("Not enough space in input array for padding");
}
// Add the padding.
while (inputOffset < (inputData.Length - 1))
{
inputData[inputOffset] = (byte)RandomNumberGenerator.GetInt32(255);
inputOffset++;
}
// Set the last byte of the array to the size of the padding added.
inputData[inputOffset] = code;
return code;
}
/// <summary>
/// Removes the padding from the input data array and returns the original data.
/// </summary>
/// <param name="inputData">
/// The input data with ISO10126d2 padding. Must not be null and must have a valid length and padding.
/// </param>
/// <returns>
/// The input data without the padding as a new byte array.
/// </returns>
/// <exception cref="ArgumentException">
/// Thrown when the padding length is invalid.
/// </exception>
public byte[] RemovePadding(byte[] inputData)
{
// Get the size of the padding from the last byte of the input data.
var paddingLength = inputData[^1];
// Check if the padding size is valid.
if (paddingLength < 1 || paddingLength > inputData.Length)
{
throw new ArgumentException("Invalid padding length");
}
// Create a new array to hold the original data.
var output = new byte[inputData.Length - paddingLength];
// Copy the original data into the new array.
Array.Copy(inputData, 0, output, 0, output.Length);
return output;
}
/// <summary>
/// Gets the number of padding bytes from the input data array.
/// </summary>
/// <param name="input">The input data array that has been padded.</param>
/// <returns>The number of padding bytes.</returns>
/// <exception cref="ArgumentNullException">Thrown when the input is null.</exception>
/// <exception cref="ArgumentException">Thrown when the padding block is corrupted.</exception>
public int GetPaddingCount(byte[] input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input), "Input cannot be null");
}
// Get the last byte of the input data as the padding value.
var lastByte = input[^1];
var paddingCount = lastByte & 0xFF;
// Calculate the index where the padding starts.
var paddingStartIndex = input.Length - paddingCount;
var paddingCheckFailed = 0;
// The paddingCheckFailed will be non-zero under the following circumstances:
// 1. When paddingStartIndex is negative: This happens when paddingCount (the last byte of the input array) is
// greater than the length of the input array. In other words, the padding count is claiming that there are more
// padding bytes than there are bytes in the array, which is not a valid scenario.
// 2. When paddingCount - 1 is negative: This happens when paddingCount is zero or less. Since paddingCount
// represents the number of padding bytes and is derived from the last byte of the input array, it should always
// be a positive number. If it's zero or less, it means that either there's no padding, or an invalid negative
// padding count has shomehow encoded into the last byte of the input array.
paddingCheckFailed = (paddingStartIndex | (paddingCount - 1)) >> 31;
if (paddingCheckFailed != 0)
{
throw new ArgumentException("Padding block is corrupted");
}
return paddingCount;
}
}
================================================
FILE: Algorithms/Crypto/Paddings/Iso7816D4Padding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// <para>
/// ISO 7816-4 padding is a padding scheme that is defined in the ISO/IEC 7816-4 documentation.
/// </para>
/// <para>
/// It is used for adding data to the end of a message that needs to be encrypted or decrypted by a block cipher.
/// </para>
/// ISO 7816-4 padding works as follows:
/// <para>
/// The first byte of the padding is 0x80, which is the hexadecimal representation of the binary value 10000000. This
/// byte indicates the start of the padding.
/// </para>
/// <para>
/// All other bytes of the padding are 0x00, which is the hexadecimal representation of the binary value 00000000. These
/// bytes fill up the remaining space in the last block.
/// </para>
/// <para>
/// The padding can be of any size, from 1 byte to the block size. For example, if the block size is 8 bytes and the
/// message has 5 bytes, then 3 bytes of padding are needed. The padding would be <c>0x80 0x00 0x00</c>.
/// </para>
/// <para>
/// ISO 7816-4 padding is also known as bit padding,because it simply places a single 1 bit after the plaintext, followed
/// by 0 valued bits up to the block size. It works for both byte-oriented and bit-oriented protocols, as it does not
/// depend on any specific character encoding or representation.
/// </para>
/// </summary>
public class Iso7816D4Padding : IBlockCipherPadding
{
/// <summary>
/// Adds padding to the input data according to the ISO 7816-4 standard.
/// </summary>
/// <param name="inputData">The input data array that needs padding.</param>
/// <param name="inputOffset">The offset in the input data array where the padding should start.</param>
/// <returns>The number of bytes added as padding.</returns>
/// <exception cref="ArgumentException">
/// Thrown when there is not enough space in the input array for padding or when the input offset is invalid.
/// </exception>
public int AddPadding(byte[] inputData, int inputOffset)
{
// Calculate the number of padding bytes based on the input data length and offset.
var code = (byte)(inputData.Length - inputOffset);
// Check if the padding bytes are valid and fit in the input array.
if (code == 0 || inputOffset + code > inputData.Length)
{
throw new ArgumentException("Not enough space in input array for padding");
}
// Set the first padding byte to 80. This marks the start of padding in the ISO 7816-4 standard.
inputData[inputOffset] = 80;
inputOffset++;
// Set the remaining padding bytes to 0.
while (inputOffset < inputData.Length)
{
inputData[inputOffset] = 0;
inputOffset++;
}
// Return the number of padding bytes.
return code;
}
/// <summary>
/// Removes the padding from the input data array and returns the original data.
/// </summary>
/// <param name="inputData">
/// The input data with ISO 7816-4 padding. Must not be null and must have a valid length and padding.
/// </param>
/// <returns>The input data without the padding as a new byte array.</returns>
/// <exception cref="ArgumentException">
/// Thrown when the input data has invalid padding.
/// </exception>
public byte[] RemovePadding(byte[] inputData)
{
// Find the index of the first padding byte by scanning from the end of the input.
var paddingIndex = inputData.Length - 1;
// Skip all the padding bytes that are 0.
while (paddingIndex >= 0 && inputData[paddingIndex] == 0)
{
paddingIndex--;
}
// Check if the first padding byte is 0x80.
if (paddingIndex < 0 || inputData[paddingIndex] != 0x80)
{
throw new ArgumentException("Invalid padding");
}
// Create a new array to store the unpadded data.
var unpaddedData = new byte[paddingIndex];
// Copy the unpadded data from the input data to the new array.
Array.Copy(inputData, 0, unpaddedData, 0, paddingIndex);
// Return the unpadded data array.
return unpaddedData;
}
/// <summary>
/// Gets the number of padding bytes in the input data according to the ISO 7816-4 standard.
/// </summary>
/// <param name="input">The input data array that has padding.</param>
/// <returns>The number of padding bytes in the input data.</returns>
/// <exception cref="ArgumentException"> Thrown when the input data has invalid padding.</exception>
public int GetPaddingCount(byte[] input)
{
// Initialize the index of the first padding byte to -1.
var paddingStartIndex = -1;
// Initialize a mask to indicate if the current byte is still part of the padding.
var stillPaddingMask = -1;
// Initialize the current index to the end of the input data.
var currentIndex = input.Length;
// Loop backwards through the input data.
while (--currentIndex >= 0)
{
// Get the current byte as an unsigned integer.
var currentByte = input[currentIndex] & 0xFF;
// Compute a mask to indicate if the current byte is 0x00.
var isZeroMask = (currentByte - 1) >> 31;
// Compute a mask to indicate if the current byte is 0x80.
var isPaddingStartMask = ((currentByte ^ 0x80) - 1) >> 31;
// Update the index of the first padding byte using bitwise operations.
// If the current byte is 0x80 and still part of the padding, set the index to the current index.
// Otherwise, keep the previous index.
paddingStartIndex ^= (currentIndex ^ paddingStartIndex) & (stillPaddingMask & isPaddingStartMask);
// Update the mask to indicate if the current byte is still part of the padding using bitwise operations.
// If the current byte is 0x00, keep the previous mask.
// Otherwise, set the mask to 0.
stillPaddingMask &= isZeroMask;
}
// Check if the index of the first padding byte is valid.
if (paddingStartIndex < 0)
{
throw new ArgumentException("Pad block corrupted");
}
// Return the number of padding bytes.
return input.Length - paddingStartIndex;
}
}
================================================
FILE: Algorithms/Crypto/Paddings/Pkcs7Padding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// <para>
/// This class implements the PKCS7 padding scheme, which is a standard way of padding data to fit a certain block size.
/// </para>
/// <para>
/// PKCS7 padding adds N bytes of value N to the end of the data, where N is the number of bytes needed to reach the block size.
/// For example, if the block size is 16 bytes, and the data is 11 bytes long, then 5 bytes of value 5 will be added to the
/// end of the data. This way, the padded data will be 16 bytes long and can be encrypted or decrypted by a block cipher algorithm.
/// </para>
/// <para>
/// The padding can be easily removed after decryption by looking at the last byte and subtracting that many bytes from the
/// end of the data.
/// </para>
/// <para>
/// This class supports any block size from 1 to 255 bytes, and can be used with any encryption algorithm that requires
/// padding, such as AES.
/// </para>
/// </summary>
public class Pkcs7Padding : IBlockCipherPadding
{
private readonly int blockSize;
public Pkcs7Padding(int blockSize)
{
if (blockSize is < 1 or > 255)
{
throw new ArgumentOutOfRangeException(nameof(blockSize), $"Invalid block size: {blockSize}");
}
this.blockSize = blockSize;
}
/// <summary>
/// Adds padding to the end of a byte array according to the PKCS#7 standard.
/// </summary>
/// <param name="input">The byte array to be padded.</param>
/// <param name="inputOffset">The offset from which to start padding.</param>
/// <returns>The padding value that was added to each byte.</returns>
/// <exception cref="ArgumentException">
/// If the input array does not have enough space to add <c>blockSize</c> bytes as padding.
/// </exception>
/// <remarks>
/// The padding value is equal to the number of of bytes that are added to the array.
/// For example, if the input array has a length of 16 and the input offset is 10,
/// then 6 bytes with the value 6 will be added to the end of the array.
/// </remarks>
public int AddPadding(byte[] input, int inputOffset)
{
// Calculate how many bytes need to be added to reach the next multiple of block size.
var code = (byte)((blockSize - (input.Length % blockSize)) % blockSize);
// If no padding is needed, add a full block of padding.
if (code == 0)
{
code = (byte)blockSize;
}
if (inputOffset + code > input.Length)
{
throw new ArgumentException("Not enough space in input array for padding");
}
// Add the padding
for (var i = 0; i < code; i++)
{
input[inputOffset + i] = code;
}
return code;
}
/// <summary>
/// Removes the PKCS7 padding from the given input data.
/// </summary>
/// <param name="input">The input data with PKCS7 padding. Must not be null and must have a valid length and padding.</param>
/// <returns>The input data without the padding as a new byte array.</returns>
/// <exception cref="ArgumentException">
/// Thrown if the input data is null, has an invalid length, or has an invalid padding.
/// </exception>
public byte[] RemovePadding(byte[] input)
{
// Check if input length is a multiple of blockSize
if (input.Length % blockSize != 0)
{
throw new ArgumentException("Input length must be a multiple of block size");
}
// Get the padding length from the last byte of input
var paddingLength = input[^1];
// Check if padding length is valid
if (paddingLength < 1 || paddingLength > blockSize)
{
throw new ArgumentException("Invalid padding length");
}
// Check if all padding bytes have the correct value
for (var i = 0; i < paddingLength; i++)
{
if (input[input.Length - 1 - i] != paddingLength)
{
throw new ArgumentException("Invalid padding");
}
}
// Create a new array with the size of input minus the padding length
var output = new byte[input.Length - paddingLength];
// Copy the data without the padding into the output array
Array.Copy(input, output, output.Length);
return output;
}
/// <summary>
/// Gets the number of padding bytes in the given input data according to the PKCS7 padding scheme.
/// </summary>
/// <param name="input">The input data with PKCS7 padding. Must not be null and must have a valid padding.</param>
/// <returns>The number of padding bytes in the input data.</returns>
/// <exception cref="ArgumentException">
/// Thrown if the input data is null or has an invalid padding.
/// </exception>
/// <remarks>
/// This method uses bitwise operations to avoid branching.
/// </remarks>
public int GetPaddingCount(byte[] input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input), "Input cannot be null");
}
// Get the last byte of the input data as the padding value.
var lastByte = input[^1];
var paddingCount = lastByte & 0xFF;
// Calculate the index where the padding starts
var paddingStartIndex = input.Length - paddingCount;
var paddingCheckFailed = 0;
// Check if the padding start index is negative or greater than the input length.
// This is done by using bitwise operations to avoid branching.
// If the padding start index is negative, then its most significant bit will be 1.
// If the padding count is greater than the block size, then its most significant bit will be 1.
// By ORing these two cases, we can get a non-zero value rif either of them is true.
// By shifting this value right by 31 bits, we can get either 0 or -1 as the result.
paddingCheckFailed = (paddingStartIndex | (paddingCount - 1)) >> 31;
for (var i = 0; i < input.Length; i++)
{
// Check if each byte matches the padding value.
// This is done by using bitwise operations to avoid branching.
// If a byte does not match the padding value, then XORing them will give a non-zero value.
// If a byte is before the padding start index, then we want to ignore it.
// This is done by using bitwise operations to create a mask that is either all zeros or all ones.
// If i is less than the padding start index, then subtracting them will give a negative value.
// By shifting this value right by 31 bits, we can get either -1 or 0 as the mask.
// By negating this mask, we can get either 0 or -1 as the mask.
// By ANDing this mask with the XOR result, we can get either 0 or the XOR result as the final result.
// By ORing this final result with the previous padding check result, we can accumulate any non-zero values.
paddingCheckFailed |= (input[i] ^ lastByte) & ~((i - paddingStartIndex) >> 31);
}
// Check if the padding check failed.
if (paddingCheckFailed != 0)
{
throw new ArgumentException("Padding block is corrupted");
}
// Return the number of padding bytes.
return paddingCount;
}
}
================================================
FILE: Algorithms/Crypto/Paddings/TbcPadding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// <para>
/// Trailing-Bit-Complement padding is a padding scheme that is defined in the ISO/IEC 9797-1 standard.
/// </para>
/// <para>
/// It is used for adding data to the end of a message that needs to be encrypted or decrypted by a block cipher.
/// </para>
/// <para>
/// The padding bytes are either 0x00 or 0xFF, depending on the last bit of the original data. For example, if the last
/// bit of the original data is 0, then the padding bytes are 0xFF; if the last bit is 1, then the padding bytes are 0x00.
/// The padding bytes are added at the end of the data block until the desired length is reached.
/// </para>
/// </summary>
public class TbcPadding : IBlockCipherPadding
{
/// <summary>
/// Adds padding to the input array according to the TBC standard.
/// </summary>
/// <param name="input">The input array to be padded.</param>
/// <param name="inputOffset">The offset in the input array where the padding starts.</param>
/// <returns>The number of bytes that were added.</returns>
/// <exception cref="ArgumentException">Thrown when the input array does not have enough space for padding.</exception>
public int AddPadding(byte[] input, int inputOffset)
{
// Calculate the number of bytes to be padded.
var count = input.Length - inputOffset;
byte code;
// Check if the input array has enough space for padding.
if (count < 0)
{
throw new ArgumentException("Not enough space in input array for padding");
}
if (inputOffset > 0)
{
// Get the last bit of the previous byte.
var lastBit = input[inputOffset - 1] & 0x01;
// Set the padding code to 0xFF if the last bit is 0, or 0x00 if the last bit is 1.
code = (byte)(lastBit == 0 ? 0xff : 0x00);
}
else
{
// Get the last bit of the last byte in the input array.
var lastBit = input[^1] & 0x01;
// Set the padding code to 0xff if the last bit is 0, or 0x00 if the last bit is 1.
code = (byte)(lastBit == 0 ? 0xff : 0x00);
}
while (inputOffset < input.Length)
{
// Set each byte to the padding code.
input[inputOffset] = code;
inputOffset++;
}
// Return the number of bytes that were padded.
return count;
}
/// <summary>
/// Removes the padding from a byte array according to the Trailing-Bit-Complement padding algorithm.
/// </summary>
/// <param name="input">The byte array to remove the padding from.</param>
/// <returns>A new byte array without the padding.</returns>
/// <remarks>
/// This method assumes that the input array has padded with either 0x00 or 0xFF bytes, depending on the last bit of
/// the original data. The method works by finding the last byte that does not match the padding code and copying all
/// the bytes up to that point into a new array. If the input array is not padded or has an invalid padding, the
/// method may return incorrect results.
/// </remarks>
public byte[] RemovePadding(byte[] input)
{
if (input.Length == 0)
{
return Array.Empty<byte>();
}
// Get the last byte of the input array.
var lastByte = input[^1];
// Determine the byte code
var code = (byte)((lastByte & 0x01) == 0 ? 0x00 : 0xff);
// Start from the end of the array and move towards the front.
int i;
for (i = input.Length - 1; i >= 0; i--)
{
// If the current byte does not match the padding code, stop.
if (input[i] != code)
{
break;
}
}
// Create a new array of the appropriate length.
var unpadded = new byte[i + 1];
// Copy the unpadded data into the new array.
Array.Copy(input, unpadded, i + 1);
// Return the new array.
return unpadded;
}
/// <summary>
/// Returns the number of padding bytes in a byte array according to the Trailing-Bit-Complement padding algorithm.
/// </summary>
/// <param name="input">The byte array to check for padding.</param>
/// <returns>The number of padding bytes in the input array.</returns>
/// <remarks>
/// This method assumes that the input array has been padded with either 0x00 or 0xFF bytes, depending on the last
/// bit of the original data. The method works by iterating backwards from the end of the array and counting the
/// number of bytes that match the padding code. The method uses bitwise operations to optimize the performance and
/// avoid branching. If the input array is not padded or has an invalid padding, the method may return incorrect
/// results.
/// </remarks>
public int GetPaddingCount(byte[] input)
{
var length = input.Length;
if (length == 0)
{
throw new ArgumentException("No padding found.");
}
// Get the value of the last byte as the padding value
var paddingValue = input[--length] & 0xFF;
var paddingCount = 1; // Start count at 1 for the last byte
var countingMask = -1; // Initialize counting mask
// Check if there is no padding
if (paddingValue != 0 && paddingValue != 0xFF)
{
throw new ArgumentException("No padding found");
}
// Loop backwards through the array
for (var i = length - 1; i >= 0; i--)
{
var currentByte = input[i] & 0xFF;
// Calculate matchMask. If currentByte equals paddingValue, matchMask will be 0, otherwise -1
var matchMask = ((currentByte ^ paddingValue) - 1) >> 31;
// Update countingMask. Once a non-matching byte is found, countingMask will remain -1
countingMask &= matchMask;
// Increment count only if countingMask is 0 (i.e., currentByte matches paddingValue)
paddingCount -= countingMask;
}
return paddingCount;
}
}
================================================
FILE: Algorithms/Crypto/Paddings/X932Padding.cs
================================================
namespace Algorithms.Crypto.Paddings;
/// <summary>
/// <para>
/// X9.32 padding is a padding scheme for symmetric encryption algorithms that is based on the ANSI X9.32 standard.
/// </para>
/// <para>
/// It adds bytes with value equal to 0 up to the end of the plaintext. For example if the plaintext is 13 bytes long
/// and the block size is 16 bytes, then 2 bytes with value 0 will be added as padding. The last byte indicates the
/// number of padding bytes.
/// </para>
/// <para>
/// If random padding mode is selected then random bytes are added before the padding bytes. For example, if the plaintext
/// is 13 bytes long, then 2 random bytes will be added as padding. Again the last byte indicates the number of padding
/// bytes.
/// </para>
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="X932Padding"/> class with the specified padding mode.
/// </remarks>
/// <param name="useRandomPadding">A boolean value that indicates whether to use random bytes as padding or not.</param>
public class X932Padding(bool useRandomPadding) : IBlockCipherPadding
{
private readonly bool useRandomPadding = useRandomPadding;
/// <summary>
/// Adds padding to the input data according to the X9.23 padding scheme.
/// </summary>
/// <param name="inputData">The input data array to be padded.</param>
/// <param name="inputOffset">The offset in the input data array where the padding should start.</param>
/// <returns>The number of padding bytes added.</returns>
/// <exception cref="ArgumentException">
/// Thrown when the input offset is greater than or equal to the input data length.
/// </exception>
public int AddPadding(byte[] inputData, int inputOffset)
{
// Check if the input offset is valid.
if (inputOffset >= inputData.Length)
{
throw new ArgumentException("Not enough space in input array for padding");
}
// Calculate the number of padding bytes needed.
var code = (byte)(inputData.Length - inputOffset);
// Fill the remaining bytes with random or zero bytes
while (inputOffset < inputData.Length - 1)
{
if (!useRandomPadding)
{
// Use zero bytes if random padding is disabled.
inputData[inputOffset] = 0;
}
else
{
// Use random bytes if random padding is enabled.
inputData[inputOffset] = (byte)RandomNumberGenerator.GetInt32(255);
}
inputOffset++;
}
// Set the last byte to the number of padding bytes.
inputData[inputOffset] = code;
// Return the number of padding bytes.
return code;
}
/// <summary>
/// Removes padding from the input data according to the X9.23 padding scheme.
/// </summary>
/// <param name="inputData">The input data array to be unpadded.</param>
/// <returns>The unpadded data array.</returns>
/// <exception cref="ArgumentException">
/// Thrown when the input data is empty or has an invalid padding length.
/// </exception>
public byte[] RemovePadding(byte[] inputData)
{
// Check if the array is empty.
if (inputData.Length == 0)
{
return Array.Empty<byte>();
}
// Get the padding length from the last byte of the input data.
var paddingLength = inputData[^1];
// Check if the padding length is valid.
if (paddingLength < 1 || paddingLength > inputData.Length)
{
throw new ArgumentException("Invalid padding length");
}
// Create a new array for the output data.
var output = new byte[inputData.Length - paddingLength];
// Copy the input data without the padding bytes to the output array.
Array.Copy(inputData, output, output.Length);
// Return the output array.
return output;
}
/// <summary>
/// Gets the number of padding bytes in the input data according to the X9.23 padding scheme.
/// </summary>
/// <param name="input">The input data array to be checked.</param>
/// <returns>The number of padding bytes in the input data.</returns>
/// <exception cref="ArgumentException">
/// Thrown when the input data has a corrupted padding block.
/// </exception>
public int GetPaddingCount(byte[] input)
{
// Get the last byte of the input data, which is the padding length.
var count = input[^1] & 0xFF;
// Calculate the position of the first padding byte.
var position = input.Length - count;
// Check if the position and count are valid using bitwise operations.
// If either of them is negative or zero, the result will be negative.
var failed = (position | (count - 1)) >> 31;
// Throw an exception if the result is negative.
if (failed != 0)
{
throw new ArgumentException("Pad block corrupted");
}
// Return the padding length.
return count;
}
}
================================================
FILE: Algorithms/Crypto/Utils/ByteEncodingUtils.cs
================================================
using System.Buffers.Binary;
using System.Runtime.CompilerServices;
namespace Algorithms.Crypto.Utils;
/// <summary>
/// Provides utility methods for converting between byte arrays and 64-bit unsigned integers using big-endian byte order.
/// </summary>
/// <remarks>
/// The <see cref="ByteEncodingUtils"/> class contains static methods that assist in reading and writing 64-bit unsigned integers
/// from and to byte arrays or spans in big-endian format. These methods are optimized for cryptographic operations where byte
/// encoding is critical for consistency and security.
/// </remarks>
public static class ByteEncodingUtils
{
/// <summary>
/// Converts an 8-byte segment from a byte array (starting at the specified offset) into a 64-bit unsigned integer using big-endian format.
/// </summary>
/// <param name="byteStream">The byte array containing the input data.</param>
/// <param name="offset">The offset within the byte array to start reading from.</param>
/// <returns>A 64-bit unsigned integer representing the big-endian interpretation of the byte array segment.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the specified offset is out of range of the byte array.</exception>
/// <remarks>
/// This method reads 8 bytes from the specified offset within the byte array and converts them to a 64-bit unsigned integer
/// in big-endian format. Big-endian format stores the most significant byte first, followed by the less significant bytes.
/// </remarks>
public static ulong BigEndianToUint64(byte[] byteStream, int offset)
{
return BinaryPrimitives.ReadUInt64BigEndian(byteStream.AsSpan(offset));
}
/// <summary>
/// Converts a read-only span of bytes into a 64-bit unsigned integer using big-endian format.
/// </summary>
/// <param name="byteStream">A read-only span containing the input data.</param>
/// <returns>A 64-bit unsigned integer representing the big-endian interpretation of the span of bytes.</returns>
/// <remarks>
/// This method is optimized for performance using the <see cref="MethodImplOptions.AggressiveInlining"/> attribute to encourage
/// inlining by the compiler. It reads exactly 8 bytes from the input span and converts them into a 64-bit unsigned integer.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong BigEndianToUint64(ReadOnlySpan<byte> byteStream)
{
return BinaryPrimitives.ReadUInt64BigEndian(byteStream);
}
/// <summary>
/// Writes a 64-bit unsigned integer to a span of bytes using big-endian format.
/// </summary>
/// <param name="value">The 64-bit unsigned integer to write.</param>
/// <param name="byteStream">The span of bytes where the value will be written.</param>
/// <remarks>
/// This method writes the 64-bit unsigned integer into the span in big-endian format, where the most significant byte is written first.
/// The method is optimized using the <see cref="MethodImplOptions.AggressiveInlining"/> attribute to improve performance in scenarios
/// where frequent byte-to-integer conversions are required, such as cryptographic algorithms.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void UInt64ToBigEndian(ulong value, Span<byte> byteStream)
{
BinaryPrimitives.WriteUInt64BigEndian(byteStream, value);
}
}
================================================
FILE: Algorithms/Crypto/Utils/LongUtils.cs
================================================
namespace Algorithms.Crypto.Utils;
/// <summary>
/// Provides utility methods for performing bitwise rotation operations (left and right) on 64-bit integers.
/// </summary>
/// <remarks>
/// The <see cref="LongUtils"/> class contains methods to rotate 64-bit signed and unsigned integers to the left or right.
/// These rotations are crucial in various cryptographic algorithms, where circular shifts are used to mix data and
/// introduce non-linearity. The methods use the underlying <see cref="System.Numerics.BitOperations"/> for efficient,
/// hardware-supported bitwise rotations.
/// </remarks>
public static class LongUtils
{
/// <summary>
/// Rotates the bits of a 64-bit signed integer to the left by a specified number of bits.
/// </summary>
/// <param name="i">The 64-bit signed integer to rotate.</param>
/// <param name="distance">The number of bits to rotate the integer to the left.</param>
/// <returns>The result of rotating the integer to the left by the specified distance.</returns>
/// <remarks>
/// This method uses the underlying <see cref="BitOperations.RotateLeft(ulong, int)"/> method, converting the signed integer to an unsigned integer
/// for the rotation, then casting it back to a signed integer. The rotation is performed in a circular manner, where bits shifted
/// out of the most significant bit are reintroduced into the least significant bit.
/// </remarks>
public static long RotateLeft(long i, int distance)
{
return (long)BitOperations.RotateLeft((ulong)i, distance);
}
/// <summary>
/// Rotates the bits of a 64-bit unsigned integer to the left by a specified number of bits.
/// </summary>
/// <param name="i">The 64-bit unsigned integer to rotate.</param>
/// <param name="distance">The number of bits to rotate the integer to the left.</param>
/// <returns>The result of rotating the integer to the left by the specified distance.</returns>
/// <remarks>
/// The rotation is performed circularly, meaning bits shifted out of the most significant bit are reintroduced into
/// the least significant bit. This method is optimized for performance using hardware-supported operations through
/// <see cref="BitOperations.RotateLeft(ulong, int)"/>.
/// </remarks>
public static ulong RotateLeft(ulong i, int distance)
{
return BitOperations.RotateLeft(i, distance);
}
/// <summary>
/// Rotates the bits of a 64-bit signed integer to the right by a specified number of bits.
/// </summary>
/// <param name="i">The 64-bit signed integer to rotate.</param>
/// <param name="distance">The number of bits to rotate the integer to the right.</param>
/// <returns>The result of rotating the integer to the right by the specified distance.</returns>
/// <remarks>
/// Similar to the left rotation, this method uses <see cref="BitOperations.RotateRight(ulong, int)"/> to perform the rotation.
/// The signed integer is cast to an unsigned integer for the operation and cast back to a signed integer afterward.
/// The rotation wraps bits shifted out of the least significant bit into the most significant bit.
/// </remarks>
public static long RotateRight(long i, int distance)
{
return (long)BitOperations.RotateRight((ulong)i, distance);
}
/// <summary>
/// Rotates the bits of a 64-bit unsigned integer to the right by a specified number of bits.
/// </summary>
/// <param name="i">The 64-bit unsigned integer to rotate.</param>
/// <param name="distance">The number of bits to rotate the integer to the right.</param>
/// <returns>The result of rotating the integer to the right by the specified distance.</returns>
/// <remarks>
/// This method performs the rotation circularly, where bits shifted out of the least significant bit are reintroduced
/// into the most significant bit. The operation uses hardware-supported instructions via <see cref="BitOperations.RotateRight(ulong, int)"/>.
/// </remarks>
public static ulong RotateRight(ulong i, int distance)
{
return BitOperations.RotateRight(i, distance);
}
}
================================================
FILE: Algorithms/Crypto/Utils/ValidationUtils.cs
================================================
using Algorithms.Crypto.Exceptions;
namespace Algorithms.Crypto.Utils;
/// <summary>
/// Provides utility methods for validating the lengths of input and output data in cryptographic operations.
/// </summary>
/// <remarks>
/// The <see cref="ValidationUtils"/> class contains static methods to validate the length and position of data buffers used in
/// cryptographic operations. These methods throw appropriate exceptions such as <see cref="DataLengthException"/> or
/// <see cref="OutputLengthException"/> when the validation fails. These are critical for ensuring that cryptographic computations
/// do not run into buffer overflows, underflows, or incorrect input/output buffer lengths.
/// </remarks>
public static class ValidationUtils
{
/// <summary>
/// Validates that the specified offset and length fit within the bounds of the given buffer.
/// </summary>
/// <param name="buffer">The byte array to validate.</param>
/// <param name="offset">The offset into the byte array where validation should start.</param>
/// <param name="length">The number of bytes to validate from the specified offset.</param>
/// <param name="message">The message that describes the error if the exception is thrown.</param>
/// <exception cref="DataLengthException">Thrown if the offset and length exceed the bounds of the buffer.</exception>
/// <remarks>
/// This method ensures that the specified offset and length fit within the bounds of the buffer. If the offset and length
/// go out of bounds, a <see cref="DataLengthException"/> is thrown with the provided error message.
/// </remarks>
public static void CheckDataLength(byte[] buffer, int offset, int length, string message)
{
if (offset > (buffer.Length - length))
{
throw new DataLengthException(message);
}
}
/// <summary>
/// Throws an <see cref="OutputLengthException"/> if the specified condition is true.
/// </summary>
/// <param name="condition">A boolean condition indicating whether the exception should be thrown.</param>
/// <param name="message">The message that describes the error if the exception is thrown.</param>
/// <exception cref="OutputLengthException">Thrown if the condition is true.</exception>
/// <remarks>
/// This method performs a simple conditional check for output length validation. If the condition is true, an
/// <see cref="OutputLengthException"/> is thrown with the provided message.
/// </remarks>
public static void CheckOutputLength(bool condition, string message)
{
if (condition)
{
throw new OutputLengthException(message);
}
}
/// <summary>
/// Validates that the specified offset and length fit within the bounds of the output buffer.
/// </summary>
/// <param name="buffer">The byte array to validate.</param>
/// <param name="offset">The offset into the byte array where validation should start.</param>
/// <param name="length">The number of bytes to validate from the specified offset.</param>
/// <param name="message">The message that describes the error if the exception is thrown.</param>
/// <exception cref="OutputLengthException">Thrown if the offset and length exceed the bounds of the buffer.</exception>
/// <remarks>
/// This method ensures that the specified offset and length do not exceed the bounds of the output buffer. If the
/// validation fails, an <see cref="OutputLengthException"/> is thrown with the provided message.
/// </remarks>
public static void CheckOutputLength(byte[] buffer, int offset, int length, string message)
{
if (offset > (buffer.Length - length))
{
throw new OutputLengthException(message);
}
}
/// <summary>
/// Validates that the length of the output span does not exceed the specified length.
/// </summary>
/// <typeparam name="T">The type of elements in the span.</typeparam>
/// <param name="output">The span to validate.</param>
/// <param name="length">The maximum allowed length for the output span.</param>
/// <param name="message">The message that describes the error if the exception is thrown.</param>
/// <exception cref="OutputLengthException">Thrown if the length of the output span exceeds the specified length.</exception>
/// <remarks>
/// This method checks that the span does not exceed the specified length. If the span length exceeds the allowed length,
/// an <see cref="OutputLengthException"/> is thrown with the provided error message.
/// </remarks>
public static void CheckOutputLength<T>(Span<T> output, int length, string message)
{
if (output.Length > length)
{
throw new OutputLengthException(message);
}
}
}
================================================
FILE: Algorithms/DataCompression/BurrowsWheelerTransform.cs
================================================
namespace Algorithms.DataCompression;
/// <summary>
/// The Burrows–Wheeler transform (BWT) rearranges a character string into runs of similar characters.
/// This is useful for compression, since it tends to be easy to compress a string that has runs of repeated
/// characters.
/// See <a href="https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform">here</a> for more info.
/// </summary>
public class BurrowsWheelerTransform
{
/// <summary>
/// Encodes the input string using BWT and returns encoded string and the index of original string in the sorted
/// rotation matrix.
/// </summary>
/// <param name="s">Input string.</param>
public (string Encoded, int Index) Encode(string s)
{
if (s.Length == 0)
{
return (string.Empty, 0);
}
var rotations = GetRotations(s);
Array.Sort(rotations, StringComparer.Ordinal);
var lastColumn = rotations
.Select(x => x[^1])
.ToArray();
var encoded = new string(lastColumn);
return (encoded, Array.IndexOf(rotations, s));
}
/// <summary>
/// Decodes the input string and returns original string.
/// </summary>
/// <param name="s">Encoded string.</param>
/// <param name="index">Index of original string in the sorted rotation matrix.</param>
public string Decode(string s, int index)
{
if (s.Length == 0)
{
return string.Empty;
}
var rotations = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
for (var j = 0; j < s.Length; j++)
{
rotations[j] = s[j] + rotations[j];
}
Array.Sort(rotations, StringComparer.Ordinal);
}
return rotations[index];
}
private string[] GetRotations(string s)
{
var result = new string[s.Length];
for (var i = 0; i < s.Length; i++)
{
result[i] = s.Substring(i) + s.Substring(0, i);
}
return result;
}
}
================================================
FILE: Algorithms/DataCompression/HuffmanCompressor.cs
================================================
using Algorithms.Sorters.Comparison;
namespace Algorithms.DataCompression;
/// <summary>
/// Greedy lossless compression algorithm.
/// </summary>
public class HuffmanCompressor(IComparisonSorter<HuffmanCompressor.ListNode> sorter, Translator translator)
{
// TODO: Use partial sorter
private readonly IComparisonSorter<ListNode> sorter = sorter;
private readonly Translator translator = translator;
/// <summary>
/// Given an input string, returns a new compressed string
/// using huffman encoding.
/// </summary>
/// <param name="uncompressedText">Text message to compress.</param>
/// <returns>Compressed string and keys to decompress it.</returns>
public (string CompressedText, Dictionary<string, string> DecompressionKeys) Compress(string uncompressedText)
{
if (string.IsNullOrEmpty(uncompressedText))
{
return (string.Empty, []);
}
if (uncompressedText.Distinct().Count() == 1)
{
var dict = new Dictionary<string, string>
{
["1"] = uncompressedText[0].ToString(),
};
return (new string('1', uncompressedText.Length), dict);
}
var nodes = GetListNodesFromText(uncompressedText);
var tree = GenerateHuffmanTree(nodes);
var (compressionKeys, decompressionKeys) = GetKeys(tree);
return (translator.Translate(uncompressedText, compressionKeys), decompressionKeys);
}
/// <summary>
/// Finds frequency for each character in the text.
/// </summary>
/// <returns>Symbol-frequency array.</returns>
private static ListNode[] GetListNodesFromText(string text)
{
var occurenceCounts = new Dictionary<char, int>();
foreach (var ch in text)
{
if (!occurenceCounts.ContainsKey(ch))
{
occurenceCounts.Add(ch, 0);
}
occurenceCounts[ch]++;
}
return occurenceCounts.Select(kvp => new ListNode(kvp.Key, 1d * kvp.Value / text.Length)).ToArray();
}
private (Dictionary<string, string> CompressionKeys, Dictionary<string, string> DecompressionKeys) GetKeys(
ListNode tree)
{
var compressionKeys = new Dictionary<string, string>();
var decompressionKeys = new Dictionary<string, string>();
if (tree.HasData)
{
compressionKeys.Add(tree.Data.ToString(), string.Empty);
decompressionKeys.Add(string.Empty, tree.Data.ToString());
return (compressionKeys, decompressionKeys);
}
if (tree.LeftChild is not null)
{
var (lsck, lsdk) = GetKeys(tree.LeftChild);
compressionKeys.AddMany(lsck.Select(kvp => (kvp.Key, "0" + kvp.Value)));
decompressionKeys.AddMany(lsdk.Select(kvp => ("0" + kvp.Key, kvp.Value)));
}
if (tree.RightChild is not null)
{
var (rsck, rsdk) = GetKeys(tree.RightChild);
compressionKeys.AddMany(rsck.Select(kvp => (kvp.Key, "1" + kvp.Value)));
decompressionKeys.AddMany(rsdk.Select(kvp => ("1" + kvp.Key, kvp.Value)));
return (compressionKeys, decompressionKeys);
}
return (compressionKeys, decompressionKeys);
}
private ListNode GenerateHuffmanTree(ListNode[] nodes)
{
var comparer = new ListNodeComparer();
while (nodes.Length > 1)
{
sorter.Sort(nodes, comparer);
var left = nodes[0];
var right = nodes[1];
var newNodes = new ListNode[nodes.Length - 1];
Array.Copy(nodes, 2, newNodes, 1, nodes.Length - 2);
newNodes[0] = new ListNode(left, right);
nodes = newNodes;
}
return nodes[0];
}
/// <summary>
/// Represents tree structure for the algorithm.
/// </summary>
public class ListNode
{
public ListNode(char data, double frequency)
{
HasData = true;
Data = data;
Frequency = frequency;
}
public ListNode(ListNode leftChild, ListNode rightChild)
{
LeftChild = leftChild;
RightChild = rightChild;
Frequency = leftChild.Frequency + rightChild.Frequency;
}
public char Data { get; }
public bool HasData { get; }
public double Frequency { get; }
public ListNode? RightChild { get; }
public ListNode? LeftChild { get; }
}
public class ListNodeComparer : IComparer<ListNode>
{
public int Compare(ListNode? x, ListNode? y)
{
if (x is null || y is null)
{
return 0;
}
return x.Frequency.CompareTo(y.Frequency);
}
}
}
================================================
FILE: Algorithms/DataCompression/ShannonFanoCompressor.cs
================================================
using Algorithms.Knapsack;
namespace Algorithms.DataCompression;
/// <summary>
/// Greedy lossless compression algorithm.
/// </summary>
public class ShannonFanoCompressor(
IHeuristicKnapsackSolver<(char Symbol, double Frequency)> splitter,
Translator translator)
{
private readonly IHeuristicKnapsackSolver<(char Symbol, double Frequency)> splitter = splitter;
private readonly Translator translator = translator;
/// <summary>
/// Given an input string, returns a new compressed string
/// using Shannon-Fano encoding.
/// </summary>
/// <param name="uncompressedText">Text message to compress.</param>
/// <returns>Compressed string and keys to decompress it.</returns>
public (string CompressedText, Dictionary<string, string> DecompressionKeys) Compress(string uncompressedText)
{
if (string.IsNullOrEmpty(uncompressedText))
{
return (string.Empty, new Dictionary<string, string>());
}
if (uncompressedText.Distinct().Count() == 1)
{
var dict = new Dictionary<string, string>
{
{ "1", uncompressedText[0].ToString() },
};
return (new string('1', uncompressedText.Length), dict);
}
var node = GetListNodeFromText(uncompressedText);
var tree = GenerateShannonFanoTree(node);
var (compressionKeys, decompressionKeys) = GetKeys(tree);
return (translator.Translate(uncompressedText, compressionKeys), decompressionKeys);
}
private (Dictionary<string, string> CompressionKeys, Dictionary<string, string> DecompressionKeys) GetKeys(
ListNode tree)
{
var compressionKeys = new Dictionary<string, string>();
var decompressionKeys = new Dictionary<string, string>();
if (tree.Data.Length == 1)
{
compressionKeys.Add(tree.Data[0].Symbol.ToString(), string.Empty);
decompressionKeys.Add(string.Empty, tree.Data[0].Symbol.ToString());
return (compressionKeys, decompressionKeys);
}
if (tree.LeftChild is not null)
{
var (lsck, lsdk) = GetKeys(tree.LeftChild);
compressionKeys.AddMany(lsck.Select(kvp => (kvp.Key, "0" + kvp.Value)));
decompressionKeys.AddMany(lsdk.Select(kvp => ("0" + kvp.Key, kvp.Value)));
}
if (tree.RightChild is not null)
{
var (rsck, rsdk) = GetKeys(tree.RightChild);
compressionKeys.AddMany(rsck.Select(kvp => (kvp.Key, "1" + kvp.Value)));
decompressionKeys.AddMany(rsdk.Select(kvp => ("1" + kvp.Key, kvp.Value)));
}
return (compressionKeys, decompressionKeys);
}
private ListNode GenerateShannonFanoTree(ListNode node)
{
if (node.Data.Length == 1)
{
return node;
}
var left = splitter.Solve(node.Data, 0.5 * node.Data.Sum(x => x.Frequency), x => x.Frequency, _ => 1);
var right = node.Data.Except(left).ToArray();
node.LeftChild = GenerateShannonFanoTree(new ListNode(left));
node.RightChild = GenerateShannonFanoTree(new ListNode(right));
return node;
}
/// <summary>
/// Finds frequency for each character in the text.
/// </summary>
/// <returns>Symbol-frequency array.</returns>
private ListNode GetListNodeFromText(string text)
{
var occurenceCounts = new Dictionary<char, double>();
for (var i = 0; i < text.Length; i++)
{
var ch = text[i];
if (!occurenceCounts.ContainsKey(ch))
{
occurenceCounts.Add(ch, 0);
}
occurenceCounts[ch]++;
}
return new ListNode(occurenceCounts.Select(kvp => (kvp.Key, 1d * kvp.Value / text.Length)).ToArray());
}
/// <summary>
/// Represents tree structure for the algorithm.
/// </summary>
public class ListNode((char Symbol, double Frequency)[] data)
{
public (char Symbol, double Frequency)[] Data { get; } = data;
public ListNode? RightChild { get; set; }
public ListNode? LeftChild { get; set; }
}
}
================================================
FILE: Algorithms/DataCompression/Translator.cs
================================================
namespace Algorithms.DataCompression;
/// <summary>
/// Provides method for text conversion by key mapping.
/// </summary>
public class Translator
{
/// <summary>
/// Converts the input text according to the translation keys.
/// </summary>
/// <param name="text">Input text.</param>
/// <param name="translationKeys">Translation keys used for text matching.</param>
/// <returns>Converted text according to the translation keys.</returns>
public string Translate(string text, Dictionary<string, string> translationKeys)
{
var sb = new StringBuilder();
var start = 0;
for (var i = 0; i < text.Length; i++)
{
var key = text.Substring(start, i - start + 1);
if (translationKeys.ContainsKey(key))
{
_ = sb.Append(translationKeys[key]);
start = i + 1;
}
}
return sb.ToString();
}
}
================================================
FILE: Algorithms/Encoders/AutokeyEncorder.cs
================================================
namespace Algorithms.Encoders
{
/// <summary>
/// Class for AutoKey encoding strings.
/// </summary>
public class AutokeyEncorder
{
/// <summary>
/// Autokey Cipher is a type of polyalphabetic cipher.
/// This works by choosing a key (a word or short phrase),
/// then you append the plaintext to itself to form a longer key.
/// </summary>
/// <param name="plainText">The string to be appended to the key.</param>
/// <param name="keyword">The string to be appended to the plaintext.</param>
/// <returns>The Autokey encoded string (All Uppercase).</returns>
public string Encode(string plainText, string keyword)
{
plainText = Regex.Replace(plainText.ToUpper(CultureInfo.InvariantCulture), "[^A-Z]", string.Empty);
keyword = keyword.ToUpper(CultureInfo.InvariantCulture);
keyword += plainText;
StringBuilder cipherText = new StringBuilder();
for (int i = 0; i < plainText.Length; i++)
{
char plainCharacter = plainText[i];
char keyCharacter = keyword[i];
int encryptedCharacter = (plainCharacter - 'A' + keyCharacter - 'A') % 26 + 'A';
cipherText.Append((char)encryptedCharacter);
}
return cipherText.ToString();
}
/// <summary>
/// Removed the key from the encoded string.
/// </summary>
/// <param name="cipherText">The encoded string.</param>
/// <param name="keyword">The key to be removed from the encoded string.</param>
/// <returns>The plaintext (All Uppercase).</returns>
public string Decode(string cipherText, string keyword)
{
cipherText = Regex.Replace(cipherText.ToUpper(CultureInfo.InvariantCulture), "[^A-Z]", string.Empty);
keyword = keyword.ToUpper(CultureInfo.InvariantCulture);
StringBuilder plainText = new StringBuilder();
StringBuilder extendedKeyword = new StringBuilder(keyword);
for (int i = 0; i < cipherText.Length; i++)
{
char cipherCharacter = cipherText[i];
char keywordCharacter = extendedKeyword[i];
int decryptedCharacter = (cipherCharacter - 'A' - (keywordCharacter - 'A') + 26) % 26 + 'A';
plainText.Append((char)decryptedCharacter);
extendedKeyword.Append((char)decryptedCharacter);
}
return plainText.ToString();
}
}
}
================================================
FILE: Algorithms/Encoders/BlowfishEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// <para>
/// The Blowfish algorithm is a symmetric-key block cipher, which means it uses the same secret key to encrypt and
/// decrypt data. It was designed by Bruce Schneier in 1993.
/// </para>
/// <para>
/// The blowfish algorithm works on 64-bit blocks of data, which are divided into two 32-bit halves: left and right.
/// It uses a variable-length key, from 32 bits to 448 bits, to generate 18 subkeys and four S-boxes, which are arrays
/// of 256 32-bit words. The subkeys and the S-boxes are key-dependent, meaning that they change according to the secret key.
/// </para>
/// <para>
/// The blowfish algorithm performs 16 rounds of encryption or decryption on each block of data, using a Feistel network
/// structure. In each round, the left half is XORed with a subkey, then passed through a function F that applies four
/// S-box lookups and two XOR operations. The output of F is then XORed with the right half. The left and right halves
/// are swapped at the end of each round, except for the last one. The final output is XORed with two more subkeys to
/// produce the encrypted or decrypted block.
/// </para>
/// <see href="https://en.wikipedia.org/wiki/Blowfish_%28cipher%29">Blowfish on Wikipedia</see>.
/// </summary>
public class BlowfishEncoder
{
// Initialize modVal to 2^32
private const ulong ModVal = 4294967296L;
// Initialize the substitution boxes
private readonly string[][] s =
[
[
"d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed", "6a267e96", "ba7c9045", "f12c7f99",
"24a19947", "b3916cf7", "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3", "f4933d7e",
"0d95748f", "728eb658", "718bcd58", "82154aee", "7b54a41d", "c25a59b5", "9c30d539", "2af26013",
"c5d1b023", "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e", "6c9e0e8b", "b01e8a3e",
"d71577c1", "bd314b27", "78af2fda", "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440",
"55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af", "7c72e993", "b3ee1411", "636fbc2a",
"2ba9c55d", "741831f6", "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381", "28958677",
"3b8f4898", "6b4bb9af", "c4bfe81b", "66282193", "61d809cc", "fb21a991", "487cac60", "5dec8032",
"ef845d5d", "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5", "0f6d6ff3", "83f44239",
"2e0b4482", "a4842004", "69c8f04a", "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0",
"6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c", "137a3be4", "ba3bf050", "7efb2a98",
"a1f1651d", "39af0176", "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3", "3b8b5ebe",
"e06f75d8", "85c12073", "401a449f", "56c16aa6", "4ed3aa62", "363f7706", "1bfedf72", "429b023d",
"37d0d724", "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b", "25d479d8", "f6e8def7",
"e3fe501a", "b6794c3b", "976ce0bd", "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463",
"68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f", "9b30952c", "cc814544", "af5ebd09",
"bee3d004", "de334afd", "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39", "b9d3fbdb",
"5579c0bd", "1a60320a", "d6a100c6", "402c7279", "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8",
"3c7516df", "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760", "53317b48", "3e00df82",
"9e5c57bb", "ca6f8ca0", "1a87562e", "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573",
"695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98", "fd2183b8", "4afcb56c", "2dd1d35b",
"9a53e479", "b6f84565", "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341", "cee4c6e8",
"ef20cada", "36774c01", "d07e9efe", "2bf11fb4", "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0",
"d08ed1d0", "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64", "8888b812", "900df01c",
"4fad5ea0", "688fc31c", "d1cff191", "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1",
"e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0", "fd13e0b7", "7cc43b81", "d2ada8d9",
"165fa266", "80957705", "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5", "fb9d35cf",
"ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49", "00250e2d", "2071b35e", "226800bb", "57b8e0af",
"2464369b", "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f", "207d5ba2", "02e5b9c5",
"83260376", "6295cfa9", "11c81968", "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915",
"d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5", "571be91f", "f296ec6b", "2a0dd915",
"b6636521", "e7b9f9b6", "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799", "6e85076a",
],
[
"4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0", "49a7df7d", "9cee60b8", "8fedb266",
"ecaa8c71", "699a17ff", "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340", "e4183a3e",
"3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6", "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1",
"4cdd2086", "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9", "3c971814", "6b6a70a1",
"687f3584", "52a0e286", "b79c5305", "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8",
"b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a", "3cb574b2", "25837a58", "dc0921bd",
"d19113f9", "7ca92ff6", "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634", "9af3dda7",
"a9446146", "0fd0030e", "ecc8c73e", "a4751e41", "e238cd99", "3bea0e2f", "3280bba1", "183eb331",
"4e548b38", "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79", "5679b072", "bcaf89af",
"de9a771f", "d9930810", "b38bae12", "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87",
"7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a", "db851dfa", "63094366", "c464c3d2",
"ef1c1847", "3215d908", "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002", "133ae4dd",
"71dff89e", "10314e55", "81ac77d6", "5f11199b", "043556f1", "d7a3c76b", "3c11183b", "5924a509",
"f28fe6ed", "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1", "860e5e0a", "5a3e2ab3",
"771fe71c", "4e3d06fa", "2965dcb9", "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a",
"c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7", "361d2b3d", "1939260f", "19c27960",
"5223a708", "f71312b6", "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1", "018cff28",
"c332ddef", "be6c5aa5", "65582185", "68ab9802", "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84",
"1521b628", "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96", "0334fe1e", "aa0363cf",
"b5735c90", "4c70a239", "d59e9e0b", "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e",
"648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32", "3c2ab4b3", "319ee9d5", "c021b8f7",
"9b540b19", "875fa099", "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f", "16681281",
"0e358829", "c7e61fd6", "96dedfa1", "7858ba99", "57f584a5", "1b227263", "9b83c3ff", "1ac24696",
"cdb30aeb", "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea", "fe28ed61", "ee7c3c73",
"5d4a14d9", "e864b7e3", "42105d14", "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0",
"c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e", "86854dc7", "e44b476a", "3d816250",
"cf62a1f2", "5b8d2646", "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b", "5692b285",
"095bbf00", "ad19489d", "1462b174", "23820e00", "58428d2a", "0c55f5ea", "1dadf43e", "233f7061",
"3372f092", "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460", "4085f2a7", "ce77326e",
"a6078084", "19f8509e", "e8efd855", "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc",
"9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3", "105588cd", "675fda79", "e3674340",
"c5c43465", "713e38d8", "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b", "db83adf7",
],
[
"e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7", "7602d4f7", "bcf46b2e", "d4a20068",
"d4082471", "3320f46a", "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74", "bf8b8840",
"4d95fc1d", "96b591af", "70f4ddd3", "66a02f45", "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504",
"96eb27b3", "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4", "0a2c86da", "e9b66dfb",
"68dc1462", "d7486900", "680ec0a4", "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6",
"aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35", "d9f385b9", "ee39d7ab", "3b124e8b",
"1dc9faf7", "4b6d1856", "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7", "ca7820fb",
"fb0af54e", "d8feb397", "454056ac", "ba489527", "55533a3a", "20838d87", "fe6ba9b7", "d096954b",
"55a867bc", "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9", "5ef47e1c", "9029317c",
"fdf8e802", "04272f70", "80bb155c", "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc",
"07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb", "d59bc0d1", "f2bcc18f", "41113564",
"257b7834", "602a9c60", "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1", "cad18115",
"6b2395e0", "333e92e1", "3b240b62", "eebeb922", "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728",
"d0127845", "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa", "c39dfd27", "f33e8d1e",
"0a476341", "992eff74", "3a6f6eab", "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d",
"c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7", "cc00ffa3", "b5390f92", "690fed0b",
"667b9ffb", "cedb7d9c", "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf", "763bd6eb",
"37392eb3", "cc115979", "8026e297", "f42e312d", "6842ada7", "c66a2b3b", "12754ccc", "782ef11c",
"6a124237", "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa", "3d25bdd8", "e2e1c3c9",
"44421659", "0a121386", "d90cec6e", "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe",
"9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346", "f6381fb0", "7745ae04", "d736fccc",
"83426b33", "f01eab71", "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299", "bf582e61",
"4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2", "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9",
"7aeb2661", "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770", "8cd55591", "c902de4c",
"b90bace1", "bb8205d0", "11a86248", "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633",
"e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d", "0ba5a4df", "a186f20f", "2868f169",
"dcb7da83", "573906fe", "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4", "0de6d027",
"9af88c27", "773f8641", "c3604c06", "61a806b5", "f0177a28", "c0f586e0", "006058aa", "30dc7d62",
"11e69ed7", "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de", "ebfc7da1", "ce591d76",
"6f05e409", "4b7c0188", "39720a3d", "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc",
"ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e", "b161e6f8", "a28514d9", "6c51133c",
"6fd5c7e7", "56e14ec4", "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e", "406000e0",
],
[
"3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e", "4fa33742", "d3822740", "99bc9bbe",
"d5118e9d", "bf0f7315", "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be", "6a366eb4",
"5748ab2f", "bc946e79", "c6a376d2", "6549c2c8", "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6",
"2939bbdb", "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a", "63ef8ce2", "9a86ee22",
"c089c2b8", "43242ef6", "a51e03aa", "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6",
"2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3", "f752f7da", "3f046f69", "77fa0a59",
"80e4a915", "87b08601", "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9", "022b8b51",
"96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28", "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c",
"e029ac71", "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc", "f8d56629", "79132e28",
"785f0191", "ed756055", "f7960e44", "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd",
"c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b", "1e6321f5", "f59c66fb", "26dcf319",
"7533d928", "b155fdf5", "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167", "ccad925f",
"4de81751", "3830dc8e", "379d5862", "9320f991", "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32",
"a8b6e37e", "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224", "69852dfd", "09072166",
"b39a460a", "6445c0dd", "586cdecf", "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb",
"dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8", "fa6484bb", "8d6612ae", "bf3c6f47",
"d29be463", "542f5d9e", "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671", "af537d5d",
"4040cb08", "4eb4e2cc", "34d2466a", "0115af84", "e1b00428", "95983a1d", "06b89fb4", "ce6ea048",
"6f3f3b82", "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc", "bb3a792b", "344525bd",
"a08839e1", "51ce794b", "2f32c9b7", "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7",
"1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a", "c6913667", "8df9317c", "e0b12b4f",
"f79e59b7", "43f5bb3a", "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71", "9b941525",
"fae59361", "ceb69ceb", "c2a86459", "12baa8d1", "b6c1075e", "e3056a0c", "10d25065", "cb03a442",
"e0ec6e0e", "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df", "d3a0342b", "8971f21e",
"1b0a7441", "4ba3348c", "c5be7120", "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d",
"e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166", "fd2c1d05", "848fd2c5", "f6fb2299",
"f523f357", "a6327623", "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697", "88d273cc",
"de966292", "81b949d0", "4c50901b", "71c65614", "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a",
"c9aa53fd", "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222", "b6cbcf7c", "cd769c2b",
"53113ec0", "1640e3d3", "38abbd60", "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060",
"85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c", "02fb8a8c", "01c36ae4", "d6ebe1f9",
"90d4f869", "a65cdea0", "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3", "3ac372e6",
],
];
// Initialize the P-array sub-keys
private readonly string[] p =
[
"243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822", "299f31d0", "082efa98", "ec4e6c89", "452821e6",
"38d01377", "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5", "b5470917", "9216d5d9", "8979fb1b",
];
/// <summary>
/// Generate a key for the encryption algorithm based on the given string parameter.
/// </summary>
/// <param name="key">The key to generate the subkey from.</param>
public void GenerateKey(string key)
{
var j = 0;
for (var i = 0; i < p.Length; i++)
{
// Perform the key expansion
var subKey = key.Substring(j % key.Length, 8);
p[i] = Xor(p[i], subKey);
j += 8;
}
}
/// <summary>
/// Encrypts a string using the blowfish algorithm.
/// </summary>
/// <param name="plainText">The string to be encrypted, represented as a hexadecimal string.</param>
/// <returns>The encrypted string, represented as a hexadecimal string.</returns>
public string Encrypt(string plainText)
{
// Perform the 16 rounds of the blowfish algorithm on the plainText.
for (var i = 0; i < 16; i++)
{
plainText = Round(i, plainText);
}
// Swap the left and right parts of the plainText.
var left = plainText.Substring(8, 8);
var right = plainText[..8];
// XOR the left half with the last subkey of the P-array.
left = Xor(left, p[17]);
// XOR the right half with the second to last subkey from the P-array.
right = Xor(right, p[16]);
// Return the encrypted string as a concatenated string.
return left + right;
}
/// <summary>
/// Decrypts a string using the blowfish algorithm.
/// </summary>
/// <param name="cipherText">The string to be decrypted, represented as a hexadecimal string.</param>
/// <returns>The decrypted string, represented as a hexadecimal string.</returns>
public string Decrypt(string cipherText)
{
// Perform 16 rounds of the blowfish algorithm on the cipherText in reverse order.
for (var i = 17; i > 1; i--)
{
cipherText = Round(i, cipherText);
}
// Swap the left and right halves of the cipherText.
var left = cipherText.Substring(8, 8);
var right = cipherText.Substring(0, 8);
// XOR the left half with the first subkey from the P-array.
left = Xor(left, p[0]);
// XOR the right half with the second subkey from the P-array.
right = Xor(right, p[1]);
// Return the decrypted string as a concatenated string.
return left + right;
}
/// <summary>
/// Converts a hexadecimal string to a binary string.
/// </summary>
/// <param name="hex">The hexadecimal string to convert.</param>
/// <returns>A multiple of 4 binary string representing the hexadecimal input.</returns>
private string HexadecimalToBinary(string hex)
{
return hex.Select(t =>
// Convert each character to an integer using base 16
Convert.ToString(Convert.ToInt32(t.ToString(), 16), 2))
// Pad each binary string with leading zeros to make it 4 bits long
.Select(fourBitBinary => fourBitBinary.PadLeft(4, '0'))
// Concatenate all the binary strings into one
.Aggregate(string.Empty, (current, fourBitBinary) => current + fourBitBinary);
}
/// <summary>
/// Converts a binary string to a hexadecimal string.
/// </summary>
/// <param name="binaryInput">The multiple of 4 binary string to convert.</param>
/// <returns>A hexadecimal string representing the binary input.</returns>
private string BinaryToHexadecimal(string binaryInput)
{
return string.Concat(
Enumerable.Range(0, binaryInput.Length / 4)
// Select each group of 4 bits
.Select(index => binaryInput.Substring(index * 4, 4))
// Convert each group to an integer using base 2
.Select(fourBitBinary => Convert.ToInt32(fourBitBinary, 2)
// Convert each integer to a hexadecimal character using base 16
.ToString("x")));
}
/// <summary>
/// Performs a bitwise XOR operation on two hexadecimal strings and returns the result.
/// </summary>
/// <param name="left">The first hexadecimal string to XOR.</param>
/// <param name="right">The second hexadecimal string to XOR.</param>
/// <returns>A hexadecimal string representing the XOR of the inputs.</returns>
private string Xor(string left, string right)
{
// Convert the hexadecimal strings to binary strings using a helper method
left = HexadecimalToBinary(left);
right = HexadecimalToBinary(right);
var xor = new StringBuilder();
// Loop through each bit in the binary strings
for (var i = 0; i < left.Length; i++)
{
// Perform a bitwise XOR operation on the corresponding bits and append the result to xor
xor.Append((char)(((left[i] - '0') ^ (right[i] - '0')) + '0'));
}
// Convert the binary string to a hexadecimal string
var result = BinaryToHexadecimal(xor.ToString());
return result;
}
/// <summary>
/// Adds two hexadecimal strings and returns the result modulo _modVal.
/// </summary>
/// <param name="left">The first hexadecimal string to add.</param>
/// <param name="right">The second hexadecimal string to add.</param>
/// <returns>A hexadecimal string representing the sum of the inputs modulo _modVal.</returns>
private string AddAndMod(string left, string right)
{
// Convert the hexadecimal strings to unsigned 64-bit integers using base 16
var leftNumber = Convert.ToUInt64(left, 16);
var rightNumber = Convert.ToUInt64(right, 16);
// Add the two integers and calculate the remainder after dividing by _modVal
var total = (leftNumber + rightNumber) % ModVal;
// Convert the result to a hexadecimal string using base 16
var result = total.ToString("x");
// Pad the result with leading zeros to make it 8 characters long
result = "00000000" + result;
// Return the last 8 characters of the result
return result[^8..];
}
/// <summary>
/// Performs the F function on a 32-bit input and returns a 32-bit output.
/// </summary>
/// <param name="plainText">The 32-bit hexadecimal input to the F function.</param>
/// <returns>The 32-bit hexadecimal output of the F function.</returns>
/// <remarks>
/// The F function is a non-linear function that operates on a 32-bit input and produces a 32-bit output. It is used
/// to generate the sub-keys and to perform the encryption and decryption of the data blocks.
/// </remarks>
private string F(string plainText)
{
var a = new string[4];
for (var i = 0; i < 8; i += 2)
{
var col = Convert.ToUInt64(HexadecimalToBinary(plainText.Substring(i, 2)), 2);
a[i / 2] = s[i / 2][col];
}
var answer = AddAndMod(a[0], a[1]);
answer = Xor(answer, a[2]);
answer = AddAndMod(answer, a[3]);
return answer;
}
/// <summary>
/// Performs one round of the blowfish encryption on a 64-bit block of data.
/// </summary>
/// <param name="feistelRound">The round number, from 0 to 15, indicating which subkey from the P-array to use.</param>
/// <param name="plainText">The 64-bit block of data to be encrypted or decrypted, represented as a hexadecimal string.</param>
/// <returns>The encrypted or decrypted block of data, represented as a hexadecimal string.</returns>
private string Round(int feistelRound, string plainText)
{
// Split the plainText into two 32-bit halves.
var left = plainText[..8];
var right = plainText.Substring(8, 8);
// XOR the left half with the subkey from the P-array.
left = Xor(left, p[feistelRound]);
// Apply the F function to the left half.
var fOutput = F(left);
// XOR the output of the F function with the right half.
right = Xor(fOutput, right);
// Swap the left and right halves and return them as a concatenated string.
return right + left;
}
}
================================================
FILE: Algorithms/Encoders/CaesarEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Encodes using caesar cypher.
/// </summary>
public class CaesarEncoder : IEncoder<int>
{
/// <summary>
/// Encodes text using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
public string Encode(string text, int key) => Cipher(text, key);
/// <summary>
/// Decodes text that was encoded using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
public string Decode(string text, int key) => Cipher(text, -key);
private static string Cipher(string text, int key)
{
var newText = new StringBuilder(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (!char.IsLetter(text[i]))
{
_ = newText.Append(text[i]);
continue;
}
var letterA = char.IsUpper(text[i]) ? 'A' : 'a';
var letterZ = char.IsUpper(text[i]) ? 'Z' : 'z';
var c = text[i] + key;
c -= c > letterZ ? 26 * (1 + (c - letterZ - 1) / 26) : 0;
c += c < letterA ? 26 * (1 + (letterA - c - 1) / 26) : 0;
_ = newText.Append((char)c);
}
return newText.ToString();
}
}
================================================
FILE: Algorithms/Encoders/FeistelCipher.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Encodes using Feistel cipher.
/// https://en.wikipedia.org/wiki/Feistel_cipher
/// In cryptography, a Feistel cipher (also known as Luby–Rackoff block cipher)
/// is a symmetric structure used in the construction of block ciphers,
/// named after the German-born physicist and cryptographer Horst Feistel
/// who did pioneering research while working for IBM (USA)
/// A large proportion of block ciphers use the scheme, including the US DES,
/// the Soviet/Russian GOST and the more recent Blowfish and Twofish ciphers.
/// </summary>
public class FeistelCipher : IEncoder<uint>
{
// number of rounds to transform data block, each round a new "round" key is generated.
private const int Rounds = 32;
/// <summary>
/// Encodes text using specified key,
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <exception cref="ArgumentException">Error: key should be more than 0x00001111 for better encoding, key=0 will throw DivideByZero exception.</exception>
/// <returns>Encoded text.</returns>
public string Encode(string text, uint key)
{
List<ulong> blocksListPlain = SplitTextToBlocks(text);
StringBuilder encodedText = new();
foreach (ulong block in blocksListPlain)
{
uint temp = 0;
// decompose a block to two subblocks 0x0123456789ABCDEF => 0x01234567 & 0x89ABCDEF
uint rightSubblock = (uint)(block & 0x00000000FFFFFFFF);
uint leftSubblock = (uint)(block >> 32);
uint roundKey;
// Feistel "network" itself
for (int round = 0; round < Rounds; round++)
{
roundKey = GetRoundKey(key, round);
temp = rightSubblock ^ BlockModification(leftSubblock, roundKey);
rightSubblock = leftSubblock;
leftSubblock = temp;
}
// compile text string formating the block value to text (hex based), length of the output = 16 byte always
ulong encodedBlock = leftSubblock;
encodedBlock = (encodedBlock << 32) | rightSubblock;
encodedText.Append(string.Format("{0:X16}", encodedBlock));
}
return encodedText.ToString();
}
/// <summary>
/// Decodes text that was encoded using specified key.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <exception cref="ArgumentException">Error: key should be more than 0x00001111 for better encoding, key=0 will throw DivideByZero exception.</exception>
/// <exception cref="ArgumentException">Error: The length of text should be divisible by 16 as it the block lenght is 16 bytes.</exception>
/// <returns>Decoded text.</returns>
public string Decode(string text, uint key)
{
// The plain text will be padded to fill the size of block (16 bytes)
if (text.Length % 16 != 0)
{
throw new ArgumentException($"The length of {nameof(key)} should be divisible by 16");
}
List<ulong> blocksListEncoded = GetBlocksFromEncodedText(text);
StringBuilder decodedTextHex = new();
foreach (ulong block in blocksListEncoded)
{
uint temp = 0;
// decompose a block to two subblocks 0x0123456789ABCDEF => 0x01234567 & 0x89ABCDEF
uint rightSubblock = (uint)(block & 0x00000000FFFFFFFF);
uint leftSubblock = (uint)(block >> 32);
// Feistel "network" - decoding, the order of rounds and operations on the blocks is reverted
uint roundKey;
for (int round = Rounds - 1; round >= 0; round--)
{
roundKey = GetRoundKey(key, round);
temp = leftSubblock ^ BlockModification(rightSubblock, roundKey);
leftSubblock = rightSubblock;
rightSubblock = temp;
}
// compose decoded block
ulong decodedBlock = leftSubblock;
decodedBlock = (decodedBlock << 32) | rightSubblock;
for (int i = 0; i < 8; i++)
{
ulong a = (decodedBlock & 0xFF00000000000000) >> 56;
// it's a trick, the code works with non zero characters, if your text has ASCII code 0x00 it will be skipped.
if (a != 0)
{
decodedTextHex.Append((char)a);
}
decodedBlock = decodedBlock << 8;
}
}
return decodedTextHex.ToString();
}
// Using the size of block = 8 bytes this function splts the text and returns set of 8 bytes (ulong) blocks
// the last block is extended up to 8 bytes if the tail of the text is smaller than 8 bytes
private static List<ulong> SplitTextToBlocks(string text)
{
List<ulong> blocksListPlain = [];
byte[] textArray = Encoding.ASCII.GetBytes(text);
int offset = 8;
for (int i = 0; i < text.Length; i += 8)
{
// text not always has len%16 == 0, that's why the offset should be adjusted for the last part of the text
if (i > text.Length - 8)
{
offset = text.Length - i;
}
string block = Convert.ToHexString(textArray, i, offset);
blocksListPlain.Add(Convert.ToUInt64(block, 16));
}
return blocksListPlain;
}
// convert the encoded text to the set of ulong values (blocks for decoding)
private static List<ulong> GetBlocksFromEncodedText(string text)
{
List<ulong> blocksListPlain = [];
for (int i = 0; i < text.Length; i += 16)
{
ulong block = Convert.ToUInt64(text.Substring(i, 16), 16);
blocksListPlain.Add(block);
}
return blocksListPlain;
}
// here might be any deterministic math formula
private static uint BlockModification(uint block, uint key)
{
for (int i = 0; i < 32; i++)
{
// 0x55555555 for the better distribution 0 an 1 in the block
block = ((block ^ 0x55555555) * block) % key;
block = block ^ key;
}
return block;
}
// There are many ways to generate a round key, any deterministic math formula does work
private static uint GetRoundKey(uint key, int round)
{
// "round + 2" - to avoid a situation when pow(key,1) ^ key = key ^ key = 0
uint a = (uint)Math.Pow((double)key, round + 2);
return a ^ key;
}
}
================================================
FILE: Algorithms/Encoders/HillEncoder.cs
================================================
using Algorithms.Numeric;
namespace Algorithms.Encoders;
/// <summary>
/// Lester S. Hill's polygraphic substitution cipher,
/// without representing letters using mod26, using
/// corresponding "(char)value" instead.
/// </summary>
public class HillEncoder : IEncoder<double[,]>
{
private readonly GaussJordanElimination linearEquationSolver;
public HillEncoder() => linearEquationSolver = new GaussJordanElimination(); // TODO: add DI
public string Encode(string text, double[,] key)
{
var preparedText = FillGaps(text);
var chunked = ChunkTextToArray(preparedText);
var splitted = SplitToCharArray(chunked);
var ciphered = new double[chunked.Length][];
for (var i = 0; i < chunked.Length; i++)
{
var vector = new double[3];
Array.Copy(splitted, i * 3, vector, 0, 3);
var product = MatrixCipher(vector, key);
ciphered[i] = product;
}
var merged = MergeArrayList(ciphered);
return BuildStringFromArray(merged);
}
public string Decode(string text, double[,] key)
{
var chunked = ChunkTextToArray(text);
var split = SplitToCharArray(chunked);
var deciphered = new double[chunked.Length][];
for (var i = 0; i < chunked.Length; i++)
{
var vector = new double[3];
Array.Copy(split, i * 3, vector, 0, 3);
var product = MatrixDeCipher(vector, key);
deciphered[i] = product;
}
var merged = MergeArrayList(deciphered);
var str = BuildStringFromArray(merged);
return UnFillGaps(str);
}
/// <summary>
/// Converts elements from the array to their corresponding Unicode characters.
/// </summary>
/// <param name="arr">array of vectors.</param>
/// <returns>Message.</returns>
private static string BuildStringFromArray(double[] arr) => new(arr.Select(c => (char)c).ToArray());
/// <summary>
/// Multiplies the key for the given scalar.
/// </summary>
/// <param name="vector">list of splitted words as numbers.</param>
/// <param name="key">Cipher selected key.</param>
/// <returns>Ciphered vector.</returns>
private static double[] MatrixCipher(double[] vector, double[,] key)
{
var multiplied = new double[vector.Length];
for (var i = 0; i < key.GetLength(1); i++)
{
for (var j = 0; j < key.GetLength(0); j++)
{
multiplied[i] += key[i, j] * vector[j];
}
}
return multiplied;
}
/// <summary>
/// Given a list of vectors, returns a single array of elements.
/// </summary>
/// <param name="list">List of ciphered arrays.</param>
/// <returns>unidimensional list.</returns>
private static double[] MergeArrayList(double[][] list)
{
var merged = new double[list.Length * 3];
for (var i = 0; i < list.Length; i++)
{
Array.Copy(list[i], 0, merged, i * 3, list[0].Length);
}
return merged;
}
/// <summary>
/// Splits the input text message as chunks of words.
/// </summary>
/// <param name="chunked">chunked words list.</param>
/// <returns>spliiter char array.</returns>
private static char[] SplitToCharArray(string[] chunked)
{
var splitted = new char[chunked.Length * 3];
for (var i = 0; i < chunked.Length; i++)
{
for (var j = 0; j < 3; j++)
{
splitted[i * 3 + j] = chunked[i].ToCharArray()[j];
}
}
return splitted;
}
/// <summary>
/// Chunks the input text message.
/// </summary>
/// <param name="text">text message.</param>
/// <returns>array of words.</returns>
private static string[] ChunkTextToArray(string text)
{
// To split the message into chunks
var div = text.Length / 3;
var chunks = new string[div];
for (var i = 0; i < div; i++)
{
chunks.SetValue(text.Substring(i * 3, 3), i);
}
return chunks;
}
/// <summary>
/// Fills a text message with spaces at the end
/// to enable a simple split by 3-length-word.
/// </summary>
/// <param name="text">Text Message.</param>
/// <returns>Modified text Message.</returns>
private static string FillGaps(string text)
{
var remainder = text.Length % 3;
return remainder == 0 ? text : text + new string(' ', 3 - remainder);
}
/// <summary>
/// Removes the extra spaces included on the cipher phase.
/// </summary>
/// <param name="text">Text message.</param>
/// <returns>Deciphered Message.</returns>
private static string UnFillGaps(string text) => text.TrimEnd();
/// <summary>
/// Finds the inverse of the given matrix using a linear equation solver.
/// </summary>
/// <param name="vector">Splitted words vector.</param>
/// <param name="key">Key used for the cipher.</param>
/// <returns>TODO.</returns>
private double[] MatrixDeCipher(double[] vector, double[,] key)
{
// To augment the original key with the given vector.
var augM = new double[3, 4];
for (var i = 0; i < key.GetLength(0); i++)
{
for (var j = 0; j < key.GetLength(1); j++)
{
augM[i, j] = key[i, j];
}
}
for (var k = 0; k < vector.Length; k++)
{
augM[k, 3] = vector[k];
}
_ = linearEquationSolver.Solve(augM);
return [augM[0, 3], augM[1, 3], augM[2, 3]];
}
}
================================================
FILE: Algorithms/Encoders/IEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Encodes and decodes text based on specified key.
/// </summary>
/// <typeparam name="TKey">Type of the key.</typeparam>
public interface IEncoder<TKey>
{
/// <summary>
/// Encodes text using specified key.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
string Encode(string text, TKey key);
/// <summary>
/// Decodes text that was encoded using specified key.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
string Decode(string text, TKey key);
}
================================================
FILE: Algorithms/Encoders/NysiisEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Class for NYSIIS encoding strings.
/// </summary>
public class NysiisEncoder
{
private static readonly char[] Vowels = ['A', 'E', 'I', 'O', 'U'];
/// <summary>
/// Encodes a string using the NYSIIS Algorithm.
/// </summary>
/// <param name="text">The string to encode.</param>
/// <returns>The NYSIIS encoded string (all uppercase).</returns>
public string Encode(string text)
{
text = text.ToUpper(CultureInfo.CurrentCulture);
text = TrimSpaces(text);
text = StartReplace(text);
text = EndReplace(text);
for (var i = 1; i < text.Length; i++)
{
text = ReplaceStep(text, i);
}
text = RemoveDuplicates(text);
return TrimEnd(text);
}
private string TrimSpaces(string text) => text.Replace(" ", string.Empty);
private string RemoveDuplicates(string text)
{
var sb = new StringBuilder();
sb.Append(text[0]);
foreach (var c in text)
{
if (sb[^1] != c)
{
sb.Append(c);
}
}
return sb.ToString();
}
private string TrimEnd(string text)
{
var checks = new (string From, string To)?[]
{
("S", string.Empty),
("AY", "Y"),
("A", string.Empty),
};
var replacement = checks.FirstOrDefault(t => text.EndsWith(t!.Value.From));
if (replacement is { })
{
var (from, to) = replacement!.Value;
text = Replace(text, text.Length - from.Length, from.Length, to);
}
return text;
}
private string ReplaceStep(string text, int i)
{
(string From, string To)[] replacements =
[
("EV", "AF"),
("E", "A"),
("I", "A"),
("O", "A"),
("U", "A"),
("Q", "G"),
("Z", "S"),
("M", "N"),
("KN", "NN"),
("K", "C"),
("SCH", "SSS"),
("PH", "FF"),
];
var replaced = TryReplace(text, i, replacements, out text);
if (replaced)
{
return text;
}
// H[vowel] or [vowel]H -> text[i-1]
if (text[i] == 'H')
{
if (!Vowels.Contains(text[i - 1]))
{
return ReplaceWithPrevious();
}
if (i < text.Length - 1 && !Vowels.Contains(text[i + 1]))
{
return ReplaceWithPrevious();
}
}
// [vowel]W -> [vowel]
if (text[i] == 'W' && Vowels.Contains(text[i - 1]))
{
return ReplaceWithPrevious();
}
return text;
string ReplaceWithPrevious() => Replace(text, i, 1, text[i - 1].ToString());
}
private bool TryReplace(string text, int index, (string, string)[] opts, out string result)
{
for (var i = 0; i < opts.Length; i++)
{
var check = opts[i].Item1;
var repl = opts[i].Item2;
if (text.Length >= index + check.Length && text.Substring(index, check.Length) == check)
{
result = Replace(text, index, check.Length, repl);
return true;
}
}
result = text;
return false;
}
private string StartReplace(string start)
{
var checks = new (string From, string To)?[]
{
("MAC", "MCC"),
("KN", "NN"),
("K", "C"),
("PH", "FF"),
("PF", "FF"),
("SCH", "SSS"),
};
var replacement = checks.FirstOrDefault(t => start.StartsWith(t!.Value.From));
if (replacement is { })
{
var (from, to) = replacement!.Value;
start = Replace(start, 0, from.Length, to);
}
return start;
}
private string EndReplace(string end)
{
var checks = new (string From, string To)?[]
{
("EE", "Y"),
("IE", "Y"),
("DT", "D"),
("RT", "D"),
("NT", "D"),
("ND", "D"),
};
var replacement = checks.FirstOrDefault(t => end.EndsWith(t!.Value.From));
if (replacement is { })
{
var (from, to) = replacement!.Value;
end = Replace(end, end.Length - from.Length, from.Length, to);
}
return end;
}
private string Replace(string text, int index, int length, string substitute) =>
text[..index] + substitute + text[(index + length)..];
}
================================================
FILE: Algorithms/Encoders/SoundexEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Class for Soundex encoding strings.
/// </summary>
public class SoundexEncoder
{
private static readonly Dictionary<char, int> CharacterMapping = new()
{
['a'] = 0,
['e'] = 0,
['i'] = 0,
['o'] = 0,
['u'] = 0,
['y'] = 0,
['h'] = 8,
['w'] = 8,
['b'] = 1,
['f'] = 1,
['p'] = 1,
['v'] = 1,
['c'] = 2,
['g'] = 2,
['j'] = 2,
['k'] = 2,
['q'] = 2,
['s'] = 2,
['x'] = 2,
['z'] = 2,
['d'] = 3,
['t'] = 3,
['l'] = 4,
['m'] = 5,
['n'] = 5,
['r'] = 6,
};
/// <summary>
/// Encodes a string using the Soundex Algorithm.
/// </summary>
/// <param name="text">The string to encode.</param>
/// <returns>The Soundex encoded string (one uppercase character and three digits).</returns>
public string Encode(string text)
{
text = text.ToLowerInvariant();
var chars = OmitHAndW(text);
IEnumerable<int> numbers = ProduceNumberCoding(chars);
numbers = CollapseDoubles(numbers);
numbers = OmitVowels(numbers);
numbers = CollapseLeadingDigit(numbers, text[0]);
numbers = numbers.Take(3);
numbers = PadTo3Numbers(numbers);
var final = numbers.ToArray();
return $"{text.ToUpperInvariant()[0]}{final[0]}{final[1]}{final[2]}";
}
private IEnumerable<int> CollapseLeadingDigit(IEnumerable<int> numbers, char c)
{
using var enumerator = numbers.GetEnumerator();
enumerator.MoveNext();
if (enumerator.Current == MapToNumber(c))
{
enumerator.MoveNext();
}
do
{
yield return enumerator.Current;
}
while (enumerator.MoveNext());
}
private IEnumerable<int> PadTo3Numbers(IEnumerable<int> numbers)
{
using var enumerator = numbers.GetEnumerator();
for (var i = 0; i < 3; i++)
{
yield return enumerator.MoveNext()
? enumerator.Current
: 0;
}
}
private IEnumerable<int> OmitVowels(IEnumerable<int> numbers) => numbers.Where(i => i != 0);
private IEnumerable<char> OmitHAndW(string text) => text.Where(c => c != 'h' && c != 'w');
private IEnumerable<int> CollapseDoubles(IEnumerable<int> numbers)
{
var previous = int.MinValue;
foreach (var i in numbers)
{
if (previous != i)
{
yield return i;
previous = i;
}
}
}
private IEnumerable<int> ProduceNumberCoding(IEnumerable<char> text) => text.Select(MapToNumber);
private int MapToNumber(char ch)
{
return CharacterMapping[ch];
}
}
================================================
FILE: Algorithms/Encoders/VigenereEncoder.cs
================================================
namespace Algorithms.Encoders;
/// <summary>
/// Encodes using vigenere cypher.
/// </summary>
public class VigenereEncoder : IEncoder<string>
{
private readonly CaesarEncoder caesarEncoder = new();
/// <summary>
/// Encodes text using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be encoded.</param>
/// <param name="key">Key that will be used to encode the text.</param>
/// <returns>Encoded text.</returns>
public string Encode(string text, string key) => Cipher(text, key, caesarEncoder.Encode);
/// <summary>
/// Decodes text that was encoded using specified key,
/// time complexity: O(n),
/// space complexity: O(n),
/// where n - text length.
/// </summary>
/// <param name="text">Text to be decoded.</param>
/// <param name="key">Key that was used to encode the text.</param>
/// <returns>Decoded text.</returns>
public string Decode(string text, string key) => Cipher(text, key, caesarEncoder.Decode);
private string Cipher(string text, string key, Func<string, int, string> symbolCipher)
{
key = AppendKey(key, text.Length);
var encodedTextBuilder = new StringBuilder(text.Length);
for (var i = 0; i < text.Length; i++)
{
if (!char.IsLetter(text[i]))
{
_ = encodedTextBuilder.Append(text[i]);
continue;
}
var letterZ = char.IsUpper(key[i]) ? 'Z' : 'z';
var encodedSymbol = symbolCipher(text[i].ToString(), letterZ - key[i]);
_ = encodedTextBuilder.Append(encodedSymbol);
}
return encodedTextBuilder.ToString();
}
private string AppendKey(string key, int length)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentOutOfRangeException($"{nameof(key)} must be non-empty string");
}
var keyBuilder = new StringBuilder(key, length);
while (keyBuilder.Length < length)
{
_ = keyBuilder.Append(key);
}
return keyBuilder.ToString();
}
}
================================================
FILE: Algorithms/Financial/PresentValue.cs
================================================
namespace Algorithms.Financial;
/// <summary>
/// PresentValue is the value of an expected income stream determined as of the date of valuation.
/// </summary>
public static class PresentValue
{
public static double Calculate(double discountRate, List<double> cashFlows)
{
if (discountRate < 0)
{
throw new ArgumentException("Discount rate cannot be negative");
}
if (cashFlows.Count == 0)
{
throw new ArgumentException("Cash flows list cannot be empty");
}
double presentValue = cashFlows.Select((t, i) => t / Math.Pow(1 + discountRate, i)).Sum();
return Math.Round(presentValue, 2);
}
}
================================================
FILE: Algorithms/GlobalUsings.cs
================================================
// -----------------------------------------------------------------------------
// Global using directives for the C-Sharp solution.
// These namespaces are imported globally so they don’t need to be repeatedly declared
// in individual files, improving readability and reducing boilerplate.
//
// Guidelines:
// - Keep only the most commonly used namespaces here.
// - Add project-specific namespaces (e.g., Utilities.Extensions) only if they are
// required across the majority of files in the project.
// - Avoid placing rarely used namespaces here to maintain clarity.
// -----------------------------------------------------------------------------
global using System; // Core base classes and fundamental types
global using System.Collections.Generic; // Generic collection types (List, Dictionary, etc.)
global using System.Globalization; // Culture-related information (dates, numbers, formatting)
global using System.Linq; // LINQ query operators for collections
global using System.Numerics; // Numeric types such as BigInteger and Complex
global using System.Security.Cryptography; // Cryptographic services (hashing, encryption, random numbers)
global using System.Text; // Text encoding, StringBuilder, etc.
global using System.Text.RegularExpressions; // Regular expression support
global using Utilities.Extensions; // Common extension methods used across the solution
================================================
FILE: Algorithms/Graph/ArticulationPoints.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Graph;
/// <summary>
/// Finds articulation points (cut vertices) in an undirected graph.
/// An articulation point is a vertex whose removal increases the number of connected components.
/// </summary>
public static class ArticulationPoints
{
/// <summary>
/// Finds all articulation points in an undirected graph.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>Set of articulation points.</returns>
public static HashSet<T> Find<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
if (vertices == null)
{
throw new ArgumentNullException(nameof(vertices));
}
if (getNeighbors == null)
{
throw new ArgumentNullException(nameof(getNeighbors));
}
var vertexList = vertices.ToList();
if (vertexList.Count == 0)
{
return new HashSet<T>();
}
var articulationPoints = new HashSet<T>();
var visited = new HashSet<T>();
var discoveryTime = new Dictionary<T, int>();
var low = new Dictionary<T, int>();
var parent = new Dictionary<T, T?>();
var time = 0;
foreach (var vertex in vertexList)
{
if (!visited.Contains(vertex))
{
var state = new DfsState<T>
{
Visited = visited,
DiscoveryTime = discoveryTime,
Low = low,
Parent = parent,
ArticulationPoints = articulationPoints,
};
Dfs(vertex, ref time, state, getNeighbors);
}
}
return articulationPoints;
}
/// <summary>
/// Checks if a vertex is an articulation point.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertex">Vertex to check.</param>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>True if vertex is an articulation point.</returns>
public static bool IsArticulationPoint<T>(
T vertex,
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
var articulationPoints = Find(vertices, getNeighbors);
return articulationPoints.Contains(vertex);
}
/// <summary>
/// Counts the number of articulation points in the graph.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>Number of articulation points.</returns>
public static int Count<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
return Find(vertices, getNeighbors).Count;
}
private static void Dfs<T>(
T u,
ref int time,
DfsState<T> state,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
state.Visited.Add(u);
state.DiscoveryTime[u] = time;
state.Low[u] = time;
time++;
int children = 0;
foreach (var v in getNeighbors(u))
{
if (!state.Visited.Contains(v))
{
children++;
state.Parent[v] = u;
Dfs(v, ref time, state, getNeighbors);
state.Low[u] = Math.Min(state.Low[u], state.Low[v]);
// Check if u is an articulation point
bool isRoot = !state.Parent.ContainsKey(u);
if (isRoot && children > 1)
{
state.ArticulationPoints.Add(u);
}
bool isNonRootArticulation = state.Parent.ContainsKey(u) && state.Low[v] >= state.DiscoveryTime[u];
if (isNonRootArticulation)
{
state.ArticulationPoints.Add(u);
}
}
else if (!EqualityComparer<T>.Default.Equals(v, state.Parent.GetValueOrDefault(u)))
{
// Back edge: update low value
state.Low[u] = Math.Min(state.Low[u], state.DiscoveryTime[v]);
}
else
{
// Edge to parent: no action needed
}
}
}
/// <summary>
/// Encapsulates the state for DFS traversal in articulation point detection.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
private sealed class DfsState<T>
where T : notnull
{
/// <summary>
/// Gets set of visited vertices.
/// </summary>
public required HashSet<T> Visited { get; init; }
/// <summary>
/// Gets discovery time for each vertex.
/// </summary>
public required Dictionary<T, int> DiscoveryTime { get; init; }
/// <summary>
/// Gets lowest discovery time reachable from each vertex.
/// </summary>
public required Dictionary<T, int> Low { get; init; }
/// <summary>
/// Gets parent vertex in DFS tree.
/// </summary>
public required Dictionary<T, T?> Parent { get; init; }
/// <summary>
/// Gets set of detected articulation points.
/// </summary>
public required HashSet<T> ArticulationPoints { get; init; }
}
}
================================================
FILE: Algorithms/Graph/BellmanFord.cs
================================================
using DataStructures.Graph;
namespace Algorithms.Graph;
/// <summary>
/// Bellman-Ford algorithm on directed weighted graph.
/// </summary>
/// <typeparam name="T">Generic type of data in the graph.</typeparam>
public class BellmanFord<T>(DirectedWeightedGraph<T> graph, Dictionary<Vertex<T>, double> distances, Dictionary<Vertex<T>, Vertex<T>?> predecessors)
{
private readonly DirectedWeightedGraph<T> graph = graph;
private readonly Dictionary<Vertex<T>, double> distances = distances;
private readonly Dictionary<Vertex<T>, Vertex<T>?> predecessors = predecessors;
/// <summary>
/// Runs the Bellman-Ford algorithm to find the shortest distances from the source vertex to all other vertices.
/// </summary>
/// <param name="sourceVertex">Source vertex for shortest path calculation.</param>
/// <returns>
/// A dictionary containing the shortest distances from the source vertex to all other vertices.
/// If a vertex is unreachable from the source, it will have a value of double.PositiveInfinity.
/// </returns>
public Dictionary<Vertex<T>, double> Run(Vertex<T> sourceVertex)
{
InitializeDistances(sourceVertex);
RelaxEdges();
CheckForNegativeCycles();
return distances;
}
private void InitializeDistances(Vertex<T> sourceVertex)
{
foreach (var vertex in graph.Vertices)
{
if (vertex != null)
{
distances[vertex] = double.PositiveInfinity;
predecessors[vertex] = null;
}
}
distances[sourceVertex] = 0;
}
private void RelaxEdges()
{
int vertexCount = graph.Count;
for (int i = 0; i < vertexCount - 1; i++)
{
foreach (var vertex in graph.Vertices)
{
if (vertex != null)
{
RelaxEdgesForVertex(vertex);
}
}
}
}
private void RelaxEdgesForVertex(Vertex<T> u)
{
foreach (var neighbor in graph.GetNeighbors(u))
{
if (neighbor == null)
{
continue;
}
var v = neighbor;
var weight = graph.AdjacentDistance(u, v);
if (distances[u] + weight < distances[v])
{
distances[v] = distances[u] + weight;
predecessors[v] = u;
}
}
}
private void CheckForNegativeCycles()
{
foreach (var vertex in graph.Vertices)
{
if (vertex != null)
{
CheckForNegativeCyclesForVertex(vertex);
}
}
}
private void CheckForNegativeCyclesForVertex(Vertex<T> u)
{
foreach (var neighbor in graph.GetNeighbors(u))
{
if (neighbor == null)
{
continue;
}
var v = neighbor;
var weight = graph.AdjacentDistance(u, v);
if (distances[u] + weight < distances[v])
{
throw new InvalidOperationException("Graph contains a negative weight cycle.");
}
}
}
}
================================================
FILE: Algorithms/Graph/BipartiteGraph.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Graph;
/// <summary>
/// Checks if a graph is bipartite (2-colorable).
/// A bipartite graph can be divided into two independent sets where no two vertices
/// within the same set are adjacent.
/// </summary>
public static class BipartiteGraph
{
/// <summary>
/// Checks if a graph is bipartite using BFS-based coloring.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>True if graph is bipartite, false otherwise.</returns>
public static bool IsBipartite<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
if (vertices == null)
{
throw new ArgumentNullException(nameof(vertices));
}
if (getNeighbors == null)
{
throw new ArgumentNullException(nameof(getNeighbors));
}
var vertexList = vertices.ToList();
if (vertexList.Count == 0)
{
return true; // Empty graph is bipartite
}
var colors = new Dictionary<T, int>();
// Check each connected component
foreach (var start in vertexList)
{
if (colors.ContainsKey(start))
{
continue; // Already colored
}
if (!BfsColor(start, colors, getNeighbors))
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the two partitions of a bipartite graph.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>Tuple of two sets representing the partitions, or null if not bipartite.</returns>
public static (HashSet<T> SetA, HashSet<T> SetB)? GetPartitions<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
if (vertices == null)
{
throw new ArgumentNullException(nameof(vertices));
}
if (getNeighbors == null)
{
throw new ArgumentNullException(nameof(getNeighbors));
}
var vertexList = vertices.ToList();
if (vertexList.Count == 0)
{
return (new HashSet<T>(), new HashSet<T>());
}
var colors = new Dictionary<T, int>();
// Color all components
foreach (var start in vertexList)
{
if (colors.ContainsKey(start))
{
continue;
}
if (!BfsColor(start, colors, getNeighbors))
{
return null; // Not bipartite
}
}
// Split into two sets based on color
var setA = new HashSet<T>();
var setB = new HashSet<T>();
foreach (var vertex in vertexList)
{
if (colors[vertex] == 0)
{
setA.Add(vertex);
}
else
{
setB.Add(vertex);
}
}
return (setA, setB);
}
/// <summary>
/// Checks if a graph is bipartite using DFS-based coloring.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>True if graph is bipartite, false otherwise.</returns>
public static bool IsBipartiteDfs<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
if (vertices == null)
{
throw new ArgumentNullException(nameof(vertices));
}
if (getNeighbors == null)
{
throw new ArgumentNullException(nameof(getNeighbors));
}
var vertexList = vertices.ToList();
if (vertexList.Count == 0)
{
return true;
}
var colors = new Dictionary<T, int>();
foreach (var start in vertexList)
{
if (colors.ContainsKey(start))
{
continue;
}
if (!DfsColor(start, 0, colors, getNeighbors))
{
return false;
}
}
return true;
}
private static bool BfsColor<T>(
T start,
Dictionary<T, int> colors,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
var queue = new Queue<T>();
queue.Enqueue(start);
colors[start] = 0;
while (queue.Count > 0)
{
var current = queue.Dequeue();
var currentColor = colors[current];
var nextColor = 1 - currentColor;
foreach (var neighbor in getNeighbors(current))
{
if (!colors.ContainsKey(neighbor))
{
colors[neighbor] = nextColor;
queue.Enqueue(neighbor);
}
else if (colors[neighbor] == currentColor)
{
return false; // Same color as current - not bipartite
}
else
{
// Different color - valid
}
}
}
return true;
}
private static bool DfsColor<T>(
T vertex,
int color,
Dictionary<T, int> colors,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
colors[vertex] = color;
var nextColor = 1 - color;
foreach (var neighbor in getNeighbors(vertex))
{
if (!colors.ContainsKey(neighbor))
{
if (!DfsColor(neighbor, nextColor, colors, getNeighbors))
{
return false;
}
}
else if (colors[neighbor] == color)
{
return false; // Same color - not bipartite
}
else
{
// Different color - valid
}
}
return true;
}
}
================================================
FILE: Algorithms/Graph/BreadthFirstSearch.cs
================================================
using DataStructures.Graph;
namespace Algorithms.Graph;
/// <summary>
/// Breadth First Search - algorithm for traversing graph.
/// Algorithm starts from root node that is selected by the user.
/// Algorithm explores all nodes at the present depth.
/// </summary>
/// <typeparam name="T">Vertex data type.</typeparam>
public class BreadthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
{
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = default)
{
Bfs(graph, startVertex, action, []);
}
/// <summary>
/// Traverses graph from start vertex.
/// </summary>
/// <param name="graph">Graph instance.</param>
/// <param name="startVertex">Vertex that search starts from.</param>
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
/// <param name="visited">Hash set with visited vertices.</param>
private void Bfs(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action, HashSet<Vertex<T>> visited)
{
var queue = new Queue<Vertex<T>>();
queue.Enqueue(startVertex);
while (queue.Count > 0)
{
var currentVertex = queue.Dequeue();
if (currentVertex == null || visited.Contains(currentVertex))
{
continue;
}
foreach (var vertex in graph.GetNeighbors(currentVertex))
{
queue.Enqueue(vertex!);
}
action?.Invoke(currentVertex);
visited.Add(currentVertex);
}
}
}
================================================
FILE: Algorithms/Graph/BreadthFirstTreeTraversal.cs
================================================
using DataStructures.BinarySearchTree;
namespace Algorithms.Graph;
/// <summary>
/// Breadth first tree traversal traverses through a binary tree
/// by iterating through each level first.
/// time complexity: O(n).
/// space complexity: O(w) where w is the max width of a binary tree.
/// </summary>
/// <typeparam name="TKey">Type of key held in binary search tree.</typeparam>
public static class BreadthFirstTreeTraversal<TKey>
{
/// <summary>
/// Level Order Traversal returns an array of integers in order
/// of each level of a binary tree. It uses a queue to iterate
/// through each node following breadth first search traversal.
/// </summary>
/// <param name="tree">Passes the binary tree to traverse.</param>
/// <returns>Returns level order traversal.</returns>
public static TKey[] LevelOrderTraversal(BinarySearchTree<TKey> tree)
{
BinarySearchTreeNode<TKey>? root = tree.Root;
TKey[] levelOrder = new TKey[tree.Count];
if (root is null)
{
return Array.Empty<TKey>();
}
Queue<BinarySearchTreeNode<TKey>> breadthTraversal = new Queue<BinarySearchTreeNode<TKey>>();
breadthTraversal.Enqueue(root);
for (int i = 0; i < levelOrder.Length; i++)
{
BinarySearchTreeNode<TKey> current = breadthTraversal.Dequeue();
levelOrder[i] = current.Key;
if (current.Left is not null)
{
breadthTraversal.Enqueue(current.Left);
}
if (current.Right is not null)
{
breadthTraversal.Enqueue(current.Right);
}
}
return levelOrder;
}
/// <summary>
/// Deepest Node return the deepest node in a binary tree. If more
/// than one node is on the deepest level, it is defined as the
/// right-most node of a binary tree. Deepest node uses breadth
/// first traversal to reach the end.
/// </summary>
/// <param name="tree">Tree passed to find deepest node.</param>
/// <returns>Returns the deepest node in the tree.</returns>
public static TKey? DeepestNode(BinarySearchTree<TKey> tree)
{
BinarySearchTreeNode<TKey>? root = tree.Root;
if (root is null)
{
return default(TKey);
}
Queue<BinarySearchTreeNode<TKey>> breadthTraversal = new Queue<BinarySearchTreeNode<TKey>>();
breadthTraversal.Enqueue(root);
TKey deepest = root.Key;
while (breadthTraversal.Count > 0)
{
BinarySearchTreeNode<TKey> current = breadthTraversal.Dequeue();
if (current.Left is not null)
{
breadthTraversal.Enqueue(current.Left);
}
if (current.Right is not null)
{
breadthTraversal.Enqueue(current.Right);
}
deepest = current.Key;
}
return deepest;
}
}
================================================
FILE: Algorithms/Graph/Bridges.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Graph;
/// <summary>
/// Finds bridges (cut edges) in an undirected graph.
/// A bridge is an edge whose removal increases the number of connected components.
/// </summary>
public static class Bridges
{
/// <summary>
/// Finds all bridges in an undirected graph.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>Set of bridges as tuples of vertices.</returns>
public static HashSet<(T From, T To)> Find<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
if (vertices == null)
{
throw new ArgumentNullException(nameof(vertices));
}
if (getNeighbors == null)
{
throw new ArgumentNullException(nameof(getNeighbors));
}
var vertexList = vertices.ToList();
if (vertexList.Count == 0)
{
return new HashSet<(T, T)>();
}
var bridges = new HashSet<(T, T)>();
var visited = new HashSet<T>();
var discoveryTime = new Dictionary<T, int>();
var low = new Dictionary<T, int>();
var parent = new Dictionary<T, T?>();
var time = 0;
foreach (var vertex in vertexList)
{
if (!visited.Contains(vertex))
{
var state = new DfsState<T>
{
Visited = visited,
DiscoveryTime = discoveryTime,
Low = low,
Parent = parent,
Bridges = bridges,
};
Dfs(vertex, ref time, state, getNeighbors);
}
}
return bridges;
}
/// <summary>
/// Checks if an edge is a bridge.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="from">Source vertex.</param>
/// <param name="to">Destination vertex.</param>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>True if edge is a bridge.</returns>
public static bool IsBridge<T>(
T from,
T to,
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
var bridges = Find(vertices, getNeighbors);
return bridges.Contains((from, to)) || bridges.Contains((to, from));
}
/// <summary>
/// Counts the number of bridges in the graph.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
/// <param name="vertices">All vertices in the graph.</param>
/// <param name="getNeighbors">Function to get neighbors of a vertex.</param>
/// <returns>Number of bridges.</returns>
public static int Count<T>(
IEnumerable<T> vertices,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
return Find(vertices, getNeighbors).Count;
}
private static void Dfs<T>(
T u,
ref int time,
DfsState<T> state,
Func<T, IEnumerable<T>> getNeighbors) where T : notnull
{
state.Visited.Add(u);
state.DiscoveryTime[u] = time;
state.Low[u] = time;
time++;
foreach (var v in getNeighbors(u))
{
if (!state.Visited.Contains(v))
{
state.Parent[v] = u;
Dfs(v, ref time, state, getNeighbors);
state.Low[u] = Math.Min(state.Low[u], state.Low[v]);
// Check if edge u-v is a bridge
if (state.Low[v] > state.DiscoveryTime[u])
{
state.Bridges.Add((u, v));
}
}
else if (!EqualityComparer<T>.Default.Equals(v, state.Parent.GetValueOrDefault(u)))
{
// Back edge: update low value
state.Low[u] = Math.Min(state.Low[u], state.DiscoveryTime[v]);
}
else
{
// Edge to parent: no action needed
}
}
}
/// <summary>
/// Encapsulates the state for DFS traversal in bridge detection.
/// </summary>
/// <typeparam name="T">Type of vertex.</typeparam>
private sealed class DfsState<T>
where T : notnull
{
/// <summary>
/// Gets set of visited vertices.
/// </summary>
public required HashSet<T> Visited { get; init; }
/// <summary>
/// Gets di
gitextract_zwg869o3/ ├── .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/ │ ├── 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/ │ │ ├── AutokeyEncorder.cs │ │ ├── BlowfishEncoder.cs │ │ ├── CaesarEncoder.cs │ │ ├── FeistelCipher.cs │ │ ├── HillEncoder.cs │ │ ├── IEncoder.cs │ │ ├── NysiisEncoder.cs │ │ ├── SoundexEncoder.cs │ │ └── VigenereEncoder.cs │ ├── Financial/ │ │ └── PresentValue.cs │ ├── GlobalUsings.cs │ ├── Graph/ │ │ ├── ArticulationPoints.cs │ │ ├── BellmanFord.cs │ │ ├── BipartiteGraph.cs │ │ ├── BreadthFirstSearch.cs │ │ ├── BreadthFirstTreeTraversal.cs │ │ ├── Bridges.cs │ │ ├── DepthFirstSearch.cs │ │ ├── Dijkstra/ │ │ │ ├── DijkstraAlgorithm.cs │ │ │ └── DistanceModel.cs │ │ ├── FloydWarshall.cs │ │ ├── IGraphSearch.cs │ │ ├── Kosaraju.cs │ │ ├── MinimumSpanningTree/ │ │ │ ├── Kruskal.cs │ │ │ └── PrimMatrix.cs │ │ ├── TarjanStronglyConnectedComponents.cs │ │ └── TopologicalSort.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 │ ├── MachineLearning/ │ │ ├── KNearestNeighbors.cs │ │ ├── LinearRegression.cs │ │ └── LogisticRegression.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 │ │ ├── DoubleFactorial.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 │ │ ├── PrimeChecker.cs │ │ ├── Pseudoinverse/ │ │ │ └── PseudoInverse.cs │ │ ├── Relu.cs │ │ ├── RungeKuttaMethod.cs │ │ ├── Series/ │ │ │ └── Maclaurin.cs │ │ ├── Sigmoid.cs │ │ ├── SoftMax.cs │ │ ├── SumOfDigits.cs │ │ └── Tanh.cs │ ├── Other/ │ │ ├── BoyerMooreMajorityVote.cs │ │ ├── DecisionsConvolutions.cs │ │ ├── FermatPrimeChecker.cs │ │ ├── FloodFill.cs │ │ ├── GaussOptimization.cs │ │ ├── GeoLocation.cs │ │ ├── Geofence.cs │ │ ├── Geohash.cs │ │ ├── Int2Binary.cs │ │ ├── JulianEaster.cs │ │ ├── KadanesAlgorithm.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 │ │ ├── GraphColoring/ │ │ │ └── GraphColoringSolver.cs │ │ ├── JobScheduling/ │ │ │ ├── IntervalSchedulingSolver.cs │ │ │ └── Job.cs │ │ ├── KnightTour/ │ │ │ └── OpenKnightTour.cs │ │ ├── NQueens/ │ │ │ └── BacktrackingNQueensSolver.cs │ │ ├── StableMarriage/ │ │ │ ├── Accepter.cs │ │ │ ├── GaleShapley.cs │ │ │ └── Proposer.cs │ │ └── TravelingSalesman/ │ │ └── TravelingSalesmanSolver.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 │ │ ├── LINQShuffler.cs │ │ ├── NaiveShuffler.cs │ │ └── RecursiveShuffler.cs │ ├── Sorters/ │ │ ├── Comparison/ │ │ │ ├── BasicTimSorter.cs │ │ │ ├── BinaryInsertionSorter.cs │ │ │ ├── BogoSorter.cs │ │ │ ├── BubbleSorter.cs │ │ │ ├── CocktailSorter.cs │ │ │ ├── CombSorter.cs │ │ │ ├── CycleSorter.cs │ │ │ ├── ExchangeSorter.cs │ │ │ ├── GnomeSorter.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 │ │ ├── InfixToPostfix.cs │ │ ├── NextGreaterElement.cs │ │ └── ReverseStack.cs │ └── Strings/ │ ├── GeneralStringAlgorithms.cs │ ├── ManachersAlgorithm.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 ├── 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/ │ │ ├── AutokeyEncoderTests.cs │ │ ├── BlowfishEncoderTests.cs │ │ ├── CaesarEncoderTests.cs │ │ ├── FeistelCipherTest.cs │ │ ├── HillEnconderTests.cs │ │ ├── NysiisEncoderTests.cs │ │ ├── SoundexEncoderTest.cs │ │ └── VigenereEncoderTests.cs │ ├── Financial/ │ │ └── PresentValueTests.cs │ ├── GlobalUsings.cs │ ├── Graph/ │ │ ├── ArticulationPointsTests.cs │ │ ├── BellmanFordTests.cs │ │ ├── BipartiteGraphTests.cs │ │ ├── BreadthFirstSearchTests.cs │ │ ├── BreadthFirstTreeTraversalTests.cs │ │ ├── BridgesTests.cs │ │ ├── DepthFirstSearchTests.cs │ │ ├── Dijkstra/ │ │ │ └── DijkstraTests.cs │ │ ├── FloydWarshallTests.cs │ │ ├── KosarajuTests.cs │ │ ├── MinimumSpanningTree/ │ │ │ ├── KruskalTests.cs │ │ │ └── PrimMatrixTests.cs │ │ ├── TarjanStronglyConnectedComponentsTests.cs │ │ └── TopologicalSortTests.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 │ ├── MachineLearning/ │ │ ├── KNearestNeighborsTests.cs │ │ ├── LinearRegressionTests.cs │ │ └── LogisticRegressionTests.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 │ │ ├── DoubleFactorialTests.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 │ │ ├── PrimeNumberTest.cs │ │ ├── PseudoInverse/ │ │ │ └── PseudoInverseTests.cs │ │ ├── ReluTest.cs │ │ ├── RungeKuttaMethodTest.cs │ │ ├── SigmoidTests.cs │ │ ├── SoftMaxTests.cs │ │ ├── SumOfDigitsTest.cs │ │ └── TanhTest.cs │ ├── Other/ │ │ ├── BoyerMooreMajorityVoteTests.cs │ │ ├── DecisionsConvolutionsTest.cs │ │ ├── FermatPrimeCheckerTests.cs │ │ ├── FloodFillTest.cs │ │ ├── GaussOptimizationTest.cs │ │ ├── GeoLocationTests.cs │ │ ├── GeofenceTests.cs │ │ ├── GeohashTests.cs │ │ ├── Int2BinaryTests.cs │ │ ├── JulianEasterTests.cs │ │ ├── KadanesAlgorithmTests.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 │ │ ├── GraphColoring/ │ │ │ └── GraphColoringSolverTests.cs │ │ ├── JobScheduling/ │ │ │ └── IntervalSchedulingSolverTests.cs │ │ ├── KnightTour/ │ │ │ └── OpenKnightTourTests.cs │ │ ├── NQueens/ │ │ │ └── BacktrackingNQueensSolverTests.cs │ │ ├── StableMarriage/ │ │ │ └── GaleShapleyTests.cs │ │ └── TravelingSalesman/ │ │ └── TravelingSalesmanSolverTests.cs │ ├── RecommenderSystem/ │ │ └── CollaborativeFilteringTests.cs │ ├── Search/ │ │ ├── AStarTests.cs │ │ ├── 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 │ │ ├── LINQShufflerTests.cs │ │ ├── NaiveShufflerTests.cs │ │ └── RecursiveShufflerTests.cs │ ├── Sorters/ │ │ ├── Comparison/ │ │ │ ├── BasicTeamSorterTests.cs │ │ │ ├── BinaryInsertionSorterTests.cs │ │ │ ├── BogoSorterTests.cs │ │ │ ├── BubbleSorterTests.cs │ │ │ ├── CocktailSorterTests.cs │ │ │ ├── CombSorterTests.cs │ │ │ ├── CycleSorterTests.cs │ │ │ ├── ExchangeSorterTests.cs │ │ │ ├── GnomeSorterTests.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 │ │ ├── InfixToPostfixTests.cs │ │ ├── NextGreaterElementTests.cs │ │ └── ReverseStackTests.cs │ └── Strings/ │ ├── GeneralStringAlgorithmsTests.cs │ ├── ManachersAlgorithmTests.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 ├── C-Sharp.sln ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── DataStructures/ │ ├── AATree/ │ │ ├── AATree.cs │ │ └── AATreeNode.cs │ ├── AVLTree/ │ │ ├── AVLTree.cs │ │ └── AVLTreeNode.cs │ ├── BTree/ │ │ ├── BTree.cs │ │ └── BTreeNode.cs │ ├── Bag/ │ │ ├── Bag.cs │ │ └── BagNode.cs │ ├── BinarySearchTree/ │ │ ├── BinarySearchTree.cs │ │ └── BinarySearchTreeNode.cs │ ├── BitArray.cs │ ├── Cache/ │ │ ├── LfuCache.cs │ │ └── LruCache.cs │ ├── DataStructures.csproj │ ├── Deque/ │ │ └── Deque.cs │ ├── DisjointSet/ │ │ ├── DisjointSet.cs │ │ └── Node.cs │ ├── Fenwick/ │ │ └── BinaryIndexedTree.cs │ ├── GlobalUsings.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 ├── DataStructures.Tests/ │ ├── AATreeTests.cs │ ├── AVLTreeTests.cs │ ├── BTreeTests.cs │ ├── BagTests.cs │ ├── BinarySearchTreeTests.cs │ ├── BitArrayTests.cs │ ├── Cache/ │ │ ├── LfuCacheTests.cs │ │ └── LruCacheTests.cs │ ├── DataStructures.Tests.csproj │ ├── Deque/ │ │ └── DequeTests.cs │ ├── DisjointSet/ │ │ └── DisjointSetTests.cs │ ├── Fenwick/ │ │ └── BinaryIndexedTreeTests.cs │ ├── GlobalUsings.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 ├── LICENSE ├── README.md ├── Utilities/ │ ├── Exceptions/ │ │ └── ItemNotFoundException.cs │ ├── Extensions/ │ │ ├── DictionaryExtensions.cs │ │ ├── MatrixExtensions.cs │ │ ├── RandomExtensions.cs │ │ └── VectorExtensions.cs │ ├── GlobalUsings.cs │ └── Utilities.csproj ├── Utilities.Tests/ │ ├── Extensions/ │ │ ├── DictionaryExtensionsTests.cs │ │ ├── MatrixExtensionsTests.cs │ │ ├── RandomExtensionsTests.cs │ │ └── VectorExtensionsTests.cs │ ├── GlobalUsings.cs │ └── Utilities.Tests.csproj ├── stylecop.json └── stylecop.ruleset
Showing preview only (286K chars total). Download the full file or copy to clipboard to get everything.
SYMBOL INDEX (3248 symbols across 598 files)
FILE: Algorithms.Tests/Compressors/BurrowsWheelerTransformTests.cs
class BurrowsWheelerTransformTests (line 5) | public class BurrowsWheelerTransformTests
method Encode (line 7) | [TestCase("banana", "nnbaaa", 3)]
method Decode (line 20) | [TestCase("nnbaaa", 3, "banana")]
method RandomEncodeDecode (line 32) | [Test]
FILE: Algorithms.Tests/Compressors/HuffmanCompressorTests.cs
class HuffmanCompressorTests (line 6) | public static class HuffmanCompressorTests
method CompressingPhrase (line 8) | [TestCase("This is a string", "101010110111011101110111100011111010010...
method DecompressedTextTheSameAsOriginal (line 29) | [Test]
method ListNodeComparer_NullIsUnordered (line 48) | [Test]
FILE: Algorithms.Tests/Compressors/ShannonFanoCompressorTests.cs
class ShannonFanoCompressorTests (line 6) | public static class ShannonFanoCompressorTests
method CompressingPhrase (line 8) | [TestCase("dddddddddd", "1111111111")]
method DecompressedTextTheSameAsOriginal (line 27) | [Test]
FILE: Algorithms.Tests/Compressors/TranslatorTests.cs
class TranslatorTests (line 5) | public static class TranslatorTests
method TranslateCorrectly (line 7) | [Test]
FILE: Algorithms.Tests/Crypto/Digests/AsconDigestTests.cs
class AsconDigestTests (line 6) | [NonParallelizable]
method AsconHash_ReturnsCorrectValue (line 12) | [TestCase("a", "02a9d471afab12914197af7090f00d16c41b6e30be0a63bbfd00bc...
method AsconHashA_ReturnsCorrectValue (line 27) | [TestCase("a", "062bb0346671da00da4f460308b4d2c4d9877c3e2827d6229ff536...
method BlockUpdate_WithValidOffsetAndLength_ShouldProcessCorrectly (line 42) | [Test]
method BlockUpdate_WithInvalidOffset_ShouldThrowDataLengthException (line 62) | [Test]
method BlockUpdate_WithInvalidLength_ShouldThrowDataLengthException (line 78) | [Test]
method BlockUpdate_WithPartialBlock_ShouldProcessCorrectly (line 94) | [Test]
method BlockUpdate_WithFullBlock_ShouldProcessCorrectly (line 111) | [Test]
method BlockUpdate_MultipleCalls_ShouldProcessCorrectly (line 128) | [Test]
method AsconHash_WhenGetNameIsCalled_ReturnsCorrectValue (line 145) | [Test]
method AsconHash_WhenGetByteLengthIsCalled_ReturnsCorrectValue (line 152) | [Test]
method Update_ShouldProcessByte_WhenBufferIsFull (line 158) | [Test]
method Update_ShouldNotProcess_WhenBufferIsNotFull (line 177) | [Test]
method Update_ShouldProcessMultipleBlocks (line 197) | [Test]
method Update_ShouldHandleSingleByteCorrectly (line 216) | [Test]
method Update_ShouldAccumulateStateWithMultipleUpdates (line 232) | [Test]
method ToHexString (line 258) | private static string ToHexString(byte[] bytes)
FILE: Algorithms.Tests/Crypto/Digests/Md2DigestTests.cs
class Md2DigestTests (line 5) | [NonParallelizable]
method Digest_ReturnsCorrectValue (line 10) | [TestCase("", "8350E5A3E24C153DF2275C9F80692773")]
FILE: Algorithms.Tests/Crypto/Exceptions/CryptoExceptionTests.cs
class CryptoExceptionTests (line 5) | [TestFixture]
method CryptoException_ShouldBeCreatedWithoutMessageOrInnerException (line 8) | [Test]
method CryptoException_ShouldSetMessage (line 21) | [Test]
method CryptoException_ShouldSetMessageAndInnerException (line 37) | [Test]
method CryptoException_MessageShouldNotBeNullWhenUsingDefaultConstructor (line 54) | [Test]
FILE: Algorithms.Tests/Crypto/Exceptions/DataLengthExceptionTests.cs
class DataLengthExceptionTests (line 5) | [TestFixture]
method DataLengthException_ShouldBeCreatedWithoutMessageOrInnerException (line 8) | [Test]
method DataLengthException_ShouldSetMessage (line 21) | [Test]
method DataLengthException_ShouldSetMessageAndInnerException (line 37) | [Test]
method DataLengthException_MessageShouldNotBeNullWhenUsingDefaultConstructor (line 54) | [Test]
FILE: Algorithms.Tests/Crypto/Exceptions/OutputLengthExceptionTests.cs
class OutputLengthExceptionTests (line 5) | [TestFixture]
method OutputLengthException_ShouldBeCreatedWithoutMessageOrInnerException (line 8) | [Test]
method OutputLengthException_ShouldSetMessage (line 21) | [Test]
method OutputLengthException_ShouldSetMessageAndInnerException (line 37) | [Test]
method OutputLengthException_MessageShouldNotBeNullWhenUsingDefaultConstructor (line 54) | [Test]
FILE: Algorithms.Tests/Crypto/Paddings/Iso10126D2PaddingTests.cs
class Iso10126D2PaddingTests (line 5) | public class Iso10126D2PaddingTests
method AddPadding_WhenInputOffsetIsLessThanInputDataLength_ShouldNotThrowException (line 9) | [Test]
method AddPadding_WhenInputOffsetIsEqualToInputDataLength_ShouldThrowException (line 20) | [Test]
method AddPadding_WhenInputOffsetIsGreaterThanInputDataLength_ShouldThrowException (line 32) | [Test]
method AddPadding_WhenInputArrayIsValid_ShouldReturnCorrectPaddingSize (line 44) | [Test]
method RemovePadding_WhenLengthIsLessThanOne_ShouldThrowATantrum (line 55) | [Test]
method RemovePadding_WhenPaddingLengthIsGreaterThanInputDataLength_ShouldThrowAnException (line 66) | [Test]
method RemovePadding_WhenInputDataIsValid_ShouldReturnCorrectData (line 77) | [Test]
method GetPaddingCount_WhenInputIsNull_ShouldThrowAnException (line 88) | [Test]
method GetPaddingCount_WhenPaddingBlockIsCorrupted_ShouldThrowAnException (line 99) | [Test]
method GetPaddingCount_WhenInputDataIsValid_ShouldReturnCorrectPaddingCount (line 110) | [Test]
FILE: Algorithms.Tests/Crypto/Paddings/Iso7816D4PaddingTests.cs
class Iso7816D4PaddingTests (line 5) | public class Iso7816D4PaddingTests
method AddPadding_WhenCalledWithValidInput_ShouldReturnCorrectPadding (line 9) | [Test]
method AddPadding_WhenCalledWithInvalidInput_ShouldThrowArgumentException (line 22) | [Test]
method AddPadding_WhenCalledWithZeroOffset_ShouldReturnCorrectPadding (line 34) | [Test]
method AddPadding_WhenCalledWithOffsetEqualToLength_ShouldThrowArgumentException (line 47) | [Test]
method AddPadding_WhenCalledWithEmptyArray_ShouldThrowArgumentException (line 59) | [Test]
method RemovePadding_WhenCalledWithValidInput_shouldReturnCorrectData (line 71) | [Test]
method RemovePadding_WhenCalledWithInvalidInput_ShouldThrowArgumentException (line 81) | [Test]
method RemovePadding_WhenCalledWithArrayContainingOnlyPadding_ShouldReturnEmptyArray (line 92) | [Test]
method RemovePadding_WhenCalledWithArrayNotContainingStartOfPadding_ShouldThrowArgumentException (line 102) | [Test]
method GetPaddingCount_WhenCalledWithValidInput_ShouldReturnCorrectCount (line 113) | [Test]
method GetPaddingCount_WhenCalledWithInvalidInput_ShouldThrowArgumentException (line 123) | [Test]
method GetPaddingCount_WhenCalledWithEmptyArray_ShouldThrowArgumentException (line 134) | [Test]
method GetPaddingCount_WhenCalledWithArrayContainingOnlyPadding_ShouldReturnCorrectCount (line 145) | [Test]
method GetPaddingCount_WhenCalledWithArrayNotContainingStartOfPadding_ShouldThrowAnException (line 155) | [Test]
FILE: Algorithms.Tests/Crypto/Paddings/Pkcs7PaddingTests.cs
class Pkcs7PaddingTests (line 5) | public class Pkcs7PaddingTests
method Constructor_WhenBlockSizeIsLessThanOne_ShouldThrowArgumentOutOfRangeException (line 9) | [Test]
method Constructor_WhenBlockSizeIsMoreThan255_ShouldThrowArgumentOutOfRangeException (line 20) | [Test]
method Constructor_WhenBlockSizeIsWithinValidRange_ShouldNotThrowAFit (line 31) | [Test]
method AddPadding_WhenNotEnoughSpaceInInputArrayForPadding_ShouldThrowArgumentException (line 41) | [Test]
method AddPadding_WhenInputArrayHasEnoughSpace_ShouldReturnCorrectPaddingSize (line 55) | [Test]
method AddPadding_WhenAppliedToAnInputArray_ShouldAddCorrectPKCS7Padding (line 68) | [Test]
method RemovePadding_WhenAppliedToAValidInputArray_ShouldRemovePKCS7PaddingCorrectly (line 84) | [Test]
method RemovePadding_WhenInputLengthNotMultipleOfBlockSize_ShouldThrowArgumentException (line 101) | [Test]
method RemovePadding_WhenInvalidPaddingLength_ShouldThrowArgumentException (line 113) | [Test]
method RemovePadding_WhenInvalidPadding_ShouldThrowArgumentException (line 126) | [Test]
method GetPaddingCount_WhenArrayIsNull_ShouldThrowArgumentNullException (line 141) | [Test]
method GetPaddingCount_WhenInputArrayIsValid_ShouldReturnCorrectPaddingCount (line 151) | [Test]
method GetPaddingCount_WhenInvalidPadding_ShouldThrowArgumentException (line 169) | [Test]
FILE: Algorithms.Tests/Crypto/Paddings/TbcPaddingTests.cs
class TbcPaddingTests (line 5) | public class TbcPaddingTests
method AddPadding_WhenInputOffsetIsZero_ShouldPadWithLastBit (line 9) | [Test]
method AddPadding_WhenInputOffsetIsPositive_ShouldPadWithPreviousBit (line 21) | [Test]
method AddPadding_WhenInputOffsetIsGreaterThanLength_ShouldThrowArgumentException (line 33) | [Test]
method AddPadding_WhenLastBitIsZero_ShouldPadWith0xFF (line 45) | [Test]
method AddPadding_WhenLastBitIsOne_ShouldPadWith0x00 (line 57) | [Test]
method RemovePadding_WhenCalledWithPaddedData_ShouldReturnUnpaddedData (line 69) | [Test]
method RemovePadding_WhenCalledWithUnpaddedData_ShouldReturnsSameData (line 80) | [Test]
method RemovePadding_WhenCalledWithEmptyArray_ShouldReturnEmptyArray (line 90) | [Test]
method RemovePadding_WhenCalledWithSingleBytePaddedData_ShouldReturnEmptyArray (line 100) | [Test]
method RemovePadding_WhenCalledWitAllBytesPadded_ShouldReturnEmptyArray (line 110) | [Test]
method GetPaddingBytes_WhenCalledWithPaddedData_ShouldReturnCorrectPaddingCount (line 121) | [Test]
method GetPaddingBytes_WhenCalledWithUnpaddedData_ShouldReturnZero (line 133) | [Test]
method GetPaddingBytes_WhenCalledWithEmptyArray_ShouldReturnZero (line 144) | [Test]
FILE: Algorithms.Tests/Crypto/Paddings/X932PaddingTests.cs
class X932PaddingTests (line 5) | public class X932PaddingTests
method AddPadding_WhenCalledWithZeroPadding_ShouldReturnCorrectCode (line 10) | [Test]
method AddPadding_WhenCalledWithZeroPaddingAndOffsetIsEqualToDataLength_ShouldThrowArgumentException (line 21) | [Test]
method AddPadding_WhenCalledWithZeroPaddingAndOffsetIsGreaterThanDataLength_ShouldThrowArgumentException (line 33) | [Test]
method AddPadding_WhenCalledWithRandomPadding_ShouldReturnCorrectCode (line 46) | [Test]
method AddPadding_WhenCalledWithRandomPaddingAndOffsetIsEqualToDataLength_ShouldThrowArgumentException (line 57) | [Test]
method AddPadding_WhenCalledWithRandomPaddingAndOffsetIsGreaterThanDataLength_ShouldThrowArgumentException (line 69) | [Test]
method AddPadding_WhenCalledWithZeroPaddingAndOffsetIsZero_ShouldReturnLengthOfInputData (line 81) | [Test]
method AddPadding_WhenCalledWithRandomPaddingAndOffsetIsZero_ShouldReturnLengthOfInputData (line 92) | [Test]
method AddPadding_WhenCalledWithRandomPadding_ShouldFillThePaddingWithRandomValues (line 103) | [Test]
method RemovePadding_WhenCalledInEmptyArray_ShouldReturnAnEmptyArray (line 119) | [Test]
method RemovePadding_WhenCalledOnArrayWithValidPadding_ShouldRemovePadding (line 127) | [Test]
method RemovePadding_WithInvalidPadding_ThrowsArgumentException (line 138) | [Test]
method GetPaddingCount_WithValidPadding_ReturnsCorrectCount (line 149) | [Test]
method GetPaddingCount_WithInvalidPadding_ThrowsArgumentException (line 159) | [Test]
FILE: Algorithms.Tests/Crypto/Utils/ByteEncodingUtils.cs
class ByteEncodingUtilsTests (line 5) | [TestFixture]
method BigEndianToUint64_ByteArray_ShouldConvertCorrectly (line 8) | [Test]
method BigEndianToUint64_ByteArray_WithOffset_ShouldConvertCorrectly (line 22) | [Test]
method BigEndianToUint64_Span_ShouldConvertCorrectly (line 36) | [Test]
method UInt64ToBigEndian_ShouldWriteCorrectly (line 50) | [Test]
method BigEndianToUint64_InvalidOffset_ShouldThrowException (line 65) | [Test]
FILE: Algorithms.Tests/Crypto/Utils/LongUtilsTests.cs
class LongUtilsTests (line 5) | [TestFixture]
method RotateLeft_Long_ShouldRotateCorrectly (line 8) | [Test]
method RotateLeft_Ulong_ShouldRotateCorrectly (line 23) | [Test]
method RotateRight_Long_ShouldRotateCorrectly (line 38) | [Test]
method RotateRight_Ulong_ShouldRotateCorrectly (line 53) | [Test]
method RotateLeft_Long_ShouldHandleZeroRotation (line 68) | [Test]
method RotateRight_Ulong_ShouldHandleFullRotation (line 82) | [Test]
FILE: Algorithms.Tests/Crypto/Utils/ValidationUtilsTests.cs
class ValidationUtilsTests (line 6) | [TestFixture]
method CheckDataLength_WithBufferOutOfBounds_ShouldThrowDataLengthException (line 9) | [Test]
method CheckOutputLength_WithCondition_ShouldThrowOutputLengthException (line 26) | [Test]
method CheckOutputLength_WithCondition_ShouldNotThrowOutputLengthException (line 41) | [Test]
method CheckOutputLength_WithBufferOutOfBounds_ShouldThrowOutputLengthException (line 55) | [Test]
method CheckOutputLength_WithBProperBufferSize_ShouldThrowOutputLengthException (line 72) | [Test]
method CheckOutputLength_SpanExceedsLimit_ShouldThrowOutputLengthException (line 88) | [Test]
method CheckOutputLength_SpanDoesNotExceedLimit_ShouldThrowOutputLengthException (line 105) | [Test]
FILE: Algorithms.Tests/Encoders/AutokeyEncoderTests.cs
class AutokeyEncoderTests (line 5) | public static class AutokeyEncoderTests
method DecodedStringIsTheSame (line 7) | [Test]
FILE: Algorithms.Tests/Encoders/BlowfishEncoderTests.cs
class BlowfishEncoderTests (line 7) | public class BlowfishEncoderTests
method BlowfishEncoder_Encryption_ShouldWorkCorrectly (line 11) | [Test]
method BlowfishEncoder_Decryption_ShouldWorkCorrectly (line 28) | [Test]
FILE: Algorithms.Tests/Encoders/CaesarEncoderTests.cs
class CaesarEncoderTests (line 5) | public static class CaesarEncoderTests
method DecodedStringIsTheSame (line 7) | [Test]
FILE: Algorithms.Tests/Encoders/FeistelCipherTest.cs
class FeistelCipherTests (line 5) | public static class FeistelCipherTests
method DecodedStringIsTheSame (line 7) | [Test]
method TestEncodedMessageSize (line 26) | [TestCase("00001111", (uint)0x12345678)]
FILE: Algorithms.Tests/Encoders/HillEnconderTests.cs
class HillEnconderTests (line 5) | public static class HillEnconderTests
method DecodedStringIsTheSame (line 7) | [Test]
FILE: Algorithms.Tests/Encoders/NysiisEncoderTests.cs
class NysiisEncoderTests (line 5) | public class NysiisEncoderTests
method AttemptNysiis (line 21) | [TestCaseSource(nameof(TestData))]
FILE: Algorithms.Tests/Encoders/SoundexEncoderTest.cs
class SoundexEncoderTest (line 5) | public static class SoundexEncoderTest
method AttemptSoundex (line 16) | [TestCaseSource(nameof(TestData))]
FILE: Algorithms.Tests/Encoders/VigenereEncoderTests.cs
class VigenereEncoderTests (line 5) | public static class VigenereEncoderTests
method DecodedStringIsTheSame (line 7) | [Test]
method Encode_KeyIsTooShort_KeyIsAppended (line 25) | [Test]
method EmptyKeyThrowsException (line 41) | [Test]
FILE: Algorithms.Tests/Financial/PresentValueTests.cs
class PresentValueTests (line 5) | public static class PresentValueTests
method Present_Value_General_Tests (line 7) | [TestCase(0.13, new[] { 10.0, 20.70, -293.0, 297.0 }, 4.69)]
method Present_Value_Exception_Tests (line 19) | [TestCase(-1.0, new[] { 10.0, 20.70, -293.0, 297.0 })]
FILE: Algorithms.Tests/Graph/ArticulationPointsTests.cs
class ArticulationPointsTests (line 10) | public class ArticulationPointsTests
method Find_SimpleChain_ReturnsMiddleVertex (line 12) | [Test]
method Find_Triangle_ReturnsEmpty (line 33) | [Test]
method Find_StarGraph_ReturnsCenterVertex (line 53) | [Test]
method Find_BridgeGraph_ReturnsMultiplePoints (line 75) | [Test]
method Find_DisconnectedGraph_FindsPointsInEachComponent (line 100) | [Test]
method Find_SingleVertex_ReturnsEmpty (line 124) | [Test]
method Find_TwoVertices_ReturnsEmpty (line 138) | [Test]
method Find_ComplexGraph_ReturnsCorrectPoints (line 157) | [Test]
method Find_EmptyGraph_ReturnsEmpty (line 181) | [Test]
method Find_NullVertices_ThrowsArgumentNullException (line 195) | [Test]
method Find_NullGetNeighbors_ThrowsArgumentNullException (line 205) | [Test]
method IsArticulationPoint_ValidPoint_ReturnsTrue (line 218) | [Test]
method IsArticulationPoint_NotArticulationPoint_ReturnsFalse (line 238) | [Test]
method Count_SimpleChain_ReturnsOne (line 258) | [Test]
method Count_Triangle_ReturnsZero (line 278) | [Test]
method Find_LargeGraph_FindsAllPoints (line 298) | [Test]
FILE: Algorithms.Tests/Graph/BellmanFordTests.cs
class BellmanFordTests (line 6) | public class BellmanFordTests
method CorrectDistancesTest (line 8) | [Test]
method NegativeWeightCycleTest (line 51) | [Test]
FILE: Algorithms.Tests/Graph/BipartiteGraphTests.cs
class BipartiteGraphTests (line 10) | public class BipartiteGraphTests
method IsBipartite_EmptyGraph_ReturnsTrue (line 12) | [Test]
method IsBipartite_SingleVertex_ReturnsTrue (line 26) | [Test]
method IsBipartite_TwoVerticesConnected_ReturnsTrue (line 40) | [Test]
method IsBipartite_Triangle_ReturnsFalse (line 59) | [Test]
method IsBipartite_Square_ReturnsTrue (line 79) | [Test]
method IsBipartite_CompleteBipartiteK23_ReturnsTrue (line 100) | [Test]
method IsBipartite_DisconnectedBipartiteComponents_ReturnsTrue (line 122) | [Test]
method IsBipartite_DisconnectedWithOddCycle_ReturnsFalse (line 143) | [Test]
method IsBipartite_StarGraph_ReturnsTrue (line 165) | [Test]
method IsBipartite_Pentagon_ReturnsFalse (line 186) | [Test]
method IsBipartite_NullVertices_ThrowsArgumentNullException (line 208) | [Test]
method IsBipartite_NullGetNeighbors_ThrowsArgumentNullException (line 218) | [Test]
method GetPartitions_BipartiteGraph_ReturnsCorrectSets (line 231) | [Test]
method GetPartitions_NonBipartiteGraph_ReturnsNull (line 254) | [Test]
method GetPartitions_EmptyGraph_ReturnsEmptySets (line 274) | [Test]
method GetPartitions_NullVertices_ThrowsArgumentNullException (line 290) | [Test]
method GetPartitions_NullGetNeighbors_ThrowsArgumentNullException (line 300) | [Test]
method IsBipartiteDfs_BipartiteGraph_ReturnsTrue (line 313) | [Test]
method IsBipartiteDfs_NonBipartiteGraph_ReturnsFalse (line 334) | [Test]
method IsBipartiteDfs_NullVertices_ThrowsArgumentNullException (line 354) | [Test]
method IsBipartiteDfs_NullGetNeighbors_ThrowsArgumentNullException (line 364) | [Test]
method IsBipartite_LargeEvenCycle_ReturnsTrue (line 377) | [Test]
method IsBipartite_LargeOddCycle_ReturnsFalse (line 400) | [Test]
method GetPartitions_CompleteBipartite_ReturnsCorrectSets (line 423) | [Test]
FILE: Algorithms.Tests/Graph/BreadthFirstSearchTests.cs
class BreadthFirstSearchTests (line 6) | public class BreadthFirstSearchTests
method VisitAll_ShouldCountNumberOfVisitedVertix_ResultShouldBeTheSameAsNumberOfVerticesInGraph (line 8) | [Test]
method VisitAll_ShouldCountNumberOfVisitedVerices_TwoSeparatedGraphInOne (line 41) | [Test]
method VisitAll_ReturnTheSuqenceOfVertices_ShouldBeTheSameAsExpected (line 84) | [Test]
FILE: Algorithms.Tests/Graph/BreadthFirstTreeTraversalTests.cs
class BreadthFirstTreeTraversalTests (line 6) | public static class BreadthFirstTreeTraversalTests
method CorrectLevelOrderTraversal (line 8) | [Test]
method EmptyArrayForNullRoot (line 27) | [Test]
method IncorrectLevelOrderTraversal (line 40) | [TestCase(new[] { 7, 9, 5 })]
method DeepestNodeInTree (line 58) | [Test]
method DeepestNodeOfEmptyTree (line 76) | [Test]
FILE: Algorithms.Tests/Graph/BridgesTests.cs
class BridgesTests (line 10) | public class BridgesTests
method Find_SimpleChain_ReturnsAllEdges (line 12) | [Test]
method Find_Triangle_ReturnsEmpty (line 33) | [Test]
method Find_TwoComponentsConnectedByBridge_ReturnsBridge (line 53) | [Test]
method Find_StarGraph_ReturnsAllEdges (line 78) | [Test]
method Find_DisconnectedGraph_FindsBridgesInEachComponent (line 100) | [Test]
method Find_SingleVertex_ReturnsEmpty (line 124) | [Test]
method Find_TwoVertices_ReturnsBridge (line 138) | [Test]
method Find_ComplexGraph_ReturnsCorrectBridges (line 158) | [Test]
method Find_EmptyGraph_ReturnsEmpty (line 182) | [Test]
method Find_NullVertices_ThrowsArgumentNullException (line 196) | [Test]
method Find_NullGetNeighbors_ThrowsArgumentNullException (line 206) | [Test]
method IsBridge_ValidBridge_ReturnsTrue (line 219) | [Test]
method IsBridge_ReverseEdge_ReturnsTrue (line 239) | [Test]
method IsBridge_NotBridge_ReturnsFalse (line 259) | [Test]
method Count_SimpleChain_ReturnsTwo (line 279) | [Test]
method Count_Triangle_ReturnsZero (line 299) | [Test]
method Find_LargeChain_FindsAllBridges (line 319) | [Test]
FILE: Algorithms.Tests/Graph/DepthFirstSearchTests.cs
class DepthFirstSearchTests (line 6) | public class DepthFirstSearchTests
method VisitAll_ShouldCountNumberOfVisitedVertix_ResultShouldBeTheSameAsNumberOfVerticesInGraph (line 8) | [Test]
method VisitAll_ShouldCountNumberOfVisitedVertices_TwoSeparatedGraphInOne (line 41) | [Test]
method VisitAll_ReturnTheSuqenceOfVertices_ShouldBeTheSameAsExpected (line 84) | [Test]
FILE: Algorithms.Tests/Graph/Dijkstra/DijkstraTests.cs
class DijkstraTests (line 6) | [TestFixture]
method DijkstraTest1_Success (line 9) | [Test]
method DijkstraTest2_Success (line 76) | [Test]
method DijkstraTest3_Success (line 115) | [Test]
method DijkstraTest4_Success (line 151) | [Test]
method DijkstraTest5_Success (line 197) | [Test]
method DijkstraTest6_Success (line 284) | [Test]
method DijkstraMethodTest_ShouldThrow_GraphIsNull (line 327) | [Test]
method DijkstraMethodTest_ShouldThrow_VertexDoesntBelongToGraph (line 339) | [Test]
FILE: Algorithms.Tests/Graph/FloydWarshallTests.cs
class FloydWarshallTests (line 6) | public class FloydWarshallTests
method CorrectMatrixTest (line 8) | [Test]
FILE: Algorithms.Tests/Graph/KosarajuTests.cs
class KosarajuTests (line 6) | public class KosarajuTests
method GetRepresentativesTest (line 9) | [Test]
method GetSccTest (line 59) | [Test]
FILE: Algorithms.Tests/Graph/MinimumSpanningTree/KruskalTests.cs
class KruskalTests (line 5) | internal class KruskalTests
method ValidateGraph_adjWrongSize_ThrowsException (line 7) | [Test]
method ValidateGraph_adjDirectedGraph_ThrowsException (line 32) | [Test]
method Solve_adjGraph1_CorrectAnswer (line 47) | [Test]
method Solve_adjGraph2_CorrectAnswer (line 81) | [Test]
method Solve_adjGraph3_CorrectAnswer (line 127) | [Test]
method Solve_adjGraph4_CorrectAnswer (line 167) | [Test]
method Solve_adjGraph5_CorrectAnswer (line 217) | [Test]
method Solve_adjGraph6_CorrectAnswer (line 361) | [Test]
method ValidateGraph_ListDirectedGraph_ThrowsException (line 411) | [Test]
method Solve_ListGraph1_CorrectAnswer (line 425) | [Test]
method Solve_ListGraph2_CorrectAnswer (line 463) | [Test]
method Solve_ListGraph3_CorrectAnswer (line 513) | [Test]
method Solve_ListGraph4_CorrectAnswer (line 557) | [Test]
method Solve_ListGraph5_CorrectAnswer (line 611) | [Test]
method Solve_ListGraph6_CorrectAnswer (line 669) | [Test]
FILE: Algorithms.Tests/Graph/MinimumSpanningTree/PrimMatrixTests.cs
class PrimTests (line 5) | internal class PrimTests
method ValidateMatrix_WrongSize_ThrowsException (line 7) | [Test]
method ValidateMatrix_UnconnectedGraph_ThrowsException (line 32) | [Test]
method ValidateMatrix_DirectedGraph_ThrowsException (line 47) | [Test]
method SolveMatrix_Graph1_CorrectAnswer (line 62) | [Test]
method SolveMatrix_Graph2_CorrectAnswer (line 99) | [Test]
method SolveMatrix_Graph3_CorrectAnswer (line 148) | [Test]
method SolveMatrix_Graph4_CorrectAnswer (line 191) | [Test]
method SolveMatrix_Graph5_CorrectAnswer (line 244) | [Test]
FILE: Algorithms.Tests/Graph/TarjanStronglyConnectedComponentsTests.cs
class TarjanStronglyConnectedComponentsTests (line 8) | public class TarjanStronglyConnectedComponentsTests
method FindSCCs_SimpleGraph_ReturnsCorrectSCCs (line 10) | [Test]
method FindSCCs_TwoSeparateSCCs_ReturnsBothSCCs (line 24) | [Test]
method FindSCCs_DisconnectedVertices_EachVertexIsSCC (line 38) | [Test]
method FindSCCs_ComplexGraph_ReturnsCorrectSCCs (line 49) | [Test]
method GetSccCount_AfterFindingSCCs_ReturnsCorrectCount (line 69) | [Test]
method InSameScc_VerticesInSameScc_ReturnsTrue (line 85) | [Test]
method InSameScc_VerticesInDifferentSccs_ReturnsFalse (line 98) | [Test]
method GetScc_ValidVertex_ReturnsSccContainingVertex (line 111) | [Test]
method BuildCondensationGraph_ComplexGraph_ReturnsDAG (line 126) | [Test]
method AddEdge_InvalidVertex_ThrowsException (line 144) | [Test]
method FindSCCs_SingleVertex_ReturnsSingleSCC (line 154) | [Test]
method FindSCCs_LinearChain_EachVertexIsSCC (line 165) | [Test]
method FindSCCs_SelfLoop_VertexIsSCC (line 178) | [Test]
FILE: Algorithms.Tests/Graph/TopologicalSortTests.cs
class TopologicalSortTests (line 6) | public class TopologicalSortTests
method Sort_SimpleLinearGraph_ReturnsCorrectOrder (line 12) | [Test]
method SortKahn_SimpleLinearGraph_ReturnsCorrectOrder (line 40) | [Test]
method Sort_GraphWithMultipleValidOrderings_ReturnsValidOrder (line 71) | [Test]
method SortKahn_GraphWithMultipleValidOrderings_ReturnsValidOrder (line 107) | [Test]
method Sort_ComplexDAG_ReturnsValidOrder (line 143) | [Test]
method SortKahn_ComplexDAG_ReturnsValidOrder (line 185) | [Test]
method Sort_GraphWithCycle_ThrowsInvalidOperationException (line 225) | [Test]
method SortKahn_GraphWithCycle_ThrowsInvalidOperationException (line 249) | [Test]
method Sort_SingleVertexGraph_ReturnsSingleVertex (line 273) | [Test]
method SortKahn_SingleVertexGraph_ReturnsSingleVertex (line 295) | [Test]
method Sort_DisconnectedDAG_ReturnsValidOrder (line 319) | [Test]
method SortKahn_DisconnectedDAG_ReturnsValidOrder (line 358) | [Test]
method Sort_CoursePrerequisitesScenario_ReturnsValidOrder (line 398) | [Test]
method SortKahn_CoursePrerequisitesScenario_ReturnsValidOrder (line 441) | [Test]
method Sort_IntegerVertices_ReturnsCorrectOrder (line 481) | [Test]
method SortKahn_IntegerVertices_ReturnsCorrectOrder (line 510) | [Test]
method Sort_GraphWithSelfLoop_ThrowsInvalidOperationException (line 539) | [Test]
method SortKahn_GraphWithSelfLoop_ThrowsInvalidOperationException (line 559) | [Test]
FILE: Algorithms.Tests/Helpers/IntComparer.cs
class IntComparer (line 3) | internal class IntComparer : IComparer<int>
method Compare (line 5) | public int Compare(int x, int y) => x.CompareTo(y);
FILE: Algorithms.Tests/Helpers/RandomHelper.cs
class RandomHelper (line 3) | internal static class RandomHelper
method GetArrays (line 5) | public static (int[] correctArray, int[] testArray) GetArrays(int n)
method GetStringArrays (line 20) | public static (string[] correctArray, string[] testArray) GetStringArr...
FILE: Algorithms.Tests/Knapsack/BranchAndBoundKnapsackSolverTests.cs
class BranchAndBoundKnapsackSolverTests (line 5) | public static class BranchAndBoundKnapsackSolverTests
method BranchAndBoundTest_Example1_Success (line 7) | [Test]
method BranchAndBoundTest_Example2_Success (line 28) | [Test]
method BranchAndBoundTest_CapacityIsZero_NothingTaken (line 49) | [Test]
method BranchAndBoundTest_PlentyCapacity_EverythingIsTaken (line 70) | [Test]
method BranchAndBoundTest_NoItems_NothingTaken (line 91) | [Test]
FILE: Algorithms.Tests/Knapsack/DynamicProgrammingKnapsackSolverTests.cs
class DynamicProgrammingKnapsackSolverTests (line 5) | public static class DynamicProgrammingKnapsackSolverTests
method SmallSampleOfChar (line 7) | [Test]
method FSU_P01 (line 31) | [Test]
method FSU_P07_WithNonIntegralValues (line 56) | [Test]
method TakesHalf (line 84) | [Test]
FILE: Algorithms.Tests/Knapsack/NaiveKnapsackSolverTests.cs
class NaiveKnapsackSolverTests (line 5) | public static class NaiveKnapsackSolverTests
method TakesHalf (line 7) | [Test]
FILE: Algorithms.Tests/LinearAlgebra/Distances/ChebyshevTests.cs
class ChebyshevTests (line 5) | public class ChebyshevTests
method DistanceTest (line 7) | [TestCase(new[] { 1.0, 1.0 }, new[] { 2.0, 2.0 }, 1.0)]
method DistanceThrowsArgumentExceptionOnDifferentPointDimensions (line 16) | [TestCase(new[] { 2.0, 3.0 }, new[] { -1.0 })]
FILE: Algorithms.Tests/LinearAlgebra/Distances/EuclideanTests.cs
class EuclideanTests (line 5) | public static class EuclideanTests
method DistanceTest (line 13) | [TestCase(new[] { 1.5 }, new[] { -1.0 }, 2.5)]
method DistanceThrowsArgumentExceptionOnDifferentPointDimensions (line 25) | [TestCase(new[] { 7.0, 4.5 }, new[] { -3.0 })]
FILE: Algorithms.Tests/LinearAlgebra/Distances/ManhattanTests.cs
class ManhattanTests (line 5) | public class ManhattanTests
method DistanceTest (line 13) | [TestCase(new[] { 1.5 }, new[] { -1.0 }, 2.5)]
method DistanceThrowsArgumentExceptionOnDifferentPointDimensions (line 27) | [TestCase(new[] { 2.0, 3.0 }, new[] { -1.0 })]
FILE: Algorithms.Tests/LinearAlgebra/Distances/MinkowskiTests.cs
class MinkowskiTests (line 5) | public class MinkowskiTests
method DistanceTest (line 7) | [TestCase(new[] { 2.0, 3.0 }, new[] { -1.0, 5.0 }, 1, 5.0)] // Simulat...
method DistanceThrowsArgumentExceptionOnInvalidInput (line 17) | [TestCase(new[] { 2.0, 3.0 }, new[] { -1.0 }, 2)]
FILE: Algorithms.Tests/LinearAlgebra/Eigenvalue/PowerIterationTests.cs
class PowerIterationTests (line 5) | public class PowerIterationTests
method Dominant_ShouldThrowArgumentException_WhenSourceMatrixIsNotSquareShaped (line 25) | [Test]
method Dominant_ShouldThrowArgumentException_WhenStartVectorIsNotSameSizeAsMatrix (line 38) | [Test]
method Dominant_ShouldCalculateDominantEigenvalueAndEigenvector (line 53) | [TestCaseSource(nameof(DominantVectorTestCases))]
method StartVector (line 68) | private double[] StartVector(int length) => new Random(111111).NextVec...
FILE: Algorithms.Tests/MachineLearning/KNearestNeighborsTests.cs
class KNearestNeighborsTests (line 7) | [TestFixture]
method Constructor_InvalidK_ThrowsException (line 10) | [Test]
method AddSample_NullFeatures_ThrowsException (line 16) | [Test]
method Predict_NoTrainingData_ThrowsException (line 24) | [Test]
method Predict_NullFeatures_ThrowsException (line 31) | [Test]
method EuclideanDistance_DifferentLengths_ThrowsException (line 40) | [Test]
method EuclideanDistance_CorrectResult (line 46) | [Test]
method Predict_SingleNeighbor_CorrectLabel (line 56) | [Test]
method Predict_MajorityVote_CorrectLabel (line 66) | [Test]
method Predict_TieBreaker_ReturnsConsistentLabel (line 77) | [Test]
FILE: Algorithms.Tests/MachineLearning/LinearRegressionTests.cs
class LinearRegressionTests (line 8) | public class LinearRegressionTests
method Fit_ThrowsException_WhenInputIsNull (line 10) | [Test]
method Fit_ThrowsException_WhenInputIsEmpty (line 18) | [Test]
method Fit_ThrowsException_WhenInputLengthsDiffer (line 25) | [Test]
method Fit_ThrowsException_WhenXVarianceIsZero (line 32) | [Test]
method Predict_ThrowsException_IfNotFitted (line 39) | [Test]
method FitAndPredict_WorksForSimpleData (line 47) | [Test]
method FitAndPredict_WorksForNegativeSlope (line 61) | [Test]
method Predict_List_WorksCorrectly (line 74) | [Test]
FILE: Algorithms.Tests/MachineLearning/LogisticRegressionTests.cs
class LogisticRegressionTests (line 7) | [TestFixture]
method Fit_ThrowsOnEmptyInput (line 10) | [Test]
method Fit_ThrowsOnMismatchedLabels (line 17) | [Test]
method FitAndPredict_WorksOnSimpleData (line 26) | [Test]
method PredictProbability_ThrowsOnFeatureMismatch (line 46) | [Test]
method FeatureCount_ReturnsCorrectValue (line 56) | [Test]
FILE: Algorithms.Tests/ModularArithmetic/ChineseRemainderTheoremTest.cs
class ChineseRemainderTheoremTest (line 5) | public static class ChineseRemainderTheoremTest
method TestCompute1 (line 7) | [Test]
method TestCompute2 (line 19) | [Test]
method TestCompute3 (line 31) | [Test]
method TestCompute_RequirementsNotMet_ArgumentLengthDifferent (line 43) | [Test]
method TestCompute_RequirementsNotMet_NTooSmall (line 53) | [Test]
method TestCompute_RequirementsNotMet_ATooSmall (line 66) | [Test]
method TestCompute_RequirementsNotMet_NNotCoprime (line 79) | [Test]
method TestCompute_BigInteger_1 (line 92) | [Test]
method TestCompute_BigInteger_2 (line 107) | [Test]
method TestCompute_BigInteger_3 (line 122) | [Test]
method TestCompute_BigInteger_RequirementsNotMet_ArgumentLengthDifferent (line 137) | [Test]
method TestCompute_BigInteger_RequirementsNotMet_NTooSmall (line 147) | [Test]
method TestCompute_BigInteger_RequirementsNotMet_ATooSmall (line 160) | [Test]
method TestCompute_BigInteger_RequirementsNotMet_NNotCoprime (line 173) | [Test]
FILE: Algorithms.Tests/ModularArithmetic/ExtendedEuclideanAlgorithmTest.cs
class ExtendedEuclideanAlgorithmTest (line 5) | public static class ExtendedEuclideanAlgorithmTest
method TestCompute (line 7) | [TestCase(240, 46, 2, -9, 47)]
method TestCompute_BigInteger (line 29) | [TestCase(240, 46, 2, -9, 47)]
FILE: Algorithms.Tests/ModularArithmetic/ModularMultiplicativeInverseTest.cs
class ModularMultiplicativeInverseTest (line 5) | public static class ModularMultiplicativeInverseTest
method TestCompute (line 7) | [TestCase(2, 3, 2)]
method TestCompute_Irrevertible (line 19) | [TestCase(46, 240)]
method TestCompute_BigInteger (line 34) | [TestCase(2, 3, 2)]
method TestCompute_BigInteger_Irrevertible (line 46) | [TestCase(46, 240)]
FILE: Algorithms.Tests/Numeric/AbsTests.cs
class AbsTests (line 5) | public static class AbsTests
method GetsAbsVal (line 7) | [TestCase(0, 0)]
method GetAbsMax (line 21) | [TestCase(new[] { -3, -1, 2, -11 }, -11)]
method AbsMaxThrowsArgumentException (line 33) | [Test]
method GetAbsMin (line 43) | [TestCase(new[] { -3, -1, 2, -11 }, -1)]
method AbsMinThrowsArgumentException (line 55) | [Test]
FILE: Algorithms.Tests/Numeric/AdditionWithoutArithmeticsTests.cs
class AdditionWithoutArithmeticTests (line 5) | public static class AdditionWithoutArithmeticTests
method CalculateAdditionWithoutArithmetic_Test (line 7) | [TestCase(3, 5, 8)]
FILE: Algorithms.Tests/Numeric/AliquotSumCalculatorTests.cs
class AliquotSumCalculatorTests (line 5) | public static class AliquotSumCalculatorTests
method CalculateSum_SumIsCorrect (line 7) | [TestCase(1, 0)]
method CalculateSum_NegativeInput_ExceptionIsThrown (line 22) | [TestCase(-2)]
FILE: Algorithms.Tests/Numeric/AmicableNumbersTest.cs
class AmicableNumbersTest (line 5) | public static class AmicableNumbersTest
method AmicableNumbersChecker_Test (line 7) | [TestCase(220, 284)]
FILE: Algorithms.Tests/Numeric/AutomorphicNumberTests.cs
class AutomorphicNumberTests (line 5) | public class AutomorphicNumberTests
method TestAutomorphicNumbers (line 7) | [TestCase(1)]
method TestNonAutomorphicNumbers (line 23) | [TestCase(2)]
method TestInvalidAutomorphicNumbers (line 43) | [TestCase(0)]
method TestAutomorphicNumberSequence (line 55) | [TestCase(1, 100)]
method TestNoAutomorphicNumberInTheSequence (line 62) | [TestCase(8, 12)]
method TestAutomorphicNumberSequenceSameBounds (line 69) | [TestCase(25, 25)]
method TestAutomorphicNumberSequenceInvalidLowerBound (line 76) | [TestCase(-1, 1)]
method TestAutomorphicNumberSequenceInvalidUpperBound (line 88) | [TestCase(1, -1)]
method TestAutomorphicNumberSequenceReversedBounds (line 100) | [TestCase(25, 2)]
FILE: Algorithms.Tests/Numeric/BinomialCoefficientTests.cs
class BinomialCoefficientTests (line 5) | public static class BinomialCoefficientTests
method CalculateFromPairs (line 7) | [TestCase(4, 2, 6)]
method TeoremCalculateThrowsException (line 20) | [TestCase(3, 7)]
FILE: Algorithms.Tests/Numeric/CeilTests.cs
class CeilTests (line 5) | public static class CeilTests
method GetsCeilVal (line 7) | [TestCase(0.0, 0)]
FILE: Algorithms.Tests/Numeric/Decomposition/LUTests.cs
class LuTests (line 5) | public class LuTests
method DecomposeIdentityMatrix (line 9) | [Test]
method DecomposeMatrix_Case3X3 (line 26) | [Test]
method DecomposeMatrix_Case4X4 (line 43) | [Test]
method FailOnDecomposeNonSquareMatrix (line 60) | [Test]
method EliminateIdentityEquation (line 73) | [Test]
method EliminateEquation_Case3X3 (line 87) | [Test]
method EliminateEquation_Case4X4 (line 102) | [Test]
method FailOnEliminateEquationWithNonSquareMatrix (line 123) | [Test]
method VectorMembersAreEqual (line 137) | private bool VectorMembersAreEqual(double[] expected, double[] actual) =>
FILE: Algorithms.Tests/Numeric/Decomposition/MaclaurinTests.cs
class MaclaurinTests (line 5) | public class MaclaurinTests
method Exp_TermsForm_ValidCases (line 7) | [TestCase(0.01, 3, 0.01)]
method Exp_TermsForm_InvalidCase (line 22) | [Test]
method Sin_TermsForm_ValidCases (line 26) | [TestCase(0, 1, 0.001)]
method Sin_TermsForm_InvalidCase (line 42) | [Test]
method Cos_TermsForm_ValidCases (line 46) | [TestCase(0, 1, 0.001)]
method Cos_TermsForm_InvalidCase (line 62) | [Test]
method Exp_ErrorForm_ValidCases (line 66) | [TestCase(0.1, 0.001)]
method Exp_ErrorForm_InvalidCases (line 82) | [TestCase(0.0)]
method Sin_ErrorForm_ValidCases (line 87) | [TestCase(0, 0.001)]
method Sin_ErrorForm_InvalidCases (line 103) | [TestCase(0.0)]
method Cos_ErrorForm_ValidCases (line 108) | [TestCase(0, 0.001)]
method Cos_ErrorForm_InvalidCases (line 124) | [TestCase(0.0)]
FILE: Algorithms.Tests/Numeric/Decomposition/SVDTests.cs
class SvdTests (line 5) | public class SvdTests
method RandomUnitVector (line 7) | [Test]
method Svd_Decompose (line 19) | [Test]
method Svd_Random (line 27) | [Test]
method AssertMatrixEqual (line 34) | private void AssertMatrixEqual(double[,] matrix1, double[,] matrix2, d...
method GenerateRandomMatrix (line 47) | private double[,] GenerateRandomMatrix(int m, int n)
method CheckSvd (line 62) | private void CheckSvd(double[,] testMatrix)
FILE: Algorithms.Tests/Numeric/DoubleFactorialTests.cs
class DoubleFactorialTests (line 9) | public static class DoubleFactorialTests
method GetsDoubleFactorial (line 18) | [TestCase(0, "1")] // Base Case: 0!! = 1
method GetsDoubleFactorialExceptionForNegativeNumbers (line 41) | [TestCase(-1)]
FILE: Algorithms.Tests/Numeric/EulerMethodTest.cs
class EulerMethodTest (line 5) | public static class EulerMethodTest
method TestLinearEquation (line 7) | [Test]
method TestExampleWikipedia (line 16) | [Test]
method TestExampleGeeksForGeeks (line 26) | [Test]
method StepsizeIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 44) | [Test]
method StartIsLargerThanEnd_ThrowsArgumentOutOfRangeException (line 51) | [Test]
FILE: Algorithms.Tests/Numeric/FactorialTests.cs
class FactorialTests (line 5) | public static class FactorialTests
method GetsFactorial (line 7) | [TestCase(0, "1")]
method GetsFactorialExceptionForNegativeNumbers (line 24) | [TestCase(-5)]
FILE: Algorithms.Tests/Numeric/Factorization/TrialDivisionFactorizerTests.cs
class TrialDivisionFactorizerTests (line 5) | public static class TrialDivisionFactorizerTests
method PrimeNumberFactorizationFails (line 7) | [TestCase(2)]
method PrimeNumberFactorizationSucceeds (line 23) | [TestCase(4, 2)]
FILE: Algorithms.Tests/Numeric/FloorTests.cs
class FloorTests (line 5) | public static class FloorTests
method GetsFloorVal (line 7) | [TestCase(0.0, 0)]
FILE: Algorithms.Tests/Numeric/GaussJordanEliminationTests.cs
class GaussJordanEliminationTests (line 8) | public static class GaussJordanEliminationTests
method NonSquaredMatrixThrowsException (line 10) | [Test]
method UnableToSolveSingularMatrix (line 24) | [Test]
FILE: Algorithms.Tests/Numeric/GreatestCommonDivisor/BinaryGreatestCommonDivisorFinderTests.cs
class BinaryGreatestCommonDivisorFinderTests (line 5) | public static class BinaryGreatestCommonDivisorFinderTests
method GreatestCommonDivisorCorrect (line 7) | [TestCase(2, 3, 1)]
FILE: Algorithms.Tests/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinderTests.cs
class EuclideanGreatestCommonDivisorFinderTests (line 5) | public static class EuclideanGreatestCommonDivisorFinderTests
method GreatestCommonDivisorCorrect (line 7) | [TestCase(2, 3, 1)]
FILE: Algorithms.Tests/Numeric/JosephusProblemTest.cs
class JosephusProblemTest (line 5) | public class JosephusProblemTest
method JosephusProblemInvalidStepSize (line 8) | [TestCase(10, 0)]
method JosephusProblemStepSizeGreaterThanGroup (line 17) | [TestCase(10, 12)]
method JosephusProblemWinnerCalculation (line 25) | [TestCase(10, 2, 5)]
FILE: Algorithms.Tests/Numeric/KeithNumberTest.cs
class KeithNumberTest (line 5) | public static class KeithNumberTest
method KeithNumberWork (line 7) | [TestCase(14)]
method KeithNumberShouldThrowEx (line 20) | [TestCase(-2)]
FILE: Algorithms.Tests/Numeric/KrishnamurthyNumberCheckerTests.cs
class KrishnamurthyNumberCheckerTests (line 5) | public class KrishnamurthyNumberCheckerTests
method KrishnamurthyNumberCheckerKnownNumbers (line 7) | [TestCase(1)]
method KrishnamurthyNumberCheckerNotKMNumber (line 17) | [TestCase(3)]
FILE: Algorithms.Tests/Numeric/MillerRabinPrimalityTest.cs
class MillerRabinPrimalityTest (line 5) | public static class MillerRabinPrimalityTest
method MillerRabinPrimalityWork (line 7) | [TestCase("7", ExpectedResult = true)] // true
method MillerRabinPrimalityShouldThrowEx (line 31) | [TestCase("-2")]
FILE: Algorithms.Tests/Numeric/ModularExponentiationTest.cs
class ModularExponentiationTest (line 5) | public class ModularExponentiationTest
method ModularExponentiationCorrect (line 7) | [TestCase(3, 6, 11, 3)]
method ModularExponentiationNegativeMod (line 21) | [TestCase(17, 7, -3)]
FILE: Algorithms.Tests/Numeric/NarcissisticNumberTest.cs
class NarcissisticNumberTest (line 5) | public static class NarcissisticNumberTest
method NarcissisticNumberWork (line 7) | [TestCase(2, ExpectedResult = true)]
FILE: Algorithms.Tests/Numeric/NewtonSquareRootTests.cs
class NewtonSquareRootTests (line 3) | public class NewtonSquareRootTests
method CalculateSquareRootTest (line 18) | [TestCaseSource(nameof(CalculateSquareRootInput))]
method CalculateSquareRootOfZero (line 24) | [Test]
method CalculateSquareRootNegativeNumber (line 30) | [Test]
FILE: Algorithms.Tests/Numeric/PerfectCubeTests.cs
class PerfectCubeTests (line 5) | public static class PerfectCubeTests
method IsPerfectCube_ResultIsCorrect (line 7) | [TestCase(-27, ExpectedResult = true)]
method IsPerfectCubeBinarySearch_ResultIsCorrect (line 24) | [TestCase(-27, ExpectedResult = true)]
FILE: Algorithms.Tests/Numeric/PerfectNumberTest.cs
class PerfectNumberTests (line 5) | public static class PerfectNumberTests
method PerfectNumberWork (line 7) | [TestCase(6)]
method PerfectNumberShouldThrowEx (line 22) | [TestCase(-2)]
FILE: Algorithms.Tests/Numeric/PerfectSquareTest.cs
class PerfectSquareTests (line 5) | public static class PerfectSquareTests
method IsPerfectSquare_ResultIsCorrect (line 7) | [TestCase(-4, ExpectedResult = false)]
FILE: Algorithms.Tests/Numeric/PrimeNumberTest.cs
class PrimeNumberTests (line 5) | public static class PrimeNumberTests
method IsPrime_ResultIsCorrect (line 11) | [TestCase(-5, ExpectedResult = false)] // Negative number
FILE: Algorithms.Tests/Numeric/PseudoInverse/PseudoInverseTests.cs
class PseudoInverseTests (line 3) | public static class PseudoInverseTests
method SquaredMatrixInverseWorks (line 5) | [Test]
method NonSquaredMatrixPseudoInverseMatrixWorks (line 23) | [Test]
FILE: Algorithms.Tests/Numeric/ReluTest.cs
class ReluTests (line 7) | [TestFixture]
method ReluFunction_Scalar_ReturnsCorrectValue (line 15) | [TestCase(0.0, 0.0)]
method ReluFunction_Scalar_HandlesLimitsAndNaN (line 26) | [Test]
method ReluFunction_Scalar_ResultIsNonNegative (line 39) | [TestCase(100.0)]
method ReluFunction_Vector_ReturnsCorrectValues (line 50) | [Test]
method ReluFunction_Vector_HandlesLimitsAndNaN (line 61) | [Test]
method ReluFunction_Vector_ThrowsOnNullInput (line 75) | [Test]
method ReluFunction_Vector_ThrowsOnEmptyInput (line 82) | [Test]
FILE: Algorithms.Tests/Numeric/RungeKuttaMethodTest.cs
class RungeKuttaTest (line 5) | public static class RungeKuttaTest
method TestLinearEquation (line 7) | [Test]
method TestExampleFunciton (line 16) | [Test]
method StepsizeIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 25) | [Test]
method StartIsLargerThanEnd_ThrowsArgumentOutOfRangeException (line 32) | [Test]
FILE: Algorithms.Tests/Numeric/SigmoidTests.cs
class SigmoidTests (line 10) | public static class SigmoidTests
method GetsCenterValue (line 19) | [Test]
method GetsAsymptoticValueForLargePositiveX (line 36) | [Test]
method GetsAsymptoticValueForLargeNegativeX (line 54) | [Test]
method GetsStandardSigmoidValues (line 75) | [TestCase(1.0, 0.7310585786300049)]
method HandlesFractionalAndLargeInput (line 93) | [Test]
FILE: Algorithms.Tests/Numeric/SoftMaxTests.cs
class SoftMaxTests (line 5) | public static class SoftMaxTests
method SoftMaxFunction (line 7) | [TestCase(new[] { 5.0, 5.0 }, new[] { 0.5, 0.5 })]
method SoftMaxFunctionThrowsArgumentException (line 19) | [Test]
method SoftMaxFunctionSumsToOne (line 29) | [TestCase(new[] { 1.0, 2.0, 3.0, 4.0, 5.0 })]
FILE: Algorithms.Tests/Numeric/SumOfDigitsTest.cs
class SumOfDigitsTests (line 10) | public static class SumOfDigitsTests
method GetsCorrectSumOfDigits (line 17) | [TestCase(0, 0)]
method ThrowsExceptionForNegativeNumbers (line 38) | [TestCase(-1)]
FILE: Algorithms.Tests/Numeric/TanhTest.cs
class TanhTests (line 7) | [TestFixture]
method TanhFunction_Scalar_ReturnsCorrectValue (line 18) | [TestCase(0.0, 0.0)]
method TanhFunction_Scalar_ApproachesLimits (line 32) | [Test]
method TanhFunction_Scalar_ResultIsBounded (line 43) | [TestCase(100.0)]
method TanhFunction_Vector_ReturnsCorrectValues (line 58) | [Test]
method TanhFunction_Vector_HandlesLimitsAndNaN (line 75) | [Test]
method TanhFunction_Vector_ThrowsOnNullInput (line 93) | [Test]
method TanhFunction_Vector_ThrowsOnEmptyInput (line 103) | [Test]
FILE: Algorithms.Tests/Other/BoyerMooreMajorityVoteTests.cs
class BoyerMooreMajorityVoteTests (line 7) | public class BoyerMooreMajorityVoteTests
method FindMajority_SimpleMajority_ReturnsCorrectElement (line 9) | [Test]
method FindMajority_AllSameElements_ReturnsThatElement (line 17) | [Test]
method FindMajority_NoMajority_ReturnsNull (line 25) | [Test]
method FindMajority_EmptyArray_ReturnsNull (line 33) | [Test]
method FindMajority_NullArray_ReturnsNull (line 41) | [Test]
method FindMajority_SingleElement_ReturnsThatElement (line 49) | [Test]
method FindMajority_MajorityAtEnd_ReturnsCorrectElement (line 57) | [Test]
method FindMajority_MajorityAtStart_ReturnsCorrectElement (line 65) | [Test]
method FindMajority_NegativeNumbers_ReturnsCorrectElement (line 73) | [Test]
method FindMajority_ExactlyHalf_ReturnsNull (line 81) | [Test]
FILE: Algorithms.Tests/Other/DecisionsConvolutionsTest.cs
class DecisionsConvolutionsTest (line 5) | public static class DecisionsConvolutionsTest
method Verify_Linear_Convolution (line 7) | [Test]
method Verify_MaxMin_Convolution (line 33) | [Test]
FILE: Algorithms.Tests/Other/FermatPrimeCheckerTests.cs
class FermatPrimeCheckerTests (line 5) | public static class FermatPrimeCheckerTests
method IsProbablePrime (line 7) | [TestCase(5, true)]
FILE: Algorithms.Tests/Other/FloodFillTest.cs
class Tests (line 5) | public static class Tests
method BreadthFirstSearch_ThrowsArgumentOutOfRangeException (line 14) | [Test]
method DepthFirstSearch_ThrowsArgumentOutOfRangeException (line 21) | [Test]
method BreadthFirstSearch_Test1 (line 28) | [Test]
method BreadthFirstSearch_Test2 (line 34) | [Test]
method BreadthFirstSearch_Test3 (line 40) | [Test]
method DepthFirstSearch_Test1 (line 46) | [Test]
method DepthFirstSearch_Test2 (line 52) | [Test]
method DepthFirstSearch_Test3 (line 58) | [Test]
method GenerateTestBitmap (line 64) | private static SKBitmap GenerateTestBitmap()
method TestAlgorithm (line 89) | private static void TestAlgorithm(
FILE: Algorithms.Tests/Other/GaussOptimizationTest.cs
class GaussOptimizationTest (line 5) | public static class GaussOptimizationTest
method Verify_Gauss_Optimization_Positive (line 7) | [Test]
method Verify_Gauss_Optimization_Negative (line 51) | [Test]
FILE: Algorithms.Tests/Other/GeoLocationTests.cs
class GeoLocationTests (line 5) | public static class GeoLocationTests
method CalculateDistanceFromLatLngTest (line 7) | [TestCase(53.430488d, -2.96129d, 53.430488d, -2.96129d, 0d)]
FILE: Algorithms.Tests/Other/GeofenceTests.cs
class GeofenceTests (line 5) | [TestFixture]
method Setup (line 10) | [SetUp]
method IsInside_ShouldReturnTrue_WhenUserIsInsideGeofence (line 16) | [Test]
method IsInside_ShouldReturnFalse_WhenUserIsOutsideGeofence (line 27) | [Test]
method IsInside_ShouldReturnTrue_WhenUserIsExactlyOnGeofenceBoundary (line 38) | [Test]
method IsInside_ShouldReturnFalse_WhenUserIsFarFromGeofence (line 49) | [Test]
FILE: Algorithms.Tests/Other/GeohashTests.cs
class GeohashTests (line 5) | [TestFixture]
method Encode_ShouldReturnCorrectGeohash_ForHoChiMinhCity (line 8) | [Test]
method Encode_ShouldReturnCorrectGeohash_ForHanoi (line 17) | [Test]
method Encode_ShouldReturnCorrectGeohash_ForDaNang (line 26) | [Test]
method Encode_ShouldReturnCorrectGeohash_ForNhaTrang (line 35) | [Test]
method Encode_ShouldReturnCorrectGeohash_ForVungTau (line 44) | [Test]
FILE: Algorithms.Tests/Other/Int2BinaryTests.cs
class Int2BinaryTests (line 5) | public static class Int2BinaryTests
method GetsBinary (line 7) | [TestCase((ushort)0, "0000000000000000")]
method GetsBinary (line 25) | [TestCase((uint)0, "00000000000000000000000000000000")]
method GetsBinary (line 43) | [TestCase((ulong)0, "0000000000000000000000000000000000000000000000000...
FILE: Algorithms.Tests/Other/JulianEasterTests.cs
class JulianEasterTest (line 8) | public static class JulianEasterTest
method CalculateTest (line 10) | [TestCaseSource(nameof(CalculateCases))]
FILE: Algorithms.Tests/Other/KadanesAlgorithmTests.cs
class KadanesAlgorithmTests (line 17) | public static class KadanesAlgorithmTests
method FindMaximumSubarraySum_WithPositiveNumbers_ReturnsCorrectSum (line 19) | [Test]
method FindMaximumSubarraySum_WithMixedNumbers_ReturnsCorrectSum (line 32) | [Test]
method FindMaximumSubarraySum_WithAllNegativeNumbers_ReturnsLargestNegative (line 46) | [Test]
method FindMaximumSubarraySum_WithSingleElement_ReturnsThatElement (line 60) | [Test]
method FindMaximumSubarraySum_WithNullArray_ThrowsArgumentException (line 74) | [Test]
method FindMaximumSubarraySum_WithEmptyArray_ThrowsArgumentException (line 84) | [Test]
method FindMaximumSubarraySum_WithAlternatingNumbers_ReturnsCorrectSum (line 94) | [Test]
method FindMaximumSubarrayWithIndices_ReturnsCorrectIndices (line 108) | [Test]
method FindMaximumSubarrayWithIndices_WithSingleElement_ReturnsZeroIndices (line 125) | [Test]
method FindMaximumSubarrayWithIndices_WithNullArray_ThrowsArgumentException (line 140) | [Test]
method FindMaximumSubarraySum_WithLongArray_ReturnsCorrectSum (line 150) | [Test]
method FindMaximumSubarraySum_WithLargeLongNumbers_ReturnsCorrectSum (line 164) | [Test]
method FindMaximumSubarraySum_WithLongNullArray_ThrowsArgumentException (line 179) | [Test]
method FindMaximumSubarraySum_WithZeros_ReturnsZero (line 189) | [Test]
method FindMaximumSubarraySum_WithMixedZerosAndNegatives_ReturnsZero (line 203) | [Test]
FILE: Algorithms.Tests/Other/KochSnowflakeTest.cs
class KochSnowflakeTest (line 6) | public static class KochSnowflakeTest
method TestIterateMethod (line 8) | [Test]
method BitmapWidthIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 25) | [Test]
method TestKochSnowflakeExample (line 31) | [Test]
FILE: Algorithms.Tests/Other/LuhnTests.cs
class LuhnTests (line 8) | public class LuhnTests
method ValidateTrue (line 10) | [TestCase("89014103211118510720")] // ICCID
method ValidateFalse (line 26) | [TestCase("89012104211118510720")] // ICCID
method GetLostNum (line 42) | [TestCase("x9012104211118510720")] // ICCID
method EdgeCases_GetLostNum (line 60) | [TestCase("")]
method EdgeCases_Validate (line 76) | [TestCase("1a2b3c4d5e6f7g8h9i0j")]
FILE: Algorithms.Tests/Other/MandelbrotTest.cs
class MandelbrotTest (line 6) | public static class MandelbrotTest
method BitmapWidthIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 8) | [Test]
method BitmapHeightIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 14) | [Test]
method MaxStepIsZeroOrNegative_ThrowsArgumentOutOfRangeException (line 20) | [Test]
method TestBlackAndWhite (line 26) | [Test]
method TestColorCoded (line 37) | [Test]
FILE: Algorithms.Tests/Other/ParetoOptimizationTests.cs
class ParetoOptimizationTests (line 5) | public static class ParetoOptimizationTests
method Verify_Pareto_Optimization (line 7) | [Test]
FILE: Algorithms.Tests/Other/PollardsRhoFactorizingTests.cs
class PollardsRhoFactorizingTests (line 5) | public class PollardsRhoFactorizingTests
method SimpleTest (line 7) | [TestCase(8051, 97)]
FILE: Algorithms.Tests/Other/RGBHSVConversionTest.cs
class RgbHsvConversionTest (line 5) | public static class RgbHsvConversionTest
method HueOutOfRange_ThrowsArgumentOutOfRangeException (line 7) | [Test]
method SaturationOutOfRange_ThrowsArgumentOutOfRangeException (line 14) | [Test]
method ValueOutOfRange_ThrowsArgumentOutOfRangeException (line 21) | [Test]
method TestRgbOutput (line 29) | [TestCase(0, 0, 0, 0, 0, 0)]
method TestHsvOutput (line 54) | [TestCase(0, 0, 0, 0, 0, 0)]
FILE: Algorithms.Tests/Other/SieveOfEratosthenesTests.cs
class SieveOfEratosthenesTests (line 5) | public static class SieveOfEratosthenesTests
method First10_000PrimesCorrect (line 667) | [Test]
method TestMaxNumber (line 671) | [Test]
method TestIsPrime (line 674) | [TestCase(13, true)]
FILE: Algorithms.Tests/Other/TriangulatorTests.cs
class TriangulatorTests (line 5) | [TestFixture]
method CalculatePosition_ValidCoordinatesAndDistances_ReturnsExpectedPosition (line 8) | [Test]
method CalculatePosition_InvalidBaseLocations_ThrowsArgumentException (line 28) | [Test]
method CalculatePosition_InvalidDistances_ThrowsArgumentException (line 41) | [Test]
FILE: Algorithms.Tests/Other/WelfordsVarianceTest.cs
class WelfordsVarianceTest (line 5) | public class WelfordsVarianceTest
method WelfordVariance_Example1 (line 7) | [Test]
method WelfordVariance_Example2 (line 22) | [Test]
method WelfordVariance_Example3 (line 36) | [Test]
method WelfordVariance_Example4 (line 50) | [Test]
method WelfordVariance_Example5 (line 64) | [Test]
method WelfordVariance_Example6 (line 74) | [Test]
method WelfordVariance_Example7 (line 85) | [Test]
method WelfordVariance_Example8 (line 96) | [Test]
method WelfordVariance_Example9 (line 107) | [Test]
method WelfordVariance_Example10 (line 118) | [Test]
method WelfordVariance_NoValue (line 129) | [Test]
method WelfordVariance_OneValue (line 139) | [Test]
method WelfordVariance_TwoValues (line 150) | [Test]
FILE: Algorithms.Tests/Problems/DynamicProgramming/CoinChange/GenerateChangesDictionaryTests.cs
class GenerateChangesDictionaryTests (line 5) | [TestFixture]
method GenerateChangesDictionaryTest_Success (line 8) | [Test]
FILE: Algorithms.Tests/Problems/DynamicProgramming/CoinChange/GenerateSingleCoinChangesTests.cs
class GenerateSingleCoinChangesTests (line 5) | [TestFixture]
method GenerateSingleCoinChangesTests_Success (line 8) | [Test]
method GenerateSingleCoinChangesTests_ShouldThrow_CoinCannotBeLesserOrEqualZero (line 32) | [Test]
method GenerateSingleCoinChangesTests_ShouldThrow_CoinsArrayCannotBeEmpty (line 44) | [Test]
method GenerateSingleCoinChangesTests_ShouldThrow_CoinsArrayMustContainOne (line 56) | [Test]
method GenerateSingleCoinChangesTests_ShouldThrow_CoinsArrayCannotContainNegativeValues (line 68) | [Test]
method GenerateSingleCoinChangesTests_ShouldThrow_CoinsArrayCannotContainDuplicates (line 80) | [Test]
FILE: Algorithms.Tests/Problems/DynamicProgramming/CoinChange/GetMinimalNextCoinTests.cs
class GetMinimalNextCoinTests (line 5) | public class GetMinimalNextCoinTests
method GetMinimalNextCoinTest_Success (line 7) | [Test]
FILE: Algorithms.Tests/Problems/DynamicProgramming/CoinChange/MakeCoinChangeDynamicTests.cs
class MakeCoinChangeDynamicTests (line 5) | [TestFixture]
method MakeCoinChangeDynamicTest_Success (line 8) | [Test]
FILE: Algorithms.Tests/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistanceTests.cs
class LevenshteinDistanceTests (line 5) | public class LevenshteinDistanceTests
method Calculate_ReturnsCorrectLevenshteinDistance (line 7) | [TestCase("kitten", "sitting", 3)]
FILE: Algorithms.Tests/Problems/GraphColoring/GraphColoringSolverTests.cs
class GraphColoringSolverTests (line 5) | [TestFixture]
method AssertValidColoring (line 18) | private static void AssertValidColoring(bool[,] adjacencyMatrix, int[]...
method CreateEmptyGraph (line 49) | private static bool[,] CreateEmptyGraph(int vertices)
method CreateCompleteGraph (line 57) | private static bool[,] CreateCompleteGraph(int vertices)
method CreateBipartiteGraph (line 76) | private static bool[,] CreateBipartiteGraph(int setASize, int setBSize)
method CreateCycleGraph (line 96) | private static bool[,] CreateCycleGraph(int vertices)
method CreatePathGraph (line 111) | private static bool[,] CreatePathGraph(int vertices)
method ColorGraph_ThrowsArgumentNullException_WhenAdjacencyMatrixIsNull (line 122) | [Test]
method ColorGraph_ThrowsArgumentException_WhenAdjacencyMatrixIsNotSquare (line 130) | [Test]
method ColorGraph_ThrowsArgumentException_WhenNumColorsIsNonPositive (line 139) | [TestCase(0)]
method ColorGraph_ReturnsEmptyArray_ForEmptyGraph (line 150) | [Test]
method ColorGraph_ColorsSingleVertex_WithOneColor (line 161) | [Test]
method ColorGraph_ColorsDisconnectedVertices_WithOneColor (line 174) | [Test]
method ColorGraph_ColorsBipartiteGraph_WithTwoColors (line 189) | [Test]
method ColorGraph_ThrowsArgumentException_ForBipartiteGraphWithOneColor (line 204) | [Test]
method ColorGraph_ColorsPathGraph_WithTwoColors (line 214) | [Test]
method ColorGraph_ColorsEvenCycle_WithTwoColors (line 229) | [Test]
method ColorGraph_ThrowsArgumentException_ForOddCycleWithTwoColors (line 244) | [Test]
method ColorGraph_ColorsOddCycle_WithThreeColors (line 254) | [Test]
method ColorGraph_ColorsTriangle_WithThreeColors (line 266) | [Test]
method ColorGraph_ThrowsArgumentException_ForTriangleWithTwoColors (line 281) | [Test]
method ColorGraph_ColorsCompleteGraphK4_WithFourColors (line 291) | [Test]
method ColorGraph_ThrowsArgumentException_ForCompleteGraphK4WithThreeColors (line 306) | [Test]
method ColorGraph_ColorsStarGraph_WithTwoColors (line 316) | [Test]
method ColorGraph_HandlesPetersenGraph_WithThreeColors (line 338) | [Test]
method ColorGraph_AllColorsWithinRange (line 366) | [Test]
method ColorGraph_SymmetricMatrix_ProducesSameResult (line 382) | [Test]
method ColorGraph_LargerGraph_ProducesValidColoring (line 399) | [Test]
FILE: Algorithms.Tests/Problems/JobScheduling/IntervalSchedulingSolverTests.cs
class IntervalSchedulingSolverTests (line 7) | public class IntervalSchedulingSolverTests
method Schedule_ReturnsEmpty_WhenNoJobs (line 9) | [Test]
method Schedule_ReturnsSingleJob_WhenOnlyOneJob (line 16) | [Test]
method Schedule_ThrowsArgumentNullException_WhenJobsIsNull (line 25) | [Test]
method Schedule_SelectsJobsWithEqualEndTime (line 31) | [Test]
method Schedule_SelectsJobStartingAtLastEnd (line 46) | [Test]
method Schedule_HandlesJobsWithNegativeTimes (line 62) | [Test]
method Schedule_SelectsNonOverlappingJobs (line 77) | [Test]
method Schedule_HandlesFullyOverlappingJobs (line 97) | [Test]
FILE: Algorithms.Tests/Problems/KnightTour/OpenKnightTourTests.cs
class OpenKnightTourTests (line 5) | [TestFixture]
method IsKnightMove (line 8) | private static bool IsKnightMove((int r, int c) a, (int r, int c) b)
method MapVisitOrder (line 15) | private static Dictionary<int, (int r, int c)> MapVisitOrder(int[,] bo...
method AssertIsValidTour (line 38) | private static void AssertIsValidTour(int[,] board)
method Tour_Throws_On_NonPositiveN (line 82) | [Test]
method Tour_Throws_On_Unsolvable_N_2_3_4 (line 92) | [TestCase(2)]
method Tour_Returns_Valid_1x1 (line 101) | [Test]
method Tour_Returns_Valid_5x5 (line 117) | [Test, Category("Slow"), CancelAfterAttribute(30000)]
method Tour_Fills_All_Cells_No_Zeros_On_Successful_Boards (line 131) | [Test]
method Tour_Produces_Values_In_Valid_Range_And_Unique (line 147) | [Test]
method Tour_Returns_Square_Array (line 170) | [Test]
FILE: Algorithms.Tests/Problems/NQueens/BacktrackingNQueensSolverTests.cs
class BacktrackingNQueensSolverTests (line 5) | public static class BacktrackingNQueensSolverTests
method SolvesCorrectly (line 7) | [TestCase(0, 0)]
method NCannotBeNegative (line 37) | [Test]
method ValidateOneQueenPerRow (line 47) | private static void ValidateOneQueenPerRow(bool[,] solution)
method ValidateOneQueenPerColumn (line 59) | private static void ValidateOneQueenPerColumn(bool[,] solution)
method ValidateOneQueenPerTopLeftBottomRightDiagonalLine (line 71) | private static void ValidateOneQueenPerTopLeftBottomRightDiagonalLine(...
method ValidateOneQueenPerBottomLeftTopRightDiagonalLine (line 92) | private static void ValidateOneQueenPerBottomLeftTopRightDiagonalLine(...
method ValidateCell (line 113) | private static bool ValidateCell(bool foundQueen, bool currentCell)
FILE: Algorithms.Tests/Problems/StableMarriage/GaleShapleyTests.cs
class GaleShapleyTests (line 10) | public static class GaleShapleyTests
method MatchingIsSuccessful (line 15) | [Test]
method AreMatchesStable (line 39) | private static bool AreMatchesStable(Proposer[] proposers, Accepter[] ...
method Score (line 46) | private static int Score(Proposer proposer, Accepter accepter) =>
FILE: Algorithms.Tests/Problems/TravelingSalesman/TravelingSalesmanSolverTests.cs
class TravelingSalesmanSolverTests (line 9) | [TestFixture]
method SolveBruteForce_KnownOptimalRoute_ReturnsCorrectResult (line 15) | [Test]
method SolveNearestNeighbor_Heuristic_ReturnsFeasibleRoute (line 35) | [Test]
method SolveNearestNeighbor_InvalidStart_ThrowsException (line 56) | [Test]
method SolveNearestNeighbor_NoUnvisitedCities_ThrowsException (line 71) | [Test]
method NonSquareMatrix_ThrowsException (line 88) | [Test]
method SolveBruteForce_TooFewCities_ThrowsException (line 99) | [Test]
method SolveNearestNeighbor_TwoCities_ReturnsCorrectRoute (line 109) | [Test]
FILE: Algorithms.Tests/RecommenderSystem/CollaborativeFilteringTests.cs
class CollaborativeFilteringTests (line 6) | [TestFixture]
method Setup (line 13) | [SetUp]
method CalculateSimilarity_WithValidInputs_ReturnsExpectedResults (line 42) | [Test]
method CalculateSimilarity_WithNoCommonItems_ReturnsZero (line 58) | [Test]
method PredictRating_WithNonexistentItem_ReturnsZero (line 69) | [Test]
method PredictRating_WithOtherUserHavingRatedTargetItem_ShouldCalculateSimilarityAndWeightedSum (line 77) | [NonParallelizable]
FILE: Algorithms.Tests/Search/AStarTests.cs
class AStarTests (line 8) | public static class AStarTests
method ResetNodes_ResetsAllNodeProperties (line 10) | [Test]
method GeneratePath_ReturnsPathFromTargetToRoot (line 30) | [Test]
method Compute_ReturnsEmptyList_WhenNoPathExists (line 45) | [Test]
method Compute_ReturnsPath_WhenPathExists (line 58) | [Test]
method VecN_Equality_WorksAsExpected (line 76) | [Test]
method AddOrUpdateConnected_ThrowsPathfindingException_OnSelfReference (line 87) | [Test]
FILE: Algorithms.Tests/Search/BinarySearcherTests.cs
class BinarySearcherTests (line 5) | public static class BinarySearcherTests
method FindIndex_ItemPresent_IndexCorrect (line 7) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 23) | [Test]
method FindIndex_ArrayEmpty_MinusOneReturned (line 43) | [Test]
FILE: Algorithms.Tests/Search/BoyerMooreTests.cs
class BoyerMoore_Tests (line 5) | public class BoyerMoore_Tests
method BoyerMoore_Majority_Finder_Test (line 7) | [Test]
FILE: Algorithms.Tests/Search/FastSearcherTests.cs
class FastSearcherTests (line 6) | public static class FastSearcherTests
method FindIndex_ItemPresent_IndexCorrect (line 8) | [Test]
method FindIndex_ItemPresentInSpecificCase_IndexCorrect (line 23) | [TestCase(new[] { 1, 2 }, 1)]
method FindIndex_ItemPresentDeterministic_IndexCorrect (line 38) | [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 3)] // Item in left...
method FindIndex_ItemPresentInArrayOfDuplicates_IndexCorrect (line 60) | [Test]
method FindIndex_ItemMissing_ItemNotFoundExceptionThrown (line 75) | [TestCase(new int[0], 2)] // Empty array
method FindIndex_ItemMissingInArrayOfDuplicates_ItemNotFoundExceptionThrown (line 89) | [Test]
method FindIndex_ItemOutOfRange_ItemNotFoundExceptionThrown (line 104) | [Test]
method CreateArrayOfDuplicates (line 121) | private static int[] CreateArrayOfDuplicates(int length, int value)
FILE: Algorithms.Tests/Search/FibonacciSearcherTests.cs
class FibonacciSearcherTests (line 5) | public static class FibonacciSearcherTests
method FindIndex_ItemPresent_IndexCorrect (line 7) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 22) | [Test]
method FindIndex_ArrayEmpty_MinusOneReturned (line 38) | [Test]
method FindIndex_ArrayNull_ItemNull_ArgumentNullExceptionThrown (line 53) | [TestCase(null, "a")]
FILE: Algorithms.Tests/Search/Helper.cs
class Helper (line 3) | public static class Helper
method GetSortedArray (line 5) | public static int[] GetSortedArray(int length) =>
method GetItemIn (line 11) | public static int GetItemIn(int[] arr) => arr[TestContext.CurrentConte...
method GetItemNotIn (line 13) | public static int GetItemNotIn(int[] arr)
method GetItemSmallerThanAllIn (line 25) | public static int GetItemSmallerThanAllIn(int[] arr) => arr.Min() - 1;
method GetItemBiggerThanAllIn (line 27) | public static int GetItemBiggerThanAllIn(int[] arr) => arr.Max() + 1;
FILE: Algorithms.Tests/Search/InterpolationSearchTests.cs
class InterpolationSearchTests (line 5) | public static class InterpolationSearchTests
method FindIndex_ItemPresent_IndexCorrect (line 7) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 22) | [Test]
method FindIndex_ArrayEmpty_MinusOneReturned (line 41) | [Test]
FILE: Algorithms.Tests/Search/JumpSearcherTests.cs
class JumpSearcherTests (line 5) | public class JumpSearcherTests
method FindIndex_ItemPresent_ItemCorrect (line 7) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 22) | [Test]
method FindIndex_ArrayEmpty_MinusOneReturned (line 37) | [Test]
method FindIndex_ArrayNull_ItemNull_ArgumentNullExceptionThrown (line 52) | [TestCase(null, "abc")]
FILE: Algorithms.Tests/Search/LinearSearcherTests.cs
class LinearSearcherTests (line 6) | public static class LinearSearcherTests
method Find_ItemPresent_ItemCorrect (line 8) | [Test]
method FindIndex_ItemPresent_IndexCorrect (line 24) | [Test]
method Find_ItemMissing_ItemNotFoundExceptionThrown (line 40) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 53) | [Test]
FILE: Algorithms.Tests/Search/RecursiveBinarySearcherTests.cs
class RecursiveBinarySearcherTests (line 5) | public static class RecursiveBinarySearcherTests
method FindIndex_ItemPresent_IndexCorrect (line 7) | [Test]
method FindIndex_ItemMissing_MinusOneReturned (line 23) | [Test]
method FindIndex_ArrayEmpty_MinusOneReturned (line 43) | [Test]
method FindIndex_NullCollection_Throws (line 57) | [Test]
FILE: Algorithms.Tests/Sequences/AllOnesSequenceTests.cs
class AllOnesSequenceTests (line 5) | public class AllOnesSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/AllThreesSequenceTests.cs
class AllThreesSequenceTests (line 5) | public class AllThreesSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/AllTwosSequenceTests.cs
class AllTwosSequenceTests (line 5) | public class AllTwosSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/BinaryPrimeConstantSequenceTests.cs
class BinaryPrimeConstantSequenceTests (line 5) | public class BinaryPrimeConstantSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/BinomialSequenceTests.cs
class BinomialSequenceTests (line 5) | public class BinomialSequenceTests
method First4RowsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/CakeNumbersSequenceTests.cs
class CakeNumbersSequenceTests (line 5) | public class CakeNumbersSequenceTests
method First46ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/CatalanSequenceTest.cs
class CatalanSequenceTest (line 5) | public class CatalanSequenceTest
method First30ItemsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/CentralPolygonalNumbersSequenceTests.cs
class CentralPolygonalNumbersSequenceTests (line 5) | public class CentralPolygonalNumbersSequenceTests
method First53ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/CubesSequenceTests.cs
class CubesSequenceTests (line 5) | public class CubesSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/DivisorsCountSequenceTests.cs
class DivisorsCountSequenceTests (line 5) | public class DivisorsCountSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/EuclidNumbersSequenceTests.cs
class EuclidNumbersSequenceTests (line 5) | public class EuclidNumbersSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/EulerTotientSequenceTests.cs
class EulerTotientSequenceTests (line 5) | public class EulerTotientSequenceTests
method FirstElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/FactorialSequenceTest.cs
class FactorialSequenceTest (line 5) | public class FactorialSequenceTest
method First10ItemsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/FermatNumbersSequenceTests.cs
class FermatNumbersSequenceTests (line 5) | public class FermatNumbersSequenceTests
method First5ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/FermatPrimesSequenceTests.cs
class FermatPrimesSequenceTests (line 5) | public class FermatPrimesSequenceTests
method All5ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/FibonacciSequenceTests.cs
class FibonacciSequenceTests (line 5) | public class FibonacciSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/GolombsSequenceTests.cs
class GolombsSequenceTests (line 5) | public class GolombsSequenceTests
method First50ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/KolakoskiSequenceTests.cs
class KolakoskiSequenceTests (line 5) | public class KolakoskiSequenceTests
method First100ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/KummerNumbersSequenceTests.cs
class KummerNumbersSequenceTests (line 5) | public class KummerNumbersSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/LucasNumbersBeginningAt2SequenceTests.cs
class LucasNumbersBeginningAt2SequenceTests (line 5) | public class LucasNumbersBeginningAt2SequenceTests
method FirstElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/MakeChangeSequenceTests.cs
class MakeChangeSequenceTests (line 5) | public class MakeChangeSequenceTests
method First100ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/MatchstickTriangleSequenceTests.cs
class MatchstickTriangleSequenceTests (line 5) | [TestFixture]
method TestOeisList (line 18) | [Test]
FILE: Algorithms.Tests/Sequences/NaturalSequenceTests.cs
class NaturalSequenceTests (line 5) | public class NaturalSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/NegativeIntegersSequenceTests.cs
class NegativeIntegersSequenceTests (line 5) | public class NegativeIntegersSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/NumberOfBooleanFunctionsSequenceTests.cs
class NumberOfBooleanFunctionsSequenceTests (line 5) | public class NumberOfBooleanFunctionsSequenceTests
method First5ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/NumberOfPrimesByNumberOfDigitsSequenceTests.cs
class NumberOfPrimesByNumberOfDigitsSequenceTests (line 5) | public class NumberOfPrimesByNumberOfDigitsSequenceTests
method First5ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/NumberOfPrimesByPowersOf10SequenceTests.cs
class NumberOfPrimesByPowersOf10SequenceTests (line 5) | public class NumberOfPrimesByPowersOf10SequenceTests
method First5ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/OnesCountingSequenceTest.cs
class OnesCountingSequenceTest (line 5) | [TestFixture]
method CountOnes (line 69) | private int CountOnes(BigInteger i)
method Count1000 (line 85) | [Test]
method CompareAgainstCalculated (line 93) | [Test]
FILE: Algorithms.Tests/Sequences/PowersOf10SequenceTests.cs
class PowersOf10SequenceTests (line 5) | public class PowersOf10SequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/PowersOf2SequenceTests.cs
class PowersOf2SequenceTests (line 5) | public class PowersOf2SequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/PrimePiSequenceTests.cs
class PrimePiSequenceTests (line 5) | public class PrimePiSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/PrimesSequenceTests.cs
class PrimesSequenceTests (line 5) | public class PrimesSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/PrimorialNumbersSequenceTests.cs
class PrimorialNumbersSequenceTests (line 5) | public class PrimorialNumbersSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/RecamansSequenceTests.cs
class RecamansSequenceTests (line 5) | public class RecamansSequenceTests
method First50ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/SquaresSequenceTests.cs
class SquaresSequenceTests (line 5) | public class SquaresSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/TetrahedralSequenceTests.cs
class TetrahedralSequenceTests (line 5) | [TestFixture]
method TestOeisList (line 19) | [Test]
FILE: Algorithms.Tests/Sequences/TetranacciNumbersSequenceTests.cs
class TetranacciNumbersSequenceTests (line 5) | public class TetranacciNumbersSequenceTests
method First35ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/ThreeNPlusOneStepsSequenceTests.cs
class ThreeNPlusOneStepsSequenceTests (line 5) | public class ThreeNPlusOneStepsSequenceTests
method First50ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/TribonacciNumbersSequenceTests.cs
class TribonacciNumbersSequenceTests (line 5) | public class TribonacciNumbersSequenceTests
method First37ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/VanEcksSequenceTests.cs
class VanEcksSequenceTests (line 5) | public class VanEcksSequenceTests
method First50ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Sequences/ZeroSequenceTests.cs
class ZeroSequenceTests (line 5) | public class ZeroSequenceTests
method First10ElementsCorrect (line 7) | [Test]
FILE: Algorithms.Tests/Shufflers/FisherYatesShufflerTests.cs
class FisherYatesShufflerTests (line 6) | public static class FisherYatesShufflerTests
method ArrayShuffled_NewArrayHasSameSize (line 8) | [Test]
method ArrayShuffled_NewArrayHasSameValues (line 24) | [Test]
method ArrayShuffled_SameShuffle (line 40) | [Test]
method ArrayShuffled_DifferentSeedDifferentShuffle (line 57) | [Test]
FILE: Algorithms.Tests/Shufflers/LINQShufflerTests.cs
class LinqShufflerTests (line 6) | public static class LinqShufflerTests
method ArrayShuffled_NewArraySameSize (line 8) | [Test]
method ArrayShuffled_NewArraySameValues (line 24) | [Test]
method ArrayShuffled_NewArraySameShuffle (line 40) | [Test]
FILE: Algorithms.Tests/Shufflers/NaiveShufflerTests.cs
class NaiveShufflerTests (line 6) | public static class NaiveShufflerTests
method ArrayShuffled_NewArraySameSize (line 8) | [Test]
method ArrayShuffled_NewArraySameValues (line 24) | [Test]
method ArrayShuffled_NewArraySameShuffle (line 40) | [Test]
FILE: Algorithms.Tests/Shufflers/RecursiveShufflerTests.cs
class RecursiveShufflerTests (line 6) | public static class RecursiveShufflerTests
method ArrayShuffled_NewArraySameSize (line 8) | [Test]
method ArrayShuffled_NewArraySameValues (line 24) | [Test]
method ArrayShuffled_NewArraySameShuffle (line 40) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/BasicTeamSorterTests.cs
class BasicTimSorterTests (line 5) | [TestFixture]
method Sort_EmptyArray_DoesNotThrow (line 10) | [Test]
method Sort_SingleElementArray_DoesNotChangeArray (line 18) | [Test]
method Sort_AlreadySortedArray_DoesNotChangeArray (line 26) | [Test]
method Sort_UnsortedArray_SortsCorrectly (line 34) | [Test]
method Sort_ReverseSortedArray_SortsCorrectly (line 42) | [Test]
method Sort_ArrayWithDuplicates_SortsCorrectly (line 50) | [Test]
method Sort_LargeArray_SortsCorrectly (line 58) | [Test]
method Sort_LargeRandomArray_SortsCorrectly (line 70) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/BinaryInsertionSorterTests.cs
class BinaryInsertionSorterTests (line 6) | public static class BinaryInsertionSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/BogoSorterTests.cs
class BogoSorterTests (line 6) | public static class BogoSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/BubbleSorterTests.cs
class BubbleSorterTests (line 6) | public static class BubbleSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/CocktailSorterTests.cs
class CocktailSorterTests (line 6) | public static class CocktailSorterTests
method SortsArray (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/CombSorterTests.cs
class CombSorterTests (line 6) | public static class CombSorterTests
method ArraySorted (line 8) | [Test]
method ArraySorted_WithCustomShrinkFactor (line 26) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/CycleSorterTests.cs
class CycleSorterTests (line 6) | public static class CycleSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/ExchangeSorterTests.cs
class ExchangeSorterTests (line 6) | public static class ExchangeSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/GnomeSorterTests.cs
class GnomeSorterTests (line 6) | public static class GnomeSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/HeapSorterTests.cs
class HeapSorterTests (line 6) | public static class HeapSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/InsertionSorterTests.cs
class InsertionSorterTests (line 6) | public static class InsertionSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/MedianOfThreeQuickSorterTests.cs
class MedianOfThreeQuickSorterTests (line 6) | public static class MedianOfThreeQuickSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/MergeSorterTests.cs
class MergeSorterTests (line 9) | public static class MergeSorterTests
method TestOnMergeSorter (line 11) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/MiddlePointQuickSorterTests.cs
class MiddlePointQuickSorterTests (line 6) | public static class MiddlePointQuickSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/PancakeSorterTests.cs
class PancakeSorterTests (line 6) | public static class PancakeSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/RandomPivotQuickSorterTests.cs
class RandomPivotQuickSorterTests (line 6) | public static class RandomPivotQuickSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/SelectionSorterTests.cs
class SelectionSorterTests (line 6) | public static class SelectionSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/ShellSorterTests.cs
class ShellSorterTests (line 6) | public static class ShellSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Comparison/TimSorterTests.cs
class TimSorterTests (line 6) | public static class TimSorterTests
method Sort_ShouldBeEquivalentToSuccessfulBasicSort (line 11) | [Test]
method Sort_TinyArray_ShouldSortCorrectly (line 27) | [Test]
method Sort_SmallChunks_ShouldSortCorrectly (line 42) | [Test]
method Sort_ThrowsArgumentNullException_WhenArrayIsNull (line 67) | [Test]
method Sort_UsesDefaultComparer_WhenComparerIsNull (line 77) | [Test]
method Sort_AlreadySortedArray_RemainsUnchanged (line 92) | [Test]
method MergeAt_ShouldReturnEarly_WhenLenAIsZero (line 107) | [Test]
method MergeAt_ShouldReturnEarly_WhenLenBIsZero (line 122) | [Test]
FILE: Algorithms.Tests/Sorters/External/ExternalMergeSorterTests.cs
class ExternalMergeSorterTests (line 7) | public static class ExternalMergeSorterTests
method ArraySorted (line 9) | [Test]
method ArraySorted_OnDisk (line 29) | [Test]
FILE: Algorithms.Tests/Sorters/Integer/BucketSorterTests.cs
class BucketSorterTests (line 6) | public static class BucketSorterTests
method ArraySorted (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/Integer/CountingSorterTests.cs
class CountingSorterTests (line 6) | public static class CountingSorterTests
method SortsNonEmptyArray (line 8) | [Test]
method SortsEmptyArray (line 25) | [Test]
FILE: Algorithms.Tests/Sorters/Integer/RadixSorterTests.cs
class RadixSorterTests (line 6) | public static class RadixSorterTests
method SortsArray (line 8) | [Test]
FILE: Algorithms.Tests/Sorters/String/MsdRadixStringSorterTests.cs
class MsdRadixStringSorterTests (line 9) | public static class MsdRadixStringSorterTests
method ArraySorted (line 11) | [Test]
FILE: Algorithms.Tests/Sorters/Utils/GallopingStrategyTests.cs
class GallopingStrategyTests (line 5) | [TestFixture]
method GallopLeft_KeyPresent_ReturnsCorrectIndex (line 10) | [Test]
method GallopLeft_KeyNotPresent_ReturnsCorrectIndex (line 18) | [Test]
method GallopLeft_KeyLessThanAll_ReturnsZero (line 26) | [Test]
method GallopLeft_KeyGreaterThanAll_ReturnsLength (line 34) | [Test]
method GallopRight_KeyPresent_ReturnsCorrectIndex (line 42) | [Test]
method GallopRight_KeyNotPresent_ReturnsCorrectIndex (line 50) | [Test]
method GallopRight_KeyLessThanAll_ReturnsZero (line 58) | [Test]
method GallopRight_KeyGreaterThanAll_ReturnsLength (line 66) | [Test]
method GallopLeft_EmptyArray_ReturnsZero (line 74) | [Test]
method GallopRight_EmptyArray_ReturnsZero (line 82) | [Test]
method TestBoundLeftShift_WhenShiftableCausesNegativeShift_ReturnsShiftedValuePlusOne (line 91) | [Test]
method TestBoundLeftShift_WhenShiftableDoesNotCauseNegativeShift_ReturnsMaxValue (line 105) | [Test]
FILE: Algorithms.Tests/Stack/BalancedParenthesesCheckerTests.cs
class BalancedParenthesesCheckerTests (line 5) | [TestFixture]
method IsBalanced (line 8) | public static bool IsBalanced(string expression)
method IsBalanced_EmptyString_ThrowsArgumentException (line 14) | [Test]
method IsBalanced_ValidBalancedExpression_ReturnsTrue (line 30) | [Test]
method IsBalanced_ValidUnbalancedExpression_ReturnsFalse (line 43) | [Test]
method IsBalanced_UnbalancedWithExtraClosingBracket_ReturnsFalse (line 56) | [Test]
method IsBalanced_ExpressionWithInvalidCharacters_ThrowsArgumentException (line 69) | [Test]
method IsBalanced_SingleOpeningBracket_ReturnsFalse (line 83) | [Test]
method IsBalanced_SingleClosingBracket_ReturnsFalse (line 96) | [Test]
method IsBalanced_ExpressionWithMultipleBalancedBrackets_ReturnsTrue (line 109) | [Test]
FILE: Algorithms.Tests/Stack/InfixToPostfixTests.cs
class InfixToPostfixTests (line 7) | [TestFixture]
method InfixToPostfixConversion_SimpleAddition_ReturnsCorrectPostfix (line 10) | [Test]
method InfixToPostfixConversion_SimpleSubtraction_ReturnsCorrectPostfix (line 23) | [Test]
method InfixToPostfixConversion_MultiplicationAndDivision_ReturnsCorrectPostfix (line 36) | [Test]
method InfixToPostfixConversion_ExponentiationOperator_ReturnsCorrectPostfix (line 49) | [Test]
method InfixToPostfixConversion_MixedOperatorPrecedence_ReturnsCorrectPostfix (line 62) | [Test]
method InfixToPostfixConversion_WithParentheses_ReturnsCorrectPostfix (line 75) | [Test]
method InfixToPostfixConversion_NestedParentheses_ReturnsCorrectPostfix (line 88) | [Test]
method InfixToPostfixConversion_ComplexExpression_ReturnsCorrectPostfix (line 101) | [Test]
method InfixToPostfixConversion_WithDigits_ReturnsCorrectPostfix (line 114) | [Test]
method InfixToPostfixConversion_LowercaseLetters_ReturnsCorrectPostfix (line 127) | [Test]
method InfixToPostfixConversion_WithWhitespace_IgnoresWhitespace (line 140) | [Test]
method InfixToPostfixConversion_MultipleParentheses_ReturnsCorrectPostfix (line 153) | [Test]
method InfixToPostfixConversion_AllOperators_ReturnsCorrectPostfix (line 166) | [Test]
method InfixToPostfixConversion_NullExpression_ThrowsArgumentException (line 179) | [Test]
method InfixToPostfixConversion_EmptyExpression_ThrowsArgumentException (line 191) | [Test]
method InfixToPostfixConversion_WhitespaceOnlyExpression_ThrowsArgumentException (line 203) | [Test]
method InfixToPostfixConversion_InvalidCharacter_ThrowsArgumentException (line 215) | [Test]
method InfixToPostfixConversion_MismatchedParenthesesClosingExtra_ThrowsInvalidOperationException (line 227) | [Test]
method InfixToPostfixConversion_MismatchedParenthesesOpeningExtra_ThrowsInvalidOperationException (line 239) | [Test]
method InfixToPostfixConversion_OnlyOpeningParenthesis_ThrowsInvalidOperationException (line 251) | [Test]
method InfixToPostfixConversion_OnlyClosingParenthesis_ThrowsInvalidOperationException (line 262) | [Test]
method InfixToPostfixConversion_ExponentiationWithOtherOperators_ReturnsCorrectPostfix (line 273) | [Test]
method InfixToPostfixConversion_SingleOperand_ReturnsOperand (line 286) | [Test]
method PostfixExpressionEvaluation_SimpleAddition_ReturnsCorrectResult (line 299) | [Test]
method PostfixExpressionEvaluation_SimpleSubtraction_ReturnsCorrectResult (line 312) | [Test]
method PostfixExpressionEvaluation_SimpleMultiplication_ReturnsCorrectResult (line 325) | [Test]
method PostfixExpressionEvaluation_SimpleDivision_ReturnsCorrectResult (line 338) | [Test]
method PostfixExpressionEvaluation_SimpleExponentiation_ReturnsCorrectResult (line 351) | [Test]
method PostfixExpressionEvaluation_ComplexExpression_ReturnsCorrectResult (line 364) | [Test]
method PostfixExpressionEvaluation_WithWhitespace_ReturnsCorrectResult (line 377) | [Test]
method PostfixExpressionEvaluation_SingleDigit_ReturnsDigit (line 390) | [Test]
method PostfixExpressionEvaluation_NullExpression_ThrowsArgumentException (line 403) | [Test]
method PostfixExpressionEvaluation_EmptyExpression_ThrowsArgumentException (line 415) | [Test]
method PostfixExpressionEvaluation_WhitespaceOnlyExpression_ThrowsArgumentException (line 427) | [Test]
method PostfixExpressionEvaluation_InsufficientOperands_ThrowsInvalidOperationException (line 439) | [Test]
method PostfixExpressionEvaluation_DivisionByZero_ThrowsDivideByZeroException (line 451) | [Test]
method PostfixExpressionEvaluation_InvalidCharacter_ThrowsInvalidOperationException (line 463) | [Test]
method PostfixExpressionEvaluation_LeftoverOperands_ThrowsInvalidOperationException (line 475) | [Test]
method PostfixExpressionEvaluation_UnknownOperator_ThrowsInvalidOperationException (line 487) | [Test]
method PostfixExpressionEvaluation_ComplexExpressionWithAllOperators_ReturnsCorrectResult (line 495) | [Test]
method PostfixExpressionEvaluation_ExponentiationInExpression_ReturnsCorrectResult (line 508) | [Test]
method PostfixExpressionEvaluation_ZeroOperands_ReturnsZero (line 521) | [Test]
method PostfixExpressionEvaluation_LargerNumbers_ReturnsCorrectResult (line 534) | [Test]
method IntegrationTest_ConvertAndEvaluate_SimpleExpression (line 547) | [Test]
method IntegrationTest_ConvertAndEvaluate_ComplexExpression (line 562) | [Test]
method IntegrationTest_ConvertAndEvaluate_WithAllOperators (line 577) | [Test]
method IntegrationTest_ConvertAndEvaluate_WithExponentiation (line 592) | [Test]
FILE: Algorithms.Tests/Stack/NextGreaterElementTests.cs
class NextGreaterElementTests (line 5) | [TestFixture]
method FindNextGreaterElement (line 8) | private static int[] FindNextGreaterElement(int[] input)
method FindNextGreaterElement_InputIsEmpty_ReturnsEmptyArray (line 14) | [Test]
method FindNextGreaterElement_BasicScenario_ReturnsCorrectResult (line 28) | [Test]
method FindNextGreaterElement_NoNextGreaterElement_ReturnsCorrectResult (line 42) | [Test]
method FindNextGreaterElement_AllElementsHaveNoGreaterElement_ReturnsAllNegativeOnes (line 56) | [Test]
method FindNextGreaterElement_InputWithDuplicates_ReturnsCorrectResult (line 70) | [Test]
method FindNextGreaterElement_SingleElementArray_ReturnsNegativeOne (line 84) | [Test]
FILE: Algorithms.Tests/Stack/ReverseStackTests.cs
class ReverseStackTests (line 5) | public class ReverseStackTests
method Reverse (line 7) | public static void Reverse<T>(Stack<T> stack)
method Reverse_EmptyStack_DoesNotChangeStack (line 13) | [Test]
method Reverse_SingleElementStack_DoesNotChangeStack (line 26) | [Test]
method Reverse_MultipleElementStack_ReturnsCorrectOrder (line 41) | [Test]
method Reverse_StackWithDuplicates_ReturnsCorrectOrder (line 61) | [Test]
FILE: Algorithms.Tests/Strings/GeneralStringAlgorithmsTests.cs
class GeneralStringAlgorithmsTests (line 5) | public static class GeneralStringAlgorithmsTests
method MaxCountCharIsObtained (line 7) | [TestCase("Griffith", 'f', 2)]
FILE: Algorithms.Tests/Strings/ManachersAlgorithmTests.cs
class ManachersAlgorithmTests (line 21) | public static class ManachersAlgorithmTests
method FindLongestPalindrome_WithOddLengthPalindrome_ReturnsCorrectPalindrome (line 23) | [Test]
method FindLongestPalindrome_WithEvenLengthPalindrome_ReturnsCorrectPalindrome (line 37) | [Test]
method FindLongestPalindrome_WithSingleCharacter_ReturnsSingleCharacter (line 50) | [Test]
method FindLongestPalindrome_WithEmptyString_ReturnsEmptyString (line 63) | [Test]
method FindLongestPalindrome_WithNullString_ThrowsArgumentException (line 76) | [Test]
method FindLongestPalindrome_WithEntirePalindrome_ReturnsEntireString (line 86) | [Test]
method FindLongestPalindrome_WithNoPalindromes_ReturnsSingleCharacter (line 99) | [Test]
method FindLongestPalindrome_WithLongPalindrome_ReturnsCorrectPalindrome (line 112) | [Test]
method FindLongestPalindrome_WithRepeatingCharacters_ReturnsCorrectPalindrome (line 125) | [Test]
method FindLongestPalindrome_WithSpecialCharacters_ReturnsCorrectPalindrome (line 138) | [Test]
method FindLongestPalindrome_WithTwoCharacters_ReturnsCorrectResult (line 152) | [Test]
method FindLongestPalindrome_WithTwoDifferentCharacters_ReturnsSingleCharacter (line 165) | [Test]
method FindLongestPalindromeWithDetails_ReturnsCorrectDetails (line 178) | [Test]
method FindLongestPalindromeWithDetails_WithEmptyString_ReturnsZeroLength (line 194) | [Test]
method FindLongestPalindromeWithDetails_WithSingleCharacter_ReturnsCorrectDetails (line 209) | [Test]
method FindLongestPalindromeWithDetails_WithNullString_ThrowsArgumentException (line 224) | [Test]
method IsPalindrome_WithPalindromeString_ReturnsTrue (line 234) | [Test]
method IsPalindrome_WithNonPalindromeString_ReturnsFalse (line 247) | [Test]
method IsPalindrome_WithSingleCharacter_ReturnsTrue (line 260) | [Test]
method IsPalindrome_WithEmptyString_ReturnsTrue (line 273) | [Test]
method IsPalindrome_WithNullString_ThrowsArgumentException (line 286) | [Test]
method IsPalindrome_WithEvenLengthPalindrome_ReturnsTrue (line 296) | [Test]
method FindLongestPalindrome_WithNumericString_ReturnsCorrectPalindrome (line 309) | [Test]
method FindLongestPalindrome_WithMixedCase_ReturnsCorrectPalindrome (line 322) | [Test]
method FindLongestPalindrome_WithPalindromeAtStart_ReturnsCorrectPalindrome (line 335) | [Test]
method FindLongestPalindrome_WithPalindromeAtEnd_ReturnsCorrectPalindrome (line 348) | [Test]
method FindLongestPalindrome_WithMultiplePalindromesOfSameLength_ReturnsOne (line 361) | [Test]
method FindLongestPalindromeWithDetails_WithLongString_PerformsEfficiently (line 376) | [Test]
method FindLongestPalindrome_WithVeryLongPalindrome_HandlesGracefully (line 391) | [Test]
method IsPalindrome_WithVeryLongPalindrome_HandlesGracefully (line 405) | [Test]
method FindLongestPalindrome_WithAlternatingCharacters_HandlesEdgeCases (line 418) | [Test]
method FindLongestPalindromeWithDetails_WithSpecialCharacters_HandlesCorrectly (line 431) | [Test]
FILE: Algorithms.Tests/Strings/PalindromeTests.cs
class PalindromeTests (line 5) | public static class PalindromeTests
method TextIsPalindrome_TrueExpected (line 7) | [TestCase("Anna")]
method TextNotPalindrome_FalseExpected (line 19) | [TestCase("hallo")]
FILE: Algorithms.Tests/Strings/PatternMatching/BitapTests.cs
class BitapTests (line 5) | [TestFixture]
method FindExactPattern_EmptyTextReturnsError (line 8) | [Test]
method FindExactPattern_EmptyPatternReturnsZero (line 14) | [Test]
method FindExactPattern_PatternFoundAtBeginning (line 20) | [Test]
method FindExactPattern_PatternFoundInTheMiddle (line 26) | [Test]
method FindExactPattern_PatternFoundAtEnd (line 32) | [Test]
method FindExactPattern_PatternNotFound (line 38) | [Test]
method FindExactPattern_PatternLongerThanText (line 44) | [Test]
method FindExactPattern_OverlappingPatterns (line 50) | [Test]
method FindExactPattern_PatternTooLongThrowsException (line 56) | [Test]
method FindExactPattern_SpecialCharactersInPattern (line 63) | [Test]
method FindFuzzyPattern_EmptyTextReturnsZero (line 69) | [Test]
method FindFuzzyPattern_EmptyPatternReturnsZero (line 75) | [Test]
method FindFuzzyPattern_ExactMatchFound (line 81) | [Test]
method FindFuzzyPattern_FuzzyMatchWithOneMismatch (line 87) | [Test]
method FindFuzzyPattern_FuzzyMatchWithMultipleMismatches (line 93) | [Test]
method FindFuzzyPattern_FuzzyMatchAtEnd (line 99) | [Test]
method FindFuzzyPattern_FuzzyMatchNotFound (line 105) | [Test]
method FindFuzzyPattern_PatternTooLongReturnsNegativeOne (line 111) | [Test]
FILE: Algorithms.Tests/Strings/PatternMatching/BoyerMoreTests.cs
class BoyerMooreTests (line 5) | public class BoyerMooreTests
method FindFirstOccurrence_IndexCheck (line 7) | [TestCase("HelloImATestcaseAndIWillPass", "Testcase", 8)]
FILE: Algorithms.Tests/Strings/PatternMatching/KnuthMorrisPrattSearcherTests.cs
class KnuthMorrisPrattSearcherTests (line 5) | public static class KnuthMorrisPrattSearcherTests
method FindIndexes_ItemsPresent_PassExpected (line 7) | [Test]
method FindIndexes_ItemsMissing_NoIndexesReturned (line 23) | [Test]
method LongestPrefixSuffixArray_PrefixSuffixOfLength1_PassExpected (line 38) | [Test]
method LongestPrefixSuffixArray_PrefixSuffixOfLength5_PassExpected (line 53) | [Test]
method LongestPrefixSuffixArray_PrefixSuffixOfLength0_PassExpected (line 68) | [Test]
FILE: Algorithms.Tests/Strings/PatternMatching/NaiveStringSearchTests.cs
class NaiveStringSearchTests (line 5) | public static class NaiveStringSearchTests
method ThreeMatchesFound_PassExpected (line 7) | [Test]
method OneMatchFound_PassExpected (line 23) | [Test]
method NoMatchFound_PassExpected (line 39) | [Test]
FILE: Algorithms.Tests/Strings/PatternMatching/RabinKarpTests.cs
class RabinKarpTest (line 5) | public class RabinKarpTest
method FindAllOccurrences_IndexCheck (line 7) | [TestCase("HelloImATestcaseAndIWillPass", "Testcase", new[] { 8 })]
FILE: Algorithms.Tests/Strings/PatternMatching/WildCardMatcherTests.cs
class WildCardMatcherTests (line 5) | public static class WildCardMatcherTests
method MatchPattern (line 7) | [TestCase("aab", "c*a*b", true)]
method MatchPatternThrowsArgumentException (line 25) | [Test]
FILE: Algorithms.Tests/Strings/PatternMatching/ZblockSubstringSearchTest.cs
class ZblockSubstringSearchTest (line 5) | public class ZblockSubstringSearchTest
method Test (line 7) | [TestCase("abc", "abcdef", 1)]
FILE: Algorithms.Tests/Strings/PermutationTests.cs
class PermutationTests (line 6) | public class PermutationTests
method Test_GetEveryUniquePermutation (line 8) | [TestCase("")]
method SortString (line 63) | private static string SortString(string word)
FILE: Algorithms.Tests/Strings/Similarity/CosineSimilarityTests.cs
class CosineSimilarityTests (line 5) | [TestFixture]
method Calculate_IdenticalStrings_ReturnsOne (line 8) | [Test]
method Calculate_CompletelyDifferentStrings_ReturnsZero (line 17) | [Test]
method Calculate_EmptyStrings_ReturnsZero (line 26) | [Test]
method Calculate_OneEmptyString_ReturnsZero (line 35) | [Test]
method Calculate_SameCharactersDifferentCases_ReturnsOne (line 44) | [Test]
method Calculate_SpecialCharacters_ReturnsCorrectValue (line 53) | [Test]
method Calculate_DifferentLengthWithCommonCharacters_ReturnsCorrectValue (line 62) | [Test]
method Calculate_PartiallyMatchingStrings_ReturnsCorrectValue (line 72) | [Test]
FILE: Algorithms.Tests/Strings/Similarity/DamerauLevenshteinDistanceTests.cs
class DamerauLevenshteinDistanceTests (line 5) | [TestFixture]
method Calculate_IdenticalStrings_ReturnsZero (line 8) | [Test]
method Calculate_CompletelyDifferentStrings_ReturnsLengthOfLongestString (line 17) | [Test]
method Calculate_OneEmptyString_ReturnsLengthOfOtherString (line 26) | [Test]
method Calculate_BothEmptyStrings_ReturnsZero (line 35) | [Test]
method Calculate_DifferentLengths_ReturnsCorrectValue (line 44) | [Test]
method Calculate_SpecialCharacters_ReturnsCorrectValue (line 53) | [Test]
method Calculate_DifferentCases_ReturnsCorrectValue (line 62) | [Test]
method Calculate_CommonPrefixes_ReturnsCorrectValue (line 71) | [Test]
method Calculate_CommonSuffixes_ReturnsCorrectValue (line 80) | [Test]
method Calculate_Transpositions_ReturnsCorrectValue (line 89) | [Test]
method Calculate_RepeatedCharacters_ReturnsCorrectValue (line 98) | [Test]
method Calculate_UnicodeCharacters_ReturnsCorrectValue (line 107) | [Test]
FILE: Algorithms.Tests/Strings/Similarity/HammingDistanceTests.cs
class HammingDistanceTests (line 5) | public class HammingDistanceTests
method Calculate_ReturnsCorrectHammingDistance (line 7) | [TestCase("equal", "equal", 0)]
method Calculate_ThrowsArgumentExceptionWhenStringLengthsDiffer (line 16) | [Test]
FILE: Algorithms.Tests/Strings/Similarity/JaccardDistanceTests.cs
class JaccardDistanceTests (line 5) | public class JaccardDistanceTests
method Calculate_WhenStringsAreNull_ThrowsArgumentNullException (line 10) | [TestCase("left", null)]
method Calculate_WhenProvidedWithStrings_CalculatesCorrectDistance (line 20) | [TestCase("", "", 0.0d)]
FILE: Algorithms.Tests/Strings/Similarity/JaccardSimilarityTests.cs
class JaccardSimilarityTests (line 5) | public class JaccardSimilarityTests
method Calculate_WhenStringsAreNull_ThrowsArgumentNullException (line 10) | [TestCase("left", null)]
method Calculate_WhenProvidedWithStrings_CalculatesTheCorrectDistance (line 19) | [TestCase("", "", 1.0d)]
FILE: Algorithms.Tests/Strings/Similarity/JaroSimilarityTests.cs
class JaroSimilarityTests (line 5) | public class JaroSimilarityTests
method Calculate_ReturnsCorrectJaroSimilarity (line 7) | [TestCase("equal", "equal", 1)]
FILE: Algorithms.Tests/Strings/Similarity/JaroWinklerDistanceTests.cs
class JaroWinklerDistanceTests (line 5) | public class JaroWinklerDistanceTests
method Calculate_ReturnsCorrectJaroWinklerDistance (line 7) | [TestCase("equal", "equal", 0)]
FILE: Algorithms.Tests/Strings/Similarity/OptimalStringAlignmentTests.cs
class OptimalStringAlignmentTests (line 5) | [TestFixture]
method Calculate_IdenticalStrings_ReturnsZero (line 8) | [Test]
method Calculate_FirstStringEmpty_ReturnsLengthOfSecondString (line 15) | [Test]
method Calculate_SecondStringEmpty_ReturnsLengthOfFirstString (line 22) | [Test]
method Calculate_BothStringsEmpty_ReturnsZero (line 29) | [Test]
method Calculate_OneInsertion_ReturnsOne (line 36) | [Test]
method Calculate_OneDeletion_ReturnsOne (line 43) | [Test]
method Calculate_OneSubstitution_ReturnsOne (line 50) | [Test]
method Calculate_OneTransposition_ReturnsOne (line 57) | [Test]
method Calculate_MultipleOperations_ReturnsCorrectDistance (line 64) | [Test]
FILE: Algorithms/Crypto/Digests/AsconDigest.cs
class AsconDigest (line 31) | public class AsconDigest : IDigest
type AsconParameters (line 33) | public enum AsconParameters
method AsconDigest (line 115) | public AsconDigest(AsconParameters parameters)
method GetDigestSize (line 170) | public int GetDigestSize() => 32;
method GetByteLength (line 181) | public int GetByteLength() => 8;
method Update (line 194) | public void Update(byte input)
method BlockUpdate (line 230) | public void BlockUpdate(byte[] input, int inOff, int inLen)
method BlockUpdate (line 252) | public void BlockUpdate(ReadOnlySpan<byte> input)
method DoFinal (line 308) | public int DoFinal(byte[] output, int outOff)
method DoFinal (line 327) | public int DoFinal(Span<byte> output)
method Digest (line 368) | public string Digest(byte[] input)
method Digest (line 383) | public string Digest(Span<byte> input)
method Reset (line 409) | public void Reset()
method AbsorbAndFinish (line 454) | private void AbsorbAndFinish()
method P (line 481) | private void P(int numberOfRounds)
method Round (line 520) | [MethodImpl(MethodImplOptions.AggressiveInlining)]
FILE: Algorithms/Crypto/Digests/IDigest.cs
type IDigest (line 6) | public interface IDigest
method GetDigestSize (line 17) | int GetDigestSize();
method GetByteLength (line 23) | int GetByteLength();
method Update (line 29) | void Update(byte input);
method BlockUpdate (line 37) | void BlockUpdate(byte[] input, int inOff, int inLen);
method BlockUpdate (line 43) | void BlockUpdate(ReadOnlySpan<byte> input);
method DoFinal (line 51) | int DoFinal(byte[] output, int outOff);
method DoFinal (line 58) | int DoFinal(Span<byte> output);
method Digest (line 60) | string Digest(byte[] input);
method Digest (line 62) | string Digest(Span<byte> input);
method Reset (line 67) | void Reset();
FILE: Algorithms/Crypto/Digests/Md2Digest.cs
class Md2Digest (line 20) | public class Md2Digest
method Digest (line 61) | public byte[] Digest(byte[] input)
method Reset (line 95) | private void Reset()
method ProcessBlock (line 124) | private void ProcessBlock(byte[] block)
method ProcessCheckSum (line 166) | private void ProcessCheckSum(byte[] block)
method Update (line 191) | private void Update(byte input)
method Update (line 202) | private void Update(byte[] input, int inputOffset, int length)
FILE: Algorithms/Crypto/Exceptions/CryptoException.cs
class CryptoException (line 6) | public class CryptoException : Exception
method CryptoException (line 11) | public CryptoException()
method CryptoException (line 19) | public CryptoException(string message)
method CryptoException (line 30) | public CryptoException(string message, Exception inner)
FILE: Algorithms/Crypto/Exceptions/DataLengthException.cs
class DataLengthException (line 6) | public class DataLengthException : CryptoException
method DataLengthException (line 11) | public DataLengthException()
method DataLengthException (line 19) | public DataLengthException(string message)
method DataLengthException (line 30) | public DataLengthException(string message, Exception inner)
FILE: Algorithms/Crypto/Exceptions/OutputLengthException.cs
class OutputLengthException (line 15) | public class OutputLengthException : DataLengthException
method OutputLengthException (line 24) | public OutputLengthException()
method OutputLengthException (line 35) | public OutputLengthException(string message)
method OutputLengthException (line 51) | public OutputLengthException(string message, Exception inner)
FILE: Algorithms/Crypto/Paddings/IBlockCipherPadding.cs
type IBlockCipherPadding (line 6) | public interface IBlockCipherPadding
method AddPadding (line 20) | public int AddPadding(byte[] inputData, int inputOffset);
method RemovePadding (line 28) | public byte[] RemovePadding(byte[] inputData);
method GetPaddingCount (line 36) | public int GetPaddingCount(byte[] input);
FILE: Algorithms/Crypto/Paddings/Iso10126D2Padding.cs
class Iso10126D2Padding (line 19) | public class Iso10126D2Padding : IBlockCipherPadding
method AddPadding (line 31) | public int AddPadding(byte[] inputData, int inputOffset)
method RemovePadding (line 66) | public byte[] RemovePadding(byte[] inputData)
method GetPaddingCount (line 93) | public int GetPaddingCount(byte[] input)
FILE: Algorithms/Crypto/Paddings/Iso7816D4Padding.cs
class Iso7816D4Padding (line 29) | public class Iso7816D4Padding : IBlockCipherPadding
method AddPadding (line 40) | public int AddPadding(byte[] inputData, int inputOffset)
method RemovePadding (line 76) | public byte[] RemovePadding(byte[] inputData)
method GetPaddingCount (line 109) | public int GetPaddingCount(byte[] input)
FILE: Algorithms/Crypto/Paddings/Pkcs7Padding.cs
class Pkcs7Padding (line 21) | public class Pkcs7Padding : IBlockCipherPadding
method Pkcs7Padding (line 25) | public Pkcs7Padding(int blockSize)
method AddPadding (line 49) | public int AddPadding(byte[] input, int inputOffset)
method RemovePadding (line 82) | public byte[] RemovePadding(byte[] input)
method GetPaddingCount (line 128) | public int GetPaddingCount(byte[] input)
FILE: Algorithms/Crypto/Paddings/TbcPadding.cs
class TbcPadding (line 16) | public class TbcPadding : IBlockCipherPadding
method AddPadding (line 25) | public int AddPadding(byte[] input, int inputOffset)
method RemovePadding (line 76) | public byte[] RemovePadding(byte[] input)
method GetPaddingCount (line 122) | public int GetPaddingCount(byte[] input)
FILE: Algorithms/Crypto/Paddings/X932Padding.cs
class X932Padding (line 22) | public class X932Padding(bool useRandomPadding) : IBlockCipherPadding
method AddPadding (line 35) | public int AddPadding(byte[] inputData, int inputOffset)
method RemovePadding (line 78) | public byte[] RemovePadding(byte[] inputData)
method GetPaddingCount (line 113) | public int GetPaddingCount(byte[] input)
FILE: Algorithms/Crypto/Utils/ByteEncodingUtils.cs
class ByteEncodingUtils (line 14) | public static class ByteEncodingUtils
method BigEndianToUint64 (line 27) | public static ulong BigEndianToUint64(byte[] byteStream, int offset)
method BigEndianToUint64 (line 41) | [MethodImpl(MethodImplOptions.AggressiveInlining)]
method UInt64ToBigEndian (line 57) | [MethodImpl(MethodImplOptions.AggressiveInlining)]
FILE: Algorithms/Crypto/Utils/LongUtils.cs
class LongUtils (line 12) | public static class LongUtils
method RotateLeft (line 25) | public static long RotateLeft(long i, int distance)
method RotateLeft (line 41) | public static ulong RotateLeft(ulong i, int distance)
method RotateRight (line 57) | public static long RotateRight(long i, int distance)
method RotateRight (line 72) | public static ulong RotateRight(ulong i, int distance)
FILE: Algorithms/Crypto/Utils/ValidationUtils.cs
class ValidationUtils (line 14) | public static class ValidationUtils
method CheckDataLength (line 28) | public static void CheckDataLength(byte[] buffer, int offset, int leng...
method CheckOutputLength (line 46) | public static void CheckOutputLength(bool condition, string message)
method CheckOutputLength (line 66) | public static void CheckOutputLength(byte[] buffer, int offset, int le...
method CheckOutputLength (line 86) | public static void CheckOutputLength<T>(Span<T> output, int length, st...
FILE: Algorithms/DataCompression/BurrowsWheelerTransform.cs
class BurrowsWheelerTransform (line 9) | public class BurrowsWheelerTransform
method Encode (line 16) | public (string Encoded, int Index) Encode(string s)
method Decode (line 37) | public string Decode(string s, int index)
method GetRotations (line 59) | private string[] GetRotations(string s)
FILE: Algorithms/DataCompression/HuffmanCompressor.cs
class HuffmanCompressor (line 8) | public class HuffmanCompressor(IComparisonSorter<HuffmanCompressor.ListN...
method Compress (line 20) | public (string CompressedText, Dictionary<string, string> Decompressio...
method GetListNodesFromText (line 46) | private static ListNode[] GetListNodesFromText(string text)
method GetKeys (line 63) | private (Dictionary<string, string> CompressionKeys, Dictionary<string...
method GenerateHuffmanTree (line 95) | private ListNode GenerateHuffmanTree(ListNode[] nodes)
class ListNode (line 117) | public class ListNode
method ListNode (line 119) | public ListNode(char data, double frequency)
method ListNode (line 126) | public ListNode(ListNode leftChild, ListNode rightChild)
class ListNodeComparer (line 144) | public class ListNodeComparer : IComparer<ListNode>
method Compare (line 146) | public int Compare(ListNode? x, ListNode? y)
FILE: Algorithms/DataCompression/ShannonFanoCompressor.cs
class ShannonFanoCompressor (line 8) | public class ShannonFanoCompressor(
method Compress (line 21) | public (string CompressedText, Dictionary<string, string> Decompressio...
method GetKeys (line 43) | private (Dictionary<string, string> CompressionKeys, Dictionary<string...
method GenerateShannonFanoTree (line 73) | private ListNode GenerateShannonFanoTree(ListNode node)
method GetListNodeFromText (line 93) | private ListNode GetListNodeFromText(string text)
class ListNode (line 114) | public class ListNode((char Symbol, double Frequency)[] data)
FILE: Algorithms/DataCompression/Translator.cs
class Translator (line 6) | public class Translator
method Translate (line 14) | public string Translate(string text, Dictionary<string, string> transl...
FILE: Algorithms/Encoders/AutokeyEncorder.cs
class AutokeyEncorder (line 6) | public class AutokeyEncorder
method Encode (line 16) | public string Encode(string plainText, string keyword)
method Decode (line 43) | public string Decode(string cipherText, string keyword)
FILE: Algorithms/Encoders/BlowfishEncoder.cs
class BlowfishEncoder (line 22) | public class BlowfishEncoder
method GenerateKey (line 179) | public void GenerateKey(string key)
method Encrypt (line 197) | public string Encrypt(string plainText)
method Decrypt (line 224) | public string Decrypt(string cipherText)
method HexadecimalToBinary (line 251) | private string HexadecimalToBinary(string hex)
method BinaryToHexadecimal (line 270) | private string BinaryToHexadecimal(string binaryInput)
method Xor (line 291) | private string Xor(string left, string right)
method AddAndMod (line 317) | private string AddAndMod(string left, string right)
method F (line 345) | private string F(string plainText)
method Round (line 367) | private string Round(int feistelRound, string plainText)
FILE: Algorithms/Encoders/CaesarEncoder.cs
class CaesarEncoder (line 6) | public class CaesarEncoder : IEncoder<int>
method Encode (line 17) | public string Encode(string text, int key) => Cipher(text, key);
method Decode (line 28) | public string Decode(string text, int key) => Cipher(text, -key);
method Cipher (line 30) | private static string Cipher(string text, int key)
FILE: Algorithms/Encoders/FeistelCipher.cs
class FeistelCipher (line 13) | public class FeistelCipher : IEncoder<uint>
method Encode (line 26) | public string Encode(string text, uint key)
method Decode (line 67) | public string Decode(string text, uint key)
method SplitTextToBlocks (line 119) | private static List<ulong> SplitTextToBlocks(string text)
method GetBlocksFromEncodedText (line 140) | private static List<ulong> GetBlocksFromEncodedText(string text)
method BlockModification (line 153) | private static uint BlockModification(uint block, uint key)
method GetRoundKey (line 166) | private static uint GetRoundKey(uint key, int round)
FILE: Algorithms/Encoders/HillEncoder.cs
class HillEncoder (line 10) | public class HillEncoder : IEncoder<double[,]>
method HillEncoder (line 14) | public HillEncoder() => linearEquationSolver = new GaussJordanEliminat...
method Encode (line 16) | public string Encode(string text, double[,] key)
method Decode (line 37) | public string Decode(string text, double[,] key)
method BuildStringFromArray (line 63) | private static string BuildStringFromArray(double[] arr) => new(arr.Se...
method MatrixCipher (line 71) | private static double[] MatrixCipher(double[] vector, double[,] key)
method MergeArrayList (line 91) | private static double[] MergeArrayList(double[][] list)
method SplitToCharArray (line 108) | private static char[] SplitToCharArray(string[] chunked)
method ChunkTextToArray (line 128) | private static string[] ChunkTextToArray(string text)
method FillGaps (line 148) | private static string FillGaps(string text)
method UnFillGaps (line 159) | private static string UnFillGaps(string text) => text.TrimEnd();
method MatrixDeCipher (line 167) | private double[] MatrixDeCipher(double[] vector, double[,] key)
FILE: Algorithms/Encoders/IEncoder.cs
type IEncoder (line 7) | public interface IEncoder<TKey>
method Encode (line 15) | string Encode(string text, TKey key);
method Decode (line 23) | string Decode(string text, TKey key);
FILE: Algorithms/Encoders/NysiisEncoder.cs
class NysiisEncoder (line 6) | public class NysiisEncoder
method Encode (line 15) | public string Encode(string text)
method TrimSpaces (line 31) | private string TrimSpaces(string text) => text.Replace(" ", string.Emp...
method RemoveDuplicates (line 33) | private string RemoveDuplicates(string text)
method TrimEnd (line 48) | private string TrimEnd(string text)
method ReplaceStep (line 66) | private string ReplaceStep(string text, int i)
method TryReplace (line 114) | private bool TryReplace(string text, int index, (string, string)[] opt...
method StartReplace (line 131) | private string StartReplace(string start)
method EndReplace (line 152) | private string EndReplace(string end)
method Replace (line 173) | private string Replace(string text, int index, int length, string subs...
FILE: Algorithms/Encoders/SoundexEncoder.cs
class SoundexEncoder (line 6) | public class SoundexEncoder
method Encode (line 43) | public string Encode(string text)
method CollapseLeadingDigit (line 57) | private IEnumerable<int> CollapseLeadingDigit(IEnumerable<int> numbers...
method PadTo3Numbers (line 73) | private IEnumerable<int> PadTo3Numbers(IEnumerable<int> numbers)
method OmitVowels (line 84) | private IEnumerable<int> OmitVowels(IEnumerable<int> numbers) => numbe...
method OmitHAndW (line 86) | private IEnumerable<char> OmitHAndW(string text) => text.Where(c => c ...
method CollapseDoubles (line 88) | private IEnumerable<int> CollapseDoubles(IEnumerable<int> numbers)
method ProduceNumberCoding (line 101) | private IEnumerable<int> ProduceNumberCoding(IEnumerable<char> text) =...
method MapToNumber (line 103) | private int MapToNumber(char ch)
FILE: Algorithms/Encoders/VigenereEncoder.cs
class VigenereEncoder (line 6) | public class VigenereEncoder : IEncoder<string>
method Encode (line 19) | public string Encode(string text, string key) => Cipher(text, key, cae...
method Decode (line 30) | public string Decode(string text, string key) => Cipher(text, key, cae...
method Cipher (line 32) | private string Cipher(string text, string key, Func<string, int, strin...
method AppendKey (line 52) | private string AppendKey(string key, int length)
FILE: Algorithms/Financial/PresentValue.cs
class PresentValue (line 6) | public static class PresentValue
method Calculate (line 8) | public static double Calculate(double discountRate, List<double> cashF...
FILE: Algorithms/Graph/ArticulationPoints.cs
class ArticulationPoints (line 11) | public static class ArticulationPoints
method Find (line 20) | public static HashSet<T> Find<T>(
method IsArticulationPoint (line 74) | public static bool IsArticulationPoint<T>(
method Count (line 90) | public static int Count<T>(
method Dfs (line 97) | private static void Dfs<T>(
class DfsState (line 149) | private sealed class DfsState<T>
FILE: Algorithms/Graph/BellmanFord.cs
class BellmanFord (line 9) | public class BellmanFord<T>(DirectedWeightedGraph<T> graph, Dictionary<V...
method Run (line 23) | public Dictionary<Vertex<T>, double> Run(Vertex<T> sourceVertex)
method InitializeDistances (line 31) | private void InitializeDistances(Vertex<T> sourceVertex)
method RelaxEdges (line 45) | private void RelaxEdges()
method RelaxEdgesForVertex (line 61) | private void RelaxEdgesForVertex(Vertex<T> u)
method CheckForNegativeCycles (line 81) | private void CheckForNegativeCycles()
method CheckForNegativeCyclesForVertex (line 92) | private void CheckForNegativeCyclesForVertex(Vertex<T> u)
FILE: Algorithms/Graph/BipartiteGraph.cs
class BipartiteGraph (line 12) | public static class BipartiteGraph
method IsBipartite (line 21) | public static bool IsBipartite<T>(
method GetPartitions (line 67) | public static (HashSet<T> SetA, HashSet<T> SetB)? GetPartitions<T>(
method IsBipartiteDfs (line 129) | public static bool IsBipartiteDfs<T>(
method BfsColor (line 167) | private static bool BfsColor<T>(
method DfsColor (line 203) | private static bool DfsColor<T>(
FILE: Algorithms/Graph/BreadthFirstSearch.cs
class BreadthFirstSearch (line 11) | public class BreadthFirstSearch<T> : IGraphSearch<T> where T : IComparab...
method VisitAll (line 19) | public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startV...
method Bfs (line 31) | private void Bfs(IDirectedWeightedGraph<T> graph, Vertex<T> startVerte...
FILE: Algorithms/Graph/BreadthFirstTreeTraversal.cs
class BreadthFirstTreeTraversal (line 12) | public static class BreadthFirstTreeTraversal<TKey>
method LevelOrderTraversal (line 21) | public static TKey[] LevelOrderTraversal(BinarySearchTree<TKey> tree)
method DeepestNode (line 58) | public static TKey? DeepestNode(BinarySearchTree<TKey> tree)
FILE: Algorithms/Graph/Bridges.cs
class Bridges (line 11) | public static class Bridges
method Find (line 20) | public static HashSet<(T From, T To)> Find<T>(
method IsBridge (line 75) | public static bool IsBridge<T>(
method Count (line 92) | public static int Count<T>(
method Dfs (line 99) | private static void Dfs<T>(
class DfsState (line 141) | private sealed class DfsState<T>
FILE: Algorithms/Graph/DepthFirstSearch.cs
class DepthFirstSearch (line 11) | public class DepthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
method VisitAll (line 19) | public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startV...
method Dfs (line 31) | private void Dfs(IDirectedWeightedGraph<T> graph, Vertex<T> startVerte...
FILE: Algorithms/Graph/Dijkstra/DijkstraAlgorithm.cs
class DijkstraAlgorithm (line 5) | public static class DijkstraAlgorithm
method GenerateShortestPath (line 17) | public static DistanceModel<T>[] GenerateShortestPath<T>(DirectedWeigh...
method InitializeDistanceArray (line 67) | private static DistanceModel<T>[] InitializeDistanceArray<T>(
method ValidateGraphAndStartVertex (line 83) | private static void ValidateGraphAndStartVertex<T>(DirectedWeightedGra...
FILE: Algorithms/Graph/Dijkstra/DistanceModel.cs
class DistanceModel (line 10) | public class DistanceModel<T>(Vertex<T>? vertex, Vertex<T>? previousVert...
method ToString (line 18) | public override string ToString() =>
FILE: Algorithms/Graph/FloydWarshall.cs
class FloydWarshall (line 9) | public class FloydWarshall<T>
method Run (line 19) | public double[,] Run(DirectedWeightedGraph<T> graph)
method SetupDistances (line 44) | private double[,] SetupDistances(DirectedWeightedGraph<T> graph)
FILE: Algorithms/Graph/IGraphSearch.cs
type IGraphSearch (line 5) | public interface IGraphSearch<T>
method VisitAll (line 13) | void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, ...
FILE: Algorithms/Graph/Kosaraju.cs
class Kosaraju (line 11) | public static class Kosaraju<T>
method Visit (line 20) | public static void Visit(Vertex<T> v, IDirectedWeightedGraph<T> graph,...
method Assign (line 52) | public static void Assign(Vertex<T> v, Vertex<T> root, IDirectedWeight...
method GetRepresentatives (line 75) | public static Dictionary<Vertex<T>, Vertex<T>> GetRepresentatives(IDir...
method GetScc (line 105) | public static IEnumerable<Vertex<T>>[] GetScc(IDirectedWeightedGraph<T...
FILE: Algorithms/Graph/MinimumSpanningTree/Kruskal.cs
class Kruskal (line 18) | public static class Kruskal
method Solve (line 25) | public static float[,] Solve(float[,] adjacencyMatrix)
method Solve (line 83) | public static Dictionary<int, float>[] Solve(Dictionary<int, float>[] ...
method ValidateGraph (line 127) | private static void ValidateGraph(float[,] adj)
method ValidateGraph (line 150) | private static void ValidateGraph(Dictionary<int, float>[] adj)
method Solve (line 172) | private static (int, int)[] Solve(DisjointSet<int> set, Node<int>[] no...
FILE: Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs
class PrimMatrix (line 12) | public static class PrimMatrix
method Solve (line 20) | public static float[,] Solve(float[,] adjacencyMatrix, int start)
method ValidateMatrix (line 78) | private static void ValidateMatrix(float[,] adjacencyMatrix)
method GetNextNode (line 117) | private static void GetNextNode(float[,] adjacencyMatrix, float[] key,...
FILE: Algorithms/Graph/TarjanStronglyConnectedComponents.cs
class TarjanStronglyConnectedComponents (line 11) | public class TarjanStronglyConnectedComponents
method TarjanStronglyConnectedComponents (line 21) | public TarjanStronglyConnectedComponents(int vertices)
method AddEdge (line 40) | public void AddEdge(int u, int v)
method FindSCCs (line 54) | public List<List<int>> FindSCCs()
method GetSccCount (line 70) | public int GetSccCount() => sccs.Count;
method InSameScc (line 75) | public bool InSameScc(int u, int v)
method GetScc (line 96) | public List<int>? GetScc(int vertex)
method BuildCondensationGraph (line 109) | public List<int>[] BuildCondensationGraph()
method Dfs (line 150) | private void Dfs(int at)
FILE: Algorithms/Graph/TopologicalSort.cs
class TopologicalSort (line 25) | public class TopologicalSort<T> where T : IComparable<T>
method Sort (line 61) | public List<Vertex<T>> Sort(IDirectedWeightedGraph<T> graph)
method SortKahn (line 134) | public List<Vertex<T>> SortKahn(IDirectedWeightedGraph<T> graph)
method CalculateInDegrees (line 157) | private Dictionary<Vertex<T>, int> CalculateInDegrees(IDirectedWeighte...
method IncrementNeighborInDegrees (line 190) | private void IncrementNeighborInDegrees(
method InitializeQueueWithZeroInDegreeVertices (line 210) | private Queue<Vertex<T>> InitializeQueueWithZeroInDegreeVertices(Dicti...
method ProcessVerticesInTopologicalOrder (line 233) | private List<Vertex<T>> ProcessVerticesInTopologicalOrder(
method ProcessNeighbors (line 259) | private void ProcessNeighbors(
method ValidateNoCycles (line 287) | private void ValidateNoCycles(IDirectedWeightedGraph<T> graph, List<Ve...
method DfsTopologicalSort (line 318) | private void DfsTopologicalSort(
FILE: Algorithms/Knapsack/BranchAndBoundKnapsackSolver.cs
class BranchAndBoundKnapsackSolver (line 7) | public class BranchAndBoundKnapsackSolver<T>
method Solve (line 29) | public T[] Solve(T[] items, int capacity, Func<T, int> weightSelector,...
method GetItemsFromPath (line 103) | private static T[] GetItemsFromPath(T[] items, BranchAndBoundNode last...
method ComputeUpperBound (line 136) | private static double ComputeUpperBound(BranchAndBoundNode aNode, T[] ...
FILE: Algorithms/Knapsack/BranchAndBoundNode.cs
class BranchAndBoundNode (line 3) | public class BranchAndBoundNode(int level, bool taken, BranchAndBoundNod...
FILE: Algorithms/Knapsack/DynamicProgrammingKnapsackSolver.cs
class DynamicProgrammingKnapsackSolver (line 7) | public class DynamicProgrammingKnapsackSolver<T>
method Solve (line 32) | public T[] Solve(T[] items, int capacity, Func<T, int> weightSelector,...
method GetOptimalItems (line 38) | private static T[] GetOptimalItems(T[] items, Func<T, int> weightSelec...
method Tabulate (line 57) | private static double[,] Tabulate(
FILE: Algorithms/Knapsack/IHeuristicKnapsackSolver.cs
type IHeuristicKnapsackSolver (line 9) | public interface IHeuristicKnapsackSolver<T>
method Solve (line 21) | T[] Solve(T[] items, double capacity, Func<T, double> weightSelector, ...
FILE: Algorithms/Knapsack/IKnapsackSolver.cs
type IKnapsackSolver (line 9) | public interface IKnapsackSolver<T> : IHeuristicKnapsackSolver<T>
FILE: Algorithms/Knapsack/NaiveKnapsackSolver.cs
class NaiveKnapsackSolver (line 7) | public class NaiveKnapsackSolver<T> : IHeuristicKnapsackSolver<T>
method Solve (line 18) | public T[] Solve(T[] items, double capacity, Func<T, double> weightSel...
FILE: Algorithms/LinearAlgebra/Distances/Chebyshev.cs
class Chebyshev (line 10) | public static class Chebyshev
method Distance (line 18) | public static double Distance(double[] point1, double[] point2)
FILE: Algorithms/LinearAlgebra/Distances/Euclidean.cs
class Euclidean (line 6) | public static class Euclidean
method Distance (line 14) | public static double Distance(double[] point1, double[] point2)
FILE: Algorithms/LinearAlgebra/Distances/Manhattan.cs
class Manhattan (line 10) | public static class Manhattan
method Distance (line 18) | public static double Distance(double[] point1, double[] point2)
FILE: Algorithms/LinearAlgebra/Distances/Minkowski.cs
class Minkowski (line 10) | public static class Minkowski
method Distance (line 19) | public static double Distance(double[] point1, double[] point2, int or...
FILE: Algorithms/LinearAlgebra/Eigenvalue/PowerIteration.cs
class PowerIteration (line 7) | public static class PowerIteration
method Dominant (line 26) | public static (double Eigenvalue, double[] Eigenvector) Dominant(
method Dominant (line 80) | public static (double Eigenvalue, double[] Eigenvector) Dominant(doubl...
FILE: Algorithms/MachineLearning/KNearestNeighbors.cs
class KNearestNeighbors (line 14) | public class KNearestNeighbors<TLabel>
method KNearestNeighbors (line 24) | public KNearestNeighbors(int k)
method EuclideanDistance (line 41) | public static double EuclideanDistance(double[] a, double[] b)
method AddSample (line 63) | public void AddSample(double[] features, TLabel label)
method Predict (line 79) | public TLabel Predict(double[] features)
FILE: Algorithms/MachineLearning/LinearRegression.cs
class LinearRegression (line 13) | public class LinearRegression
method Fit (line 28) | public void Fit(IList<double> x, IList<double> y)
method Predict (line 75) | public double Predict(double x)
method Predict (line 91) | public IList<double> Predict(IList<double> xValues)
FILE: Algorithms/MachineLearning/LogisticRegression.cs
class LogisticRegression (line 9) | public class LogisticRegression
method Fit (line 23) | public void Fit(double[][] x, int[] y, int epochs = 1000, double learn...
method PredictProbability (line 69) | public double PredictProbability(double[] x)
method Predict (line 82) | public int Predict(double[] x) => PredictProbability(x) >= 0.5 ? 1 : 0;
method Sigmoid (line 84) | private static double Sigmoid(double z) => 1.0 / (1.0 + Math.Exp(-z));
method Dot (line 86) | private static double Dot(double[] a, double[] b) => a.Zip(b).Sum(pair...
FILE: Algorithms/ModularArithmetic/ChineseRemainderTheorem.cs
class ChineseRemainderTheorem (line 6) | public static class ChineseRemainderTheorem
method Compute (line 28) | public static long Compute(List<long> listOfAs, List<long> listOfNs)
method Compute (line 81) | public static BigInteger Compute(List<BigInteger> listOfAs, List<BigIn...
method CheckRequirements (line 120) | private static void CheckRequirements(List<long> listOfAs, List<long> ...
method CheckRequirements (line 157) | private static void CheckRequirements(List<BigInteger> listOfAs, List<...
FILE: Algorithms/ModularArithmetic/ExtendedEuclideanAlgorithm.cs
class ExtendedEuclideanAlgorithm (line 6) | public static class ExtendedEuclideanAlgorithm
method Compute (line 15) | public static ExtendedEuclideanAlgorithmResult<long> Compute(long a, l...
method Compute (line 53) | public static ExtendedEuclideanAlgorithmResult<BigInteger> Compute(Big...
type ExtendedEuclideanAlgorithmResult (line 91) | public record ExtendedEuclideanAlgorithmResult<T>(T BezoutA, T BezoutB...
FILE: Algorithms/ModularArithmetic/ModularMultiplicativeInverse.cs
class ModularMultiplicativeInverse (line 6) | public static class ModularMultiplicativeInverse
method Compute (line 15) | public static long Compute(long a, long n)
method Compute (line 42) | public static BigInteger Compute(BigInteger a, BigInteger n)
FILE: Algorithms/NewtonSquareRoot.cs
class NewtonSquareRoot (line 3) | public static class NewtonSquareRoot
method Calculate (line 5) | public static BigInteger Calculate(BigInteger number)
method IsSquareRoot (line 29) | private static bool IsSquareRoot(BigInteger number, BigInteger root)
FILE: Algorithms/Numeric/Abs.cs
class Abs (line 6) | public static class Abs
method AbsVal (line 14) | public static T AbsVal<T>(T inputNum) where T : INumber<T>
method AbsMin (line 25) | public static T AbsMin<T>(T[] inputNums) where T : INumber<T>
method AbsMax (line 51) | public static T AbsMax<T>(T[] inputNums) where T : INumber<T>
FILE: Algorithms/Numeric/AdditionWithoutArithmetic.cs
class AdditionWithoutArithmetic (line 6) | public static class AdditionWithoutArithmetic
method CalculateAdditionWithoutArithmetic (line 14) | public static int CalculateAdditionWithoutArithmetic(int first, int se...
FILE: Algorithms/Numeric/AliquotSumCalculator.cs
class AliquotSumCalculator (line 9) | public static class AliquotSumCalculator
method CalculateAliquotSum (line 17) | public static int CalculateAliquotSum(int number)
FILE: Algorithms/Numeric/AmicableNumbersChecker.cs
class AmicableNumbersChecker (line 8) | public static class AmicableNumbersChecker
method AreAmicableNumbers (line 16) | public static bool AreAmicableNumbers(int x, int y)
method SumOfDivisors (line 21) | private static int SumOfDivisors(int number)
FILE: Algorithms/Numeric/AutomorphicNumber.cs
class AutomorphicNumber (line 7) | public static class AutomorphicNumber
method GetAutomorphicNumbers (line 19) | public static IEnumerable<int> GetAutomorphicNumbers(int lowerBound, i...
method IsAutomorphic (line 45) | public static bool IsAutomorphic(int number)
FILE: Algorithms/Numeric/BinomialCoefficient.cs
class BinomialCoefficient (line 7) | public static class BinomialCoefficient
method Calculate (line 15) | public static BigInteger Calculate(BigInteger num, BigInteger k)
FILE: Algorithms/Numeric/Ceil.cs
class Ceil (line 6) | public static class Ceil
method CeilVal (line 14) | public static T CeilVal<T>(T inputNum) where T : INumber<T>
FILE: Algorithms/Numeric/Decomposition/LU.cs
class Lu (line 7) | public static class Lu
method Decompose (line 17) | public static (double[,] L, double[,] U) Decompose(double[,] source)
method Eliminate (line 73) | public static double[] Eliminate(double[,] matrix, double[] coefficients)
FILE: Algorithms/Numeric/Decomposition/ThinSVD.cs
class ThinSvd (line 7) | public static class ThinSvd
method RandomUnitVector (line 14) | public static double[] RandomUnitVector(int dimensions)
method Decompose1D (line 33) | public static double[] Decompose1D(double[,] matrix) =>
method Decompose1D (line 43) | public static double[] Decompose1D(double[,] matrix, double epsilon, i...
method Decompose (line 69) | public static (double[,] U, double[] S, double[,] V) Decompose(double[...
method Decompose (line 79) | public static (double[,] U, double[] S, double[,] V) Decompose(
FILE: Algorithms/Numeric/DoubleFactorial.cs
class DoubleFactorial (line 10) | public static class DoubleFactorial
method Calculate (line 17) | public static BigInteger Calculate(int inputNum)
FILE: Algorithms/Numeric/EulerMethod.cs
class EulerMethod (line 14) | public static class EulerMethod
method EulerFull (line 26) | public static List<double[]> EulerFull(
method EulerStep (line 72) | private static double EulerStep(
FILE: Algorithms/Numeric/Factorial.cs
class Factorial (line 7) | public static class Factorial
method Calculate (line 14) | public static BigInteger Calculate(int inputNum)
FILE: Algorithms/Numeric/Factorization/IFactorizer.cs
type IFactorizer (line 6) | public interface IFactorizer
method TryFactor (line 14) | bool TryFactor(int n, out int factor);
FILE: Algorithms/Numeric/Factorization/TrialDivisionFactorizer.cs
class TrialDivisionFactorizer (line 6) | public class TrialDivisionFactorizer : IFactorizer
method TryFactor (line 14) | public bool TryFactor(int n, out int factor)
FILE: Algorithms/Numeric/Floor.cs
class Floor (line 6) | public static class Floor
method FloorVal (line 14) | public static T FloorVal<T>(T inputNum) where T : INumber<T>
FILE: Algorithms/Numeric/GaussJordanElimination.cs
class GaussJordanElimination (line 6) | public class GaussJordanElimination
method Solve (line 18) | public bool Solve(double[,] matrix)
method CanMatrixBeUsed (line 46) | private bool CanMatrixBeUsed(double[,] matrix) => matrix?.Length == Ro...
method PivotMatrix (line 53) | private bool PivotMatrix(ref double[,] matrix)
method FindNonZeroCoefficient (line 84) | private int FindNonZeroCoefficient(ref double[,] matrix, int col)
method Elimination (line 104) | private void Elimination(ref double[,] matrix)
method ElementaryReduction (line 126) | private bool ElementaryReduction(ref double[,] matrix)
FILE: Algorithms/Numeric/GreatestCommonDivisor/BinaryGreatestCommonDivisorFinder.cs
class BinaryGreatestCommonDivisorFinder (line 8) | public class BinaryGreatestCommonDivisorFinder : IGreatestCommonDivisorF...
method FindGcd (line 10) | public int FindGcd(int u, int v)
FILE: Algorithms/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinder.cs
class EuclideanGreatestCommonDivisorFinder (line 6) | public class EuclideanGreatestCommonDivisorFinder : IGreatestCommonDivis...
method FindGcd (line 15) | public int FindGcd(int a, int b)
FILE: Algorithms/Numeric/GreatestCommonDivisor/IGreatestCommonDivisorFinder.cs
type IGreatestCommonDivisorFinder (line 3) | public interface IGreatestCommonDivisorFinder
method FindGcd (line 5) | int FindGcd(int a, int b);
FILE: Algorithms/Numeric/JosephusProblem.cs
class JosephusProblem (line 3) | public static class JosephusProblem
method FindWinner (line 11) | public static long FindWinner(long n, long k)
FILE: Algorithms/Numeric/KeithNumberChecker.cs
class KeithNumberChecker (line 8) | public static class KeithNumberChecker
method IsKeithNumber (line 15) | public static bool IsKeithNumber(int number)
FILE: Algorithms/Numeric/KrishnamurthyNumberChecker.cs
class KrishnamurthyNumberChecker (line 9) | public static class KrishnamurthyNumberChecker
method IsKMurthyNumber (line 16) | public static bool IsKMurthyNumber(int n)
FILE: Algorithms/Numeric/MillerRabinPrimalityChecker.cs
class MillerRabinPrimalityChecker (line 11) | public static class MillerRabinPrimalityChecker
method IsProbablyPrimeNumber (line 21) | public static bool IsProbablyPrimeNumber(BigInteger n, BigInteger roun...
method IsProbablyPrimeNumber (line 29) | private static bool IsProbablyPrimeNumber(BigInteger n, BigInteger rou...
FILE: Algorithms/Numeric/ModularExponentiation.cs
class ModularExponentiation (line 8) | public class ModularExponentiation
method ModularPow (line 17) | public int ModularPow(int b, int e, int m)
FILE: Algorithms/Numeric/NarcissisticNumberChecker.cs
class NarcissisticNumberChecker (line 7) | public static class NarcissisticNumberChecker
method IsNarcissistic (line 14) | public static bool IsNarcissistic(int number)
FILE: Algorithms/Numeric/PerfectCubeChecker.cs
class PerfectCubeChecker (line 6) | public static class PerfectCubeChecker
method IsPerfectCube (line 13) | public static bool IsPerfectCube(int number)
method IsPerfectCubeBinarySearch (line 29) | public static bool IsPerfectCubeBinarySearch(int number)
FILE: Algorithms/Numeric/PerfectNumberChecker.cs
class PerfectNumberChecker (line 8) | public static class PerfectNumberChecker
method IsPerfectNumber (line 16) | public static bool IsPerfectNumber(int number)
FILE: Algorithms/Numeric/PerfectSquareChecker.cs
class PerfectSquareChecker (line 6) | public static class PerfectSquareChecker
method IsPerfectSquare (line 13) | public static bool IsPerfectSquare(int number)
FILE: Algorithms/Numeric/PrimeChecker.cs
class PrimeChecker (line 6) | public static class PrimeChecker
method IsPrime (line 15) | public static bool IsPrime(int number)
FILE: Algorithms/Numeric/Pseudoinverse/PseudoInverse.cs
class PseudoInverse (line 12) | public static class PseudoInverse
method PInv (line 20) | public static double[,] PInv(double[,] inMat)
FILE: Algorithms/Numeric/Relu.cs
class Relu (line 8) | public static class Relu
method Compute (line 15) | public static double Compute(double input)
method Compute (line 25) | public static double[] Compute(double[] input)
FILE: Algorithms/Numeric/RungeKuttaMethod.cs
class RungeKuttaMethod (line 9) | public static class RungeKuttaMethod
method ClassicRungeKuttaMethod (line 21) | public static List<double[]> ClassicRungeKuttaMethod(
FILE: Algorithms/Numeric/Series/Maclaurin.cs
class Maclaurin (line 9) | public static class Maclaurin
method Exp (line 20) | public static double Exp(double x, int n) =>
method Sin (line 32) | public static double Sin(double x, int n) =>
method Cos (line 44) | public static double Cos(double x, int n) =>
method Exp (line 56) | public static double Exp(double x, double error = 0.00001) => ErrorTer...
method Sin (line 67) | public static double Sin(double x, double error = 0.00001) => ErrorTer...
method Cos (line 78) | public static double Cos(double x, double error = 0.00001) => ErrorTer...
method ErrorTermWrapper (line 89) | private static double ErrorTermWrapper(double x, double error, Func<do...
method ExpTerm (line 117) | private static double ExpTerm(double x, int i) => Math.Pow(x, i) / (lo...
method SinTerm (line 125) | private static double SinTerm(double x, int i) =>
method CosTerm (line 134) | private static double CosTerm(double x, int i) =>
FILE: Algorithms/Numeric/Sigmoid.cs
class Sigmoid (line 10) | public static class Sigmoid
method Calculate (line 17) | public static double Calculate(double x)
FILE: Algorithms/Numeric/SoftMax.cs
class SoftMax (line 10) | public static class SoftMax
method Compute (line 21) | public static double[] Compute(double[] input)
FILE: Algorithms/Numeric/SumOfDigits.cs
class SumOfDigits (line 8) | public static class SumOfDigits
method Calculate (line 18) | public static int Calculate(int number)
FILE: Algorithms/Numeric/Tanh.cs
class Tanh (line 10) | public static class Tanh
method Compute (line 18) | public static double Compute(double input)
method Compute (line 29) | public static double[] Compute(double[] input)
FILE: Algorithms/Other/BoyerMooreMajorityVote.cs
class BoyerMooreMajorityVote (line 7) | public static class BoyerMooreMajorityVote
method FindMajority (line 14) | public static int? FindMajority(int[] nums)
method FindCandidate (line 25) | private static int FindCandidate(int[] nums)
method IsMajority (line 43) | private static bool IsMajority(int[] nums, int candidate) =>
FILE: Algorithms/Other/DecisionsConvolutions.cs
class DecisionsConvolutions (line 8) | public static class DecisionsConvolutions
method Linear (line 18) | public static List<decimal> Linear(List<List<decimal>> matrix, List<de...
method MaxMin (line 47) | public static List<decimal> MaxMin(List<List<decimal>> matrix, List<de...
FILE: Algorithms/Other/FermatPrimeChecker.cs
class FermatPrimeChecker (line 6) | public static class FermatPrimeChecker
method IsPrime (line 14) | public static bool IsPrime(int numberToTest, int timesToCheck)
FILE: Algorithms/Other/FloodFill.cs
class FloodFill (line 13) | public static class FloodFill
method BreadthFirstSearch (line 24) | public static void BreadthFirstSearch(SKBitmap bitmap, (int X, int Y) ...
method DepthFirstSearch (line 49) | public static void DepthFirstSearch(SKBitmap bitmap, (int X, int Y) lo...
method BreadthFirstFill (line 59) | private static void BreadthFirstFill(SKBitmap bitmap, (int X, int Y) l...
method DepthFirstFill (line 80) | private static void DepthFirstFill(SKBitmap bitmap, (int X, int Y) loc...
FILE: Algorithms/Other/GaussOptimization.cs
class GaussOptimization (line 10) | public class GaussOptimization
method Optimize (line 23) | public (double X1, double X2) Optimize(
FILE: Algorithms/Other/GeoLocation.cs
class GeoLocation (line 3) | public static class GeoLocation
method CalculateDistanceFromLatLng (line 16) | public static double CalculateDistanceFromLatLng(double lat1, double l...
FILE: Algorithms/Other/Geofence.cs
class Geofence (line 3) | public class Geofence(double latitude, double longitude, double radiusIn...
method IsInside (line 18) | public bool IsInside(double userLatitude, double userLongitude)
FILE: Algorithms/Other/Geohash.cs
class Geohash (line 3) | public static class Geohash
method Encode (line 21) | public static string Encode(double latitude, double longitude)
FILE: Algorithms/Other/Int2Binary.cs
class Int2Binary (line 6) | public static class Int2Binary
method Int2Bin (line 13) | public static string Int2Bin(ushort input)
method Int2Bin (line 40) | public static string Int2Bin(uint input)
method Int2Bin (line 67) | public static string Int2Bin(ulong input)
FILE: Algorithms/Other/JulianEaster.cs
class JulianEaster (line 7) | public static class JulianEaster
method Calculate (line 14) | public static DateTime Calculate(int year)
FILE: Algorithms/Other/KadanesAlgorithm.cs
class KadanesAlgorithm (line 9) | public static class KadanesAlgorithm
method FindMaximumSubarraySum (line 25) | public static int FindMaximumSubarraySum(int[] array)
method FindMaximumSubarrayWithIndices (line 68) | public static (int MaxSum, int StartIndex, int EndIndex) FindMaximumSu...
method FindMaximumSubarraySum (line 123) | public static long FindMaximumSubarraySum(long[] array)
FILE: Algorithms/Other/KochSnowflake.cs
class KochSnowflake (line 21) | public static class KochSnowflake
method Iterate (line 34) | public static List<Vector2> Iterate(List<Vector2> initialVectors, int ...
method GetKochSnowflake (line 52) | public static SKBitmap GetKochSnowflake(
method IterationStep (line 84) | private static List<Vector2> IterationStep(List<Vector2> vectors)
method Rotate (line 109) | private static Vector2 Rotate(Vector2 vector, float angleInDegrees)
method GetBitmap (line 124) | private static SKBitmap GetBitmap(
FILE: Algorithms/Other/Luhn.cs
class Luhn (line 11) | public static class Luhn
method Validate (line 21) | public static bool Validate(string number) => GetSum(number) % 10 == 0;
method GetLostNum (line 29) | public static int GetLostNum(string number)
method GetSum (line 46) | private static int GetSum(string number)
FILE: Algorithms/Other/Mandelbrot.cs
class Mandelbrot (line 22) | public static class Mandelbrot
method GetBitmap (line 43) | public static SKBitmap GetBitmap(
method BlackAndWhiteColorMap (line 104) | private static SKColor BlackAndWhiteColorMap(double distance) =>
method ColorCodedColorMap (line 115) | private static SKColor ColorCodedColorMap(double distance)
method GetDistance (line 155) | private static double GetDistance(double figureX, double figureY, int ...
FILE: Algorithms/Other/ParetoOptimization.cs
class ParetoOptimization (line 10) | public class ParetoOptimization
method Optimize (line 17) | public List<List<decimal>> Optimize(List<List<decimal>> matrix)
method GetMinimalPairwiseDifference (line 51) | private decimal GetMinimalPairwiseDifference(List<decimal> arr1, List<...
FILE: Algorithms/Other/PollardsRhoFactorizing.cs
class PollardsRhoFactorizing (line 9) | public static class PollardsRhoFactorizing
method Calculate (line 11) | public static int Calculate(int number)
method Fun_g (line 31) | private static int Fun_g(int x, int p)
FILE: Algorithms/Other/RGBHSVConversion.cs
class RgbHsvConversion (line 14) | public static class RgbHsvConversion
method HsvToRgb (line 23) | public static (byte Red, byte Green, byte Blue) HsvToRgb(
method RgbToHsv (line 60) | public static (double Hue, double Saturation, double Value) RgbToHsv(
method GetRgbBySection (line 95) | private static (byte Red, byte Green, byte Blue) GetRgbBySection(
method ConvertToByte (line 145) | private static byte ConvertToByte(double input) => (byte)Math.Round(25...
FILE: Algorithms/Other/SieveOfEratosthenes.cs
class SieveOfEratosthenes (line 6) | public class SieveOfEratosthenes
method SieveOfEratosthenes (line 17) | public SieveOfEratosthenes(long maximumNumberToCheck)
method IsPrime (line 48) | public bool IsPrime(long numberToCheck) => primes[numberToCheck];
method GetPrimes (line 54) | public IEnumerable<long> GetPrimes()
FILE: Algorithms/Other/Triangulator.cs
class Triangulator (line 3) | public class Triangulator
method CalculatePosition (line 5) | public (double Latitude, double Longitude) CalculatePosition(List<(dou...
method ToRadians (line 39) | private double ToRadians(double degrees)
method ToDegrees (line 44) | private double ToDegrees(double radians)
FILE: Algorithms/Other/WelfordsVariance.cs
class WelfordsVariance (line 5) | public class WelfordsVariance
method WelfordsVariance (line 26) | public WelfordsVariance()
method WelfordsVariance (line 32) | public WelfordsVariance(double[] values)
method AddValue (line 39) | public void AddValue(double newValue)
method AddRange (line 45) | public void AddRange(double[] values)
method AddValueToDataset (line 55) | private void AddValueToDataset(double newValue)
FILE: Algorithms/Problems/DynamicProgramming/CoinChange/DynamicCoinChangeSolver.cs
class DynamicCoinChangeSolver (line 3) | public static class DynamicCoinChangeSolver
method GenerateSingleCoinChanges (line 13) | public static int[] GenerateSingleCoinChanges(int coin, int[] coins)
method GenerateChangesDictionary (line 51) | public static Dictionary<int, int[]> GenerateChangesDictionary(int coi...
method GetMinimalNextCoin (line 74) | public static int GetMinimalNextCoin(int coin, Dictionary<int, int[]> ...
method MakeCoinChangeDynamic (line 109) | public static int[] MakeCoinChangeDynamic(int coin, int[] coins)
method ValidateCoin (line 130) | private static void ValidateCoin(int coin)
method ValidateCoinsArray (line 138) | private static void ValidateCoinsArray(int[] coinsArray)
FILE: Algorithms/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistance.cs
class LevenshteinDistance (line 11) | public static class LevenshteinDistance
method Calculate (line 20) | public static int Calculate(string source, string target)
FILE: Algorithms/Problems/GraphColoring/GraphColoringSolver.cs
class GraphColoringSolver (line 34) | public sealed class GraphColoringSolver
method ColorGraph (line 67) | public int[] ColorGraph(bool[,] adjacencyMatrix, int numColors)
method ColorVertex (line 120) | private bool ColorVertex(bool[,] adjacencyMatrix, int[] colors, int ve...
method IsSafeToColor (line 166) | private bool IsSafeToColor(bool[,] adjacencyMatrix, int[] colors, int ...
FILE: Algorithms/Problems/JobScheduling/IntervalSchedulingSolver.cs
class IntervalSchedulingSolver (line 11) | public static class IntervalSchedulingSolver
method Schedule (line 18) | public static List<Job> Schedule(IEnumerable<Job> jobs)
FILE: Algorithms/Problems/JobScheduling/Job.cs
type Job (line 6) | public record Job(int Start, int End);
FILE: Algorithms/Problems/KnightTour/OpenKnightTour.cs
class OpenKnightTour (line 30) | public sealed class OpenKnightTour
method Tour (line 53) | public int[,] Tour(int n)
method KnightTourHelper (line 92) | private bool KnightTourHelper(int[,] board, (int Row, int Col) pos, in...
method GetValidMoves (line 130) | private IEnumerable<(int R, int C)> GetValidMoves((int R, int C) posit...
method IsComplete (line 161) | private bool IsComplete(int[,] board)
FILE: Algorithms/Problems/NQueens/BacktrackingNQueensSolver.cs
class BacktrackingNQueensSolver (line 3) | public class BacktrackingNQueensSolver
method BacktrackSolve (line 11) | public IEnumerable<bool[,]> BacktrackSolve(int n)
method BacktrackSolve (line 21) | private static IEnumerable<bool[,]> BacktrackSolve(bool[,] board, int ...
method HandleIntermediateColumn (line 29) | private static IEnumerable<bool[,]> HandleIntermediateColumn(bool[,] b...
method HandleLastColumn (line 48) | private static IEnumerable<bool[,]> HandleLastColumn(bool[,] board)
method CanPlace (line 72) | private static bool CanPlace(bool[,] board, int row, int col)
FILE: Algorithms/Problems/StableMarriage/Accepter.cs
class Accepter (line 3) | public class Accepter
method PrefersOverCurrent (line 9) | public bool PrefersOverCurrent(Proposer newProposer) =>
FILE: Algorithms/Problems/StableMarriage/GaleShapley.cs
class GaleShapley (line 3) | public static class GaleShapley
method Match (line 13) | public static void Match(Proposer[] proposers, Accepter[] accepters)
method IsEngaged (line 26) | private static bool IsEngaged(Proposer proposer) => proposer.EngagedTo...
method DoSingleMatchingRound (line 28) | private static void DoSingleMatchingRound(IEnumerable<Proposer> propos...
method Free (line 51) | private static void Free(Proposer proposer)
method Engage (line 56) | private static void Engage(Proposer proposer, Accepter accepter)
FILE: Algorithms/Problems/StableMarriage/Proposer.cs
class Proposer (line 3) | public class Proposer
FILE: Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs
class TravelingSalesmanSolver (line 7) | public static class TravelingSalesmanSolver
method SolveBruteForce (line 15) | public static (int[] Route, double Distance) SolveBruteForce(double[,]...
method SolveNearestNeighbor (line 67) | public static (int[] Route, double Distance) SolveNearestNeighbor(doub...
method Permute (line 118) | private static IEnumerable<int[]> Permute(int[] arr)
FILE: Algorithms/RecommenderSystem/CollaborativeFiltering.cs
class CollaborativeFiltering (line 3) | public class CollaborativeFiltering(ISimilarityCalculator similarityCalc...
method CalculateSimilarity (line 13) | public double CalculateSimilarity(Dictionary<string, double> user1Rati...
method PredictRating (line 59) | public double PredictRating(string targetItem, string targetUser, Dict...
FILE: Algorithms/RecommenderSystem/ISimilarityCalculator.cs
type ISimilarityCalculator (line 3) | public interface ISimilarityCalculator
method CalculateSimilarity (line 5) | double CalculateSimilarity(Dictionary<string, double> user1Ratings, Di...
FILE: Algorithms/Search/AStar/AStar.cs
class AStar (line 6) | public static class AStar
method ResetNodes (line 12) | public static void ResetNodes(List<Node> nodes)
method GeneratePath (line 28) | public static List<Node> GeneratePath(Node target)
method Compute (line 48) | public static List<Node> Compute(Node from, Node to)
method AddOrUpdateConnected (line 101) | private static void AddOrUpdateConnected(Node current, Node to, Priori...
FILE: Algorithms/Search/AStar/Node.cs
class Node (line 6) | public class Node(VecN position, bool traversable, double traverseMultip...
method CompareTo (line 63) | public int CompareTo(Node? other) => TotalCost.CompareTo(other?.TotalC...
method Equals (line 65) | public bool Equals(Node? other) => CompareTo(other) == 0;
method Equals (line 79) | public override bool Equals(object? obj) => obj is Node other && Equal...
method GetHashCode (line 81) | public override int GetHashCode() =>
method DistanceTo (line 91) | public double DistanceTo(Node other) => Math.Sqrt(Position.SqrDistance...
FILE: Algorithms/Search/AStar/NodeState.cs
type NodeState (line 6) | public enum NodeState
FILE: Algorithms/Search/AStar/PathfindingException.cs
class PathfindingException (line 6) | public class PathfindingException(string message) : Exception(message)
FILE: Algorithms/Search/AStar/PriorityQueue.cs
class PriorityQueue (line 12) | public class PriorityQueue<T>
method PriorityQueue (line 20) | public PriorityQueue(bool isDescending = false)
method PriorityQueue (line 31) | public PriorityQueue(int capacity, bool isDescending = false)
method PriorityQueue (line 42) | public PriorityQueue(IEnumerable<T> collection, bool isDescending = fa...
method Enqueue (line 61) | public void Enqueue(T x)
method Dequeue (line 88) | public T Dequeue()
method Peek (line 124) | public T Peek()
method Clear (line 137) | public void Clear() => list.Clear();
method GetData (line 143) | public List<T> GetData() => list;
FILE: Algorithms/Search/AStar/VecN.cs
type VecN (line 10) | public struct VecN(params double[] vals) : IEquatable<VecN>
method SqrLength (line 23) | public double SqrLength()
method Length (line 38) | public double Length() => Math.Sqrt(SqrLength());
method Distance (line 45) | public double Distance(VecN other)
method SqrDistance (line 56) | public double SqrDistance(VecN other)
method Subtract (line 67) | public VecN Subtract(VecN other)
method Equals (line 94) | public bool Equals(VecN other)
FILE: Algorithms/Search/BinarySearcher.cs
class BinarySearcher (line 11) | public class BinarySearcher<T> where T : IComparable<T>
method FindIndex (line 19) | public int FindIndex(T[] sortedData, T item)
FILE: Algorithms/Search/BoyerMoore.cs
class BoyerMoore (line 7) | public static class BoyerMoore<T> where T : IComparable
method FindMajority (line 9) | public static T? FindMajority(IEnumerable<T> input)
method FindMajorityCandidate (line 22) | private static T FindMajorityCandidate(IEnumerable<T> input, int length)
method VerifyMajority (line 49) | private static bool VerifyMajority(IEnumerable<T> input, int size, T c...
FILE: Algorithms/Search/FastSearcher.cs
class FastSearcher (line 13) | public class FastSearcher
method FindIndex (line 23) | public int FindIndex(Span<int> array, int item)
method ComputeIndices (line 46) | private (int Left, int Right) ComputeIndices(Span<int> array, int item)
method SelectSegment (line 64) | private (int From, int To) SelectSegment(Span<int> array, int left, in...
FILE: Algorithms/Search/FibonacciSearcher.cs
class FibonacciSearcher (line 7) | public class FibonacciSearcher<T> where T : IComparable<T>
method FindIndex (line 20) | public int FindIndex(T[] array, T item)
FILE: Algorithms/Search/InterpolationSearch.cs
class InterpolationSearch (line 6) | public static class InterpolationSearch
method FindIndex (line 18) | public static int FindIndex(int[] sortedArray, int val)
FILE: Algorithms/Search/JumpSearcher.cs
class JumpSearcher (line 10) | public class JumpSearcher<T> where T : IComparable<T>
method FindIndex (line 18) | public int FindIndex(T[] sortedArray, T searchItem)
FILE: Algorithms/Search/LinearSearcher.cs
class LinearSearcher (line 9) | public class LinearSearcher<T>
method Find (line 19) | public T Find(T[] data, Func<T, bool> term)
method FindIndex (line 40) | public int FindIndex(T[] data, Func<T, bool> term)
FILE: Algorithms/Search/RecursiveBinarySearcher.cs
class RecursiveBinarySearcher (line 7) | public class RecursiveBinarySearcher<T> where T : IComparable<T>
method FindIndex (line 19) | public int FindIndex(IList<T>? collection, T item)
method FindIndex (line 43) | private int FindIndex(IList<T> collection, T item, int leftIndex, int ...
FILE: Algorithms/Sequences/AllOnesSequence.cs
class AllOnesSequence (line 11) | public class AllOnesSequence : ISequence
FILE: Algorithms/Sequences/AllThreesSequence.cs
class AllThreesSequence (line 11) | public class AllThreesSequence : ISequence
FILE: Algorithms/Sequences/AllTwosSequence.cs
class AllTwosSequence (line 11) | public class AllTwosSequence : ISequence
FILE: Algorithms/Sequences/BinaryPrimeConstantSequence.cs
class BinaryPrimeConstantSequence (line 15) | public class BinaryPrimeConstantSequence : ISequence
FILE: Algorithms/Sequences/BinomialSequence.cs
class BinomialSequence (line 14) | public class BinomialSequence : ISequence
method BinomialCoefficient (line 38) | private static BigInteger BinomialCoefficient(long n, long k)
method GenerateRow (line 53) | private static IEnumerable<BigInteger> GenerateRow(long n)
FILE: Algorithms/Sequences/CakeNumbersSequence.cs
class CakeNumbersSequence (line 12) | public class CakeNumbersSequence : ISequence
FILE: Algorithms/Sequences/CatalanSequence.cs
class CatalanSequence (line 14) | public class CatalanSequence : ISequence
FILE: Algorithms/Sequences/CentralPolygonalNumbersSequence.cs
class CentralPolygonalNumbersSequence (line 12) | public class CentralPolygonalNumbersSequence : ISequence
FILE: Algorithms/Sequences/CubesSequence.cs
class CubesSequence (line 14) | public class CubesSequence : ISequence
FILE: Algorithms/Sequences/DivisorsCountSequence.cs
class DivisorsCountSequence (line 11) | public class DivisorsCountSequence : ISequence
FILE: Algorithms/Sequences/EuclidNumbersSequence.cs
class EuclidNumbersSequence (line 14) | public class EuclidNumbersSequence : ISequence
FILE: Algorithms/Sequences/EulerTotientSequence.cs
class EulerTotientSequence (line 14) | public class EulerTotientSequence : ISequence
method PrimeFactors (line 86) | private static IEnumerable<BigInteger> PrimeFactors(BigInteger target)
FILE: Algorithms/Sequences/FactorialSequence.cs
class FactorialSequence (line 14) | public class FactorialSequence : ISequence
FILE: Algorithms/Sequences/FermatNumbersSequence.cs
class FermatNumbersSequence (line 14) | public class FermatNumbersSequence : ISequence
FILE: Algorithms/Sequences/FermatPrimesSequence.cs
class FermatPrimesSequence (line 14) | public class FermatPrimesSequence : ISequence
FILE: Algorithms/Sequences/FibonacciSequence.cs
class FibonacciSequence (line 14) | public class FibonacciSequence : ISequence
FILE: Algorithms/Sequences/GolombsSequence.cs
class GolombsSequence (line 14) | public class GolombsSequence : ISequence
FILE: Algorithms/Sequences/ISequence.cs
type ISequence (line 6) | public interface ISequence
FILE: Algorithms/Sequences/KolakoskiSequence.cs
class KolakoskiSequence (line 14) | public class KolakoskiSequence : ISequence
FILE: Algorithms/Sequences/KolakoskiSequence2.cs
class KolakoskiSequence2 (line 14) | public class KolakoskiSequence2 : ISequence
FILE: Algorithms/Sequences/KummerNumbersSequence.cs
class KummerNumbersSequence (line 15) | public class KummerNumbersSequence : ISequence
FILE: Algorithms/Sequences/LucasNumbersBeginningAt2Sequence.cs
class LucasNumbersBeginningAt2Sequence (line 14) | public class LucasNumbersBeginningAt2Sequence : ISequence
FILE: Algorithms/Sequences/MakeChangeSequence.cs
class MakeChangeSequence (line 11) | public class MakeChangeSequence : ISequence
FILE: Algorithms/Sequences/MatchstickTriangleSequence.cs
class MatchstickTriangleSequence (line 15) | public class MatchstickTriangleSequence : ISequence
FILE: Algorithms/Sequences/NaturalSequence.cs
class NaturalSequence (line 14) | public class NaturalSequence : ISequence
FILE: Algorithms/Sequences/NegativeIntegersSequence.cs
class NegativeIntegersSequence (line 14) | public class NegativeIntegersSequence : ISequence
FILE: Algorithms/Sequences/NumberOfBooleanFunctionsSequence.cs
class NumberOfBooleanFunctionsSequence (line 15) | public class NumberOfBooleanFunctionsSequence : ISequence
FILE: Algorithms/Sequences/NumberOfPrimesByNumberOfDigitsSequence.cs
class NumberOfPrimesByNumberOfDigitsSequence (line 15) | public class NumberOfPrimesByNumberOfDigitsSequence : ISequence
FILE: Algorithms/Sequences/NumberOfPrimesByPowersOf10Sequence.cs
class NumberOfPrimesByPowersOf10Sequence (line 14) | public class NumberOfPrimesByPowersOf10Sequence : ISequence
FILE: Algorithms/Sequences/OnesCountingSequence.cs
class OnesCountingSequence (line 11) | public class OnesCountingSequence : ISequence
method GenerateFractalCount (line 67) | private static IEnumerable<BigInteger> GenerateFractalCount(BigInteger...
FILE: Algorithms/Sequences/PowersOf10Sequence.cs
class PowersOf10Sequence (line 14) | public class PowersOf10Sequence : ISequence
FILE: Algorithms/Sequences/PowersOf2Sequence.cs
class PowersOf2Sequence (line 14) | public class PowersOf2Sequence : ISequence
FILE: Algorithms/Sequences/PrimePiSequence.cs
class PrimePiSequence (line 14) | public class PrimePiSequence : ISequence
FILE: Algorithms/Sequences/PrimesSequence.cs
class PrimesSequence (line 14) | public class PrimesSequence : ISequence
FILE: Algorithms/Sequences/PrimorialNumbersSequence.cs
class PrimorialNumbersSequence (line 14) | public class PrimorialNumbersSequence : ISequence
FILE: Algorithms/Sequences/RecamansSequence.cs
class RecamansSequence (line 14) | public class RecamansSequence : ISequence
FILE: Algorithms/Sequences/SquaresSequence.cs
class SquaresSequence (line 14) | public class SquaresSequence : ISequence
FILE: Algorithms/Sequences/TetrahedralSequence.cs
class TetrahedralSequence (line 14) | public class TetrahedralSequence : ISequence
FILE: Algorithms/Sequences/TetranacciNumbersSequence.cs
class TetranacciNumbersSequence (line 11) | public class TetranacciNumbersSequence : ISequence
FILE: Algorithms/Sequences/ThreeNPlusOneStepsSequence.cs
class ThreeNPlusOneStepsSequence (line 14) | public class ThreeNPlusOneStepsSequence : ISequence
FILE: Algorithms/Sequences/TribonacciNumbersSequence.cs
class TribonacciNumbersSequence (line 11) | public class TribonacciNumbersSequence : ISequence
FILE: Algorithms/Sequences/VanEcksSequence.cs
class VanEcksSequence (line 11) | public class VanEcksSequence : ISequence
FILE: Algorithms/Sequences/ZeroSequence.cs
class ZeroSequence (line 11) | public class ZeroSequence : ISequence
FILE: Algorithms/Shufflers/FisherYatesShuffler.cs
class FisherYatesShuffler (line 8) | public class FisherYatesShuffler<T> : IShuffler<T>
method Shuffle (line 18) | public void Shuffle(T[] array, int? seed = null)
FILE: Algorithms/Shufflers/IShuffler.cs
type IShuffler (line 7) | public interface IShuffler<in T>
method Shuffle (line 13) | void Shuffle(T[] array, int? seed = null);
FILE: Algorithms/Shufflers/LINQShuffler.cs
class LinqShuffler (line 9) | public class LinqShuffler<T>
method Shuffle (line 18) | public T[] Shuffle(T[] array, int? seed = null)
FILE: Algorithms/Shufflers/NaiveShuffler.cs
class NaiveShuffler (line 8) | public class NaiveShuffler<T> : IShuffler<T>
method Shuffle (line 17) | public void Shuffle(T[] array, int? seed = null)
FILE: Algorithms/Shufflers/RecursiveShuffler.cs
class RecursiveShuffler (line 9) | public class RecursiveShuffler<T> : IShuffler<T>
method Shuffle (line 16) | public void Shuffle(T[] array, int? seed = null)
method Shuffle (line 30) | private void Shuffle(T[] array, int items, int? seed)
FILE: Algorithms/Sorters/Comparison/BasicTimSorter.cs
class BasicTimSorter (line 11) | public class BasicTimSorter<T>(IComparer<T> comparer)
method Sort (line 20) | public void Sort(T[] array)
method InsertionSort (line 52) | private void InsertionSort(T[] array, int left, int right)
method Merge (line 78) | private void Merge(T[] array, int left, int mid, int right)
FILE: Algorithms/Sorters/Comparison/BinaryInsertionSorter.cs
class BinaryInsertionSorter (line 7) | public class BinaryInsertionSorter<T> : IComparisonSorter<T>
method Sort (line 19) | public void Sort(T[] array, IComparer<T> comparer)
method BinarySearch (line 42) | private static int BinarySearch(T[] array, int from, int to, T target,...
FILE: Algorithms/Sorters/Comparison/BogoSorter.cs
class BogoSorter (line 7) | public class BogoSorter<T> : IComparisonSorter<T>
method Sort (line 22) | public void Sort(T[] array, IComparer<T> comparer)
method IsSorted (line 30) | private bool IsSorted(T[] array, IComparer<T> comparer)
method Shuffle (line 43) | private void Shuffle(T[] array)
FILE: Algorithms/Sorters/Comparison/BubbleSorter.cs
class BubbleSorter (line 7) | public class BubbleSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/CocktailSorter.cs
class CocktailSorter (line 8) | public class CocktailSorter<T> : IComparisonSorter<T>
method Sort (line 15) | public void Sort(T[] array, IComparer<T> comparer) => CocktailSort(arr...
method CocktailSort (line 17) | private static void CocktailSort(IList<T> array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/CombSorter.cs
class CombSorter (line 7) | public class CombSorter<T>(double shrinkFactor = 1.3) : IComparisonSorte...
method Sort (line 23) | public void Sort(T[] array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/CycleSorter.cs
class CycleSorter (line 11) | public class CycleSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
method MoveCycle (line 26) | private static void MoveCycle(T[] array, int startingIndex, IComparer<...
method SkipSameElements (line 53) | private static int SkipSameElements(T[] array, int nextIndex, T item, ...
method CountSmallerElements (line 63) | private static int CountSmallerElements(T[] array, int startingIndex, ...
FILE: Algorithms/Sorters/Comparison/ExchangeSorter.cs
class ExchangeSorter (line 7) | public class ExchangeSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/GnomeSorter.cs
class GnomeSorter (line 7) | public class GnomeSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
method Swap (line 36) | public void Swap(T[] array, int index1, int index2)
FILE: Algorithms/Sorters/Comparison/HeapSorter.cs
class HeapSorter (line 8) | public class HeapSorter<T> : IComparisonSorter<T>
method Sort (line 15) | public void Sort(T[] array, IComparer<T> comparer) => HeapSort(array, ...
method HeapSort (line 17) | private static void HeapSort(IList<T> data, IComparer<T> comparer)
method MakeHeap (line 36) | private static void MakeHeap(IList<T> input, int heapSize, int index, ...
FILE: Algorithms/Sorters/Comparison/IComparisonSorter.cs
type IComparisonSorter (line 7) | public interface IComparisonSorter<T>
method Sort (line 14) | void Sort(T[] array, IComparer<T> comparer);
FILE: Algorithms/Sorters/Comparison/InsertionSorter.cs
class InsertionSorter (line 7) | public class InsertionSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/MedianOfThreeQuickSorter.cs
class MedianOfThreeQuickSorter (line 7) | public sealed class MedianOfThreeQuickSorter<T> : QuickSorter<T>
method SelectPivot (line 9) | protected override T SelectPivot(T[] array, IComparer<T> comparer, int...
method FindMedian (line 18) | private static T FindMedian(IComparer<T> comparer, T a, T b, T c)
FILE: Algorithms/Sorters/Comparison/MergeSorter.cs
class MergeSorter (line 9) | public class MergeSorter<T> : IComparisonSorter<T>
method Sort (line 21) | public void Sort(T[] array, IComparer<T> comparer)
method Merge (line 34) | private static void Merge(T[] array, T[] left, T[] right, IComparer<T>...
method Split (line 57) | private static (T[] Left, T[] Right) Split(T[] array)
FILE: Algorithms/Sorters/Comparison/MiddlePointQuickSorter.cs
class MiddlePointQuickSorter (line 7) | public sealed class MiddlePointQuickSorter<T> : QuickSorter<T>
method SelectPivot (line 9) | protected override T SelectPivot(T[] array, IComparer<T> comparer, int...
FILE: Algorithms/Sorters/Comparison/PancakeSorter.cs
class PancakeSorter (line 7) | public class PancakeSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
method Flip (line 46) | private void Flip(T[] array, int i)
method FindMax (line 62) | private int FindMax(T[] array, int n, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/QuickSorter.cs
class QuickSorter (line 7) | public abstract class QuickSorter<T> : IComparisonSorter<T>
method Sort (line 19) | public void Sort(T[] array, IComparer<T> comparer) => Sort(array, comp...
method SelectPivot (line 21) | protected abstract T SelectPivot(T[] array, IComparer<T> comparer, int...
method Sort (line 23) | private void Sort(T[] array, IComparer<T> comparer, int left, int right)
method Partition (line 35) | private int Partition(T[] array, IComparer<T> comparer, int left, int ...
FILE: Algorithms/Sorters/Comparison/RandomPivotQuickSorter.cs
class RandomPivotQuickSorter (line 7) | public sealed class RandomPivotQuickSorter<T> : QuickSorter<T>
method SelectPivot (line 11) | protected override T SelectPivot(T[] array, IComparer<T> comparer, int...
FILE: Algorithms/Sorters/Comparison/SelectionSorter.cs
class SelectionSorter (line 7) | public class SelectionSorter<T> : IComparisonSorter<T>
method Sort (line 18) | public void Sort(T[] array, IComparer<T> comparer)
FILE: Algorithms/Sorters/Comparison/ShellSorter.cs
class ShellSorter (line 7) | public class ShellSorter<T> : IComparisonSorter<T>
method Sort (line 19) | public void Sort(T[] array, IComparer<T> comparer)
method GappedBubbleSort (line 30) | private static void GappedBubbleSort(T[] array, IComparer<T> comparer,...
FILE: Algorithms/Sorters/Comparison/TimSorter.cs
class TimSorter (line 25) | public class TimSorter<T> : IComparisonSorter<T>
class TimChunk (line 42) | private class TimChunk<Tc>
method TimSorter (line 53) | public TimSorter(TimSorterSettings settings, IComparer<T> comparer)
method Sort (line 80) | public void Sort(T[] array, IComparer<T> comparer)
method MinRunLength (line 141) | private static int MinRunLength(int total, int minRun)
method ReverseRange (line 159) | private static void ReverseRange(T[] array, int start, int end)
method NeedsMerge (line 177) | private static bool NeedsMerge(TimChunk<T> left, TimChunk<T> right, re...
method FinalizeMerge (line 202) | private static void FinalizeMerge(TimChunk<T> left, TimChunk<T> right,...
method CountRunAndMakeAscending (line 239) | private int CountRunAndMakeAscending(T[] array, int start)
method BinarySort (line 276) | private void BinarySort(T[] array, int start, int end, int first)
method BinarySearch (line 293) | private int BinarySearch(T[] array, int left, int right, T target)
method MergeCollapse (line 313) | private void MergeCollapse(T[] array)
method MergeForceCollapse (line 338) | private void MergeForceCollapse(T[] array)
method MergeAt (line 352) | private void MergeAt(T[] array, int index)
method Merge (line 389) | private void Merge(T[] array, int baseA, int lenA, int baseB, int lenB)
method RunMerge (line 431) | private bool RunMerge(TimChunk<T> left, TimChunk<T> right, ref int des...
method StableMerge (line 462) | private bool StableMerge(TimChunk<T> left, TimChunk<T> right, ref int ...
method GallopMerge (line 492) | private bool GallopMerge(TimChunk<T> left, TimChunk<T> right, ref int ...
FILE: Algorithms/Sorters/Comparison/TimSorterSettings.cs
class TimSorterSettings (line 3) | public class TimSorterSettings(int minMerge = 32, int minGallop = 7)
FILE: Algorithms/Sorters/External/ExternalMergeSorter.cs
class ExternalMergeSorter (line 3) | public class ExternalMergeSorter<T> : IExternalSorter<T>
method Sort (line 5) | public void Sort(
method Merge (line 66) | private static void Merge(
method Copy (line 118) | private static void Copy(ISequentialStorageReader<T> from, ISequential...
FILE: Algorithms/Sorters/External/IExternalSorter.cs
type IExternalSorter (line 3) | public interface IExternalSorter<T>
method Sort (line 10) | void Sort(ISequentialStorage<T> mainMemory, ISequentialStorage<T> temp...
FILE: Algorithms/Sorters/External/ISequentialStorage.cs
type ISequentialStorage (line 3) | public interface ISequentialStorage<T>
method GetReader (line 7) | ISequentialStorageReader<T> GetReader();
method GetWriter (line 9) | ISequentialStorageWriter<T> GetWriter();
FILE: Algorithms/Sorters/External/ISequentialStorageReader.cs
type ISequentialStorageReader (line 3) | public interface ISequentialStorageReader<out T> : IDisposable
method Read (line 5) | T Read();
FILE: Algorithms/Sorters/External/ISequentialStorageWriter.cs
type ISequentialStorageWriter (line 3) | public interface ISequentialStorageWriter<in T> : IDisposable
method Write (line 5) | void Write(T value);
FILE: Algorithms/Sorters/External/Storages/IntFileStorage.cs
class IntFileStorage (line 5) | public class IntFileStorage(string filename, int length) : ISequentialSt...
method GetReader (line 11) | public ISequentialStorageReader<int> GetReader() => new FileReader(fil...
method GetWriter (line 13) | public ISequentialStorageWriter<int> GetWriter() => new FileWriter(fil...
class FileReader (line 15) | private class FileReader(string filename) : ISequentialStorageReader<int>
method Dispose (line 19) | public void Dispose() => reader.Dispose();
method Read (line 21) | public int Read() => reader.ReadInt32();
class FileWriter (line 24) | private class FileWriter(string filename) : ISequentialStorageWriter<int>
method Write (line 28) | public void Write(int value) => writer.Write(value);
method Dispose (line 30) | public void Dispose() => writer.Dispose();
FILE: Algorithms/Sorters/External/Storages/IntInMemoryStorage.cs
class IntInMemoryStorage (line 3) | public class IntInMemoryStorage(int[] array) : ISequentialStorage<int>
method GetReader (line 9) | public ISequentialStorageReader<int> GetReader() => new InMemoryReader...
method GetWriter (line 11) | public ISequentialStorageWriter<int> GetWriter() => new InMemoryWriter...
class InMemoryReader (line 13) | private class InMemoryReader(int[] storage) : ISequentialStorageReader...
method Dispose (line 18) | public void Dispose()
method Read (line 23) | public int Read() => storage[offset++];
class InMemoryWriter (line 26) | private class InMemoryWriter(int[] storage) : ISequentialStorageWriter...
method Write (line 31) | public void Write(int value) => storage[offset++] = value;
method Dispose (line 33) | public void Dispose()
FILE: Algorithms/Sorters/Integer/BucketSorter.cs
class BucketSorter (line 6) | public class BucketSorter : IIntegerSorter
method Sort (line 14) | public void Sort(int[] array)
method NumberOfDigits (line 46) | private static int NumberOfDigits(IEnumerable<int> array) => (int)Math...
method DistributeElements (line 54) | private static void DistributeElements(IEnumerable<int> data, int[,] b...
method CollectElements (line 77) | private static void CollectElements(IList<int> data, int[,] buckets)
method EmptyBucket (line 96) | private static void EmptyBucket(int[,] buckets)
FILE: Algorithms/Sorters/Integer/CountingSorter.cs
class CountingSorter (line 12) | public class CountingSorter : IIntegerSorter
method Sort (line 26) | public void Sort(int[] array)
FILE: Algorithms/Sorters/Integer/IIntegerSorter.cs
type IIntegerSorter (line 6) | public interface IIntegerSorter
method Sort (line 12) | void Sort(int[] array);
FILE: Algorithms/Sorters/Integer/RadixSorter.cs
class RadixSorter (line 11) | public class RadixSorter : IIntegerSorter
method Sort (line 17) | public void Sort(int[] array)
FILE: Algorithms/Sorters/String/IStringSorter.cs
type IStringSorter (line 6) | public interface IStringSorter
method Sort (line 12) | void Sort(string[] array);
FILE: Algorithms/Sorters/String/MsdRadixStringSorter.cs
class MsdRadixStringSorter (line 11) | public class MsdRadixStringSorter : IStringSorter
method Sort (line 17) | public void Sort(string[] array) => Sort(array, 0, array.Length - 1, 0...
method Sort (line 19) | private static void Sort(string[] array, int l, int r, int d, string[]...
FILE: Algorithms/Sorters/Utils/GallopingStrategy.cs
class GallopingStrategy (line 3) | public static class GallopingStrategy<T>
method GallopLeft (line 5) | public static int GallopLeft(T[] array, T key, int baseIndex, int leng...
method GallopRight (line 19) | public static int GallopRight(T[] array, T key, int baseIndex, int len...
method BoundLeftShift (line 33) | public static int BoundLeftShift(int shiftable) => (shiftable << 1) < 0
method LeftRun (line 37) | private static (int Offset, int LastOfs) LeftRun(T[] array, T key, int...
method RightRun (line 59) | private static (int Offset, int LastOfs) RightRun(T[] array, T key, in...
method FinalOffset (line 80) | private static int FinalOffset(T[] array, T key, int baseIndex, int of...
FILE: Algorithms/Stack/BalancedParenthesesChecker.cs
class BalancedParenthesesChecker (line 7) | public class BalancedParenthesesChecker
method IsBalanced (line 31) | public bool IsBalanced(string expression)
method IsOpeningParenthesis (line 61) | private static bool IsOpeningParenthesis(char c)
method IsClosingParenthesis (line 66) | private static bool IsClosingParenthesis(char c)
method IsBalancedClosing (line 71) | private static bool IsBalancedClosing(Stack<char> stack, char close)
method IsMatchingPair (line 82) | private static bool IsMatchingPair(char open, char close)
FILE: Algorithms/Stack/InfixToPostfix.cs
class InfixToPostfix (line 10) | public static class InfixToPostfix
method InfixToPostfixConversion (line 20) | public static string InfixToPostfixConversion(string initialInfixExpre...
method PostfixExpressionEvaluation (line 56) | public static int PostfixExpressionEvaluation(string postfixExpression)
method ProcessInfixCharacter (line 91) | private static void ProcessInfixCharacter(char c, Stack<char> stack, S...
method ProcessClosingParenthesis (line 114) | private static void ProcessClosingParenthesis(Stack<char> stack, Strin...
method ProcessOperator (line 129) | private static void ProcessOperator(char c, Stack<char> stack, StringB...
method EmptyRemainingStack (line 139) | private static void EmptyRemainingStack(Stack<char> stack, StringBuild...
method EvaluateOperator (line 152) | private static void EvaluateOperator(Stack<int> stack, char op)
method ValidateInfix (line 180) | private static void ValidateInfix(string expr)
method ValidatePostfix (line 188) | private static void ValidatePostfix(string expr)
method Precedence (line 201) | [ExcludeFromCodeCoverage]
method IsOperand (line 227) | private static bool IsOperand(char ch) => char.IsLetterOrDigit(ch);
method IsOperator (line 236) | private static bool IsOperator(char ch) => Operators.Contains(ch);
method IsValidCharacter (line 243) | private static bool IsValidCharacter(char c) => IsOperand(c) || IsOper...
method IsParenthesis (line 245) | private static bool IsParenthesis(char c) => c == '(' || c == ')';
FILE: Algorithms/Stack/NextGreaterElement.cs
class NextGreaterElement (line 7) | public class NextGreaterElement
method FindNextGreaterElement (line 17) | public int[] FindNextGreaterElement(int[] nums)
FILE: Algorithms/Stack/ReverseStack.cs
class ReverseStack (line 7) | public class ReverseStack
method Reverse (line 15) | public void Reverse<T>(Stack<T> stack)
method InsertAtBottom (line 27) | private void InsertAtBottom<T>(Stack<T> stack, T value)
FILE: Algorithms/Strings/GeneralStringAlgorithms.cs
class GeneralStringAlgorithms (line 6) | public static class GeneralStringAlgorithms
method FindLongestConsecutiveCharacters (line 13) | public static Tuple<char, int> FindLongestConsecutiveCharacters(string...
FILE: Algorithms/Strings/ManachersAlgorithm.cs
class ManachersAlgorithm (line 22) | public static class ManachersAlgorithm
method FindLongestPalindrome (line 64) | public static string FindLongestPalindrome(string input)
method FindLongestPalindromeWithDetails (line 222) | public static (string Palindrome, int StartIndex, int Length) FindLong...
method IsPalindrome (line 312) | public static bool IsPalindrome(string input)
method PreprocessString (line 359) | private static string PreprocessString(string input)
FILE: Algorithms/Strings/Palindrome.cs
class Palindrome (line 7) | public static class Palindrome
method IsStringPalindrome (line 13) | public static bool IsStringPalindrome(string word) =>
method TypifyString (line 21) | private static string TypifyString(string word) =>
method ReverseString (line 29) | private static string ReverseString(string s)
FILE: Algorithms/Strings/PatternMatching/Bitap.cs
class Bitap (line 46) | public static class Bitap
method FindExactPattern (line 73) | public static int FindExactPattern(string text, string pattern)
method FindFuzzyPattern (line 140) | public static int FindFuzzyPattern(string text, string pattern, int th...
FILE: Algorithms/Strings/PatternMatching/BoyerMoore.cs
class BoyerMoore (line 18) | public static class BoyerMoore
method FindFirstOccurrence (line 26) | public static int FindFirstOccurrence(string t, string p)
method BadCharacterRule (line 81) | private static int[] BadCharacterRule(string p, int m)
method GoodSuffixRule (line 103) | private static int[] GoodSuffixRule(string p, int m)
FILE: Algorithms/Strings/PatternMatching/KnuthMorrisPrattSearcher.cs
class KnuthMorrisPrattSearcher (line 3) | public class KnuthMorrisPrattSearcher
method FindIndexes (line 15) | public IEnumerable<int> FindIndexes(string str, string pat)
method FindLongestPrefixSuffixValues (line 53) | public int[] FindLongestPrefixSuffixValues(string pat)
FILE: Algorithms/Strings/PatternMatching/NaiveStringSearch.cs
class NaiveStringSearch (line 7) | public static class NaiveStringSearch
method NaiveSearch (line 16) | public static int[] NaiveSearch(string content, string pattern)
FILE: Algorithms/Strings/PatternMatching/RabinKarp.cs
class RabinKarp (line 12) | public static class RabinKarp
method FindAllOccurrences (line 18) | public static List<int> FindAllOccurrences(string text, string pattern)
FILE: Algorithms/Strings/PatternMatching/WildCardMatcher.cs
class WildCardMatcher (line 9) | public static class WildCardMatcher
method MatchPattern (line 22) | public static bool MatchPattern(string inputString, string pattern)
method MatchRemainingLenghts (line 62) | private static void MatchRemainingLenghts(string inputString, string p...
method MatchForZeroOrMore (line 80) | private static void MatchForZeroOrMore(string inputString, string patt...
FILE: Algorithms/Strings/PatternMatching/ZblockSubstringSearch.cs
class ZblockSubstringSearch (line 5) | public static class ZblockSubstringSearch
method FindSubstring (line 10) | public static int FindSubstring(string pattern, string text)
method ComputeNewRightValue (line 59) | private static int ComputeNewRightValue(string concatStr, int n, int l...
FILE: Algorithms/Strings/Permutation.cs
class Permutation (line 3) | public static class Permutation
method GetEveryUniquePermutation (line 9) | public static List<string> GetEveryUniquePermutation(string word)
FILE: Algorithms/Strings/Similarity/CosineSimilarity.cs
class CosineSimilarity (line 3) | public static class CosineSimilarity
method Calculate (line 16) | public static double Calculate(string left, string right)
method GetVectors (line 64) | private static (Dictionary<char, int> LeftVector, Dictionary<char, int...
method DotProduct (line 94) | private static double DotProduct(Dictionary<char, int> leftVector, Dic...
method GetIntersection (line 116) | private static HashSet<char> GetIntersection(Dictionary<char, int> lef...
FILE: Algorithms/Strings/Similarity/DamerauLevenshteinDistance.cs
class DamerauLevenshteinDistance (line 3) | public static class DamerauLevenshteinDistance
method Calculate (line 14) | public static int Calculate(string left, string right)
method InitializeDistanceArray (line 80) | private static int[,] InitializeDistanceArray(int leftSize, int rightS...
FILE: Algorithms/Strings/Similarity/HammingDistance.cs
class HammingDistance (line 12) | public static class HammingDistance
method Calculate (line 20) | public static int Calculate(string s1, string s2)
FILE: Algorithms/Strings/Similarity/JaccardDistance.cs
class JaccardDistance (line 34) | public class JaccardDistance
method Calculate (line 44) | public double Calculate(string left, string right)
FILE: Algorithms/Strings/Similarity/JaccardSimilarity.cs
class JaccardSimilarity (line 31) | public class JaccardSimilarity
method Calculate (line 43) | public double Calculate(string left, string right)
method ValidateInput (line 87) | private void ValidateInput(string left, string right)
FILE: Algorithms/Strings/Similarity/JaroSimilarity.cs
class JaroSimilarity (line 13) | public static class JaroSimilarity
method Calculate (line 20) | public static double Calculate(string s1, string s2)
method CalculateTranspositions (line 69) | private static int CalculateTranspositions(string s1, string s2, bool[...
FILE: Algorithms/Strings/Similarity/JaroWinklerDistance.cs
class JaroWinklerDistance (line 13) | public static class JaroWinklerDistance
method Calculate (line 22) | public static double Calculate(string s1, string s2, double scalingFac...
FILE: Algorithms/Strings/Similarity/OptimalStringAlignment.cs
class OptimalStringAlignment (line 46) | public static class OptimalStringAlignment
method Calculate (line 55) | public static double Calculate(string firstString, string secondString)
method GenerateDistanceMatrix (line 87) | private static int[,] GenerateDistanceMatrix(int firstLength, int seco...
method CalculateDistance (line 111) | private static int[,] CalculateDistance(string firstString, string sec...
method Minimum (line 150) | private static int Minimum(int a, int b, int c)
FILE: DataStructures.Tests/AATreeTests.cs
class AaTreeTests (line 5) | internal class AaTreeTests
method Constructor_UseCustomComparer_FormsCorrectTree (line 7) | [Test]
method Add_MultipleKeys_FormsCorrectTree (line 18) | [Test]
method Add_KeyAlreadyInTree_ThrowsException (line 35) | [Test]
method AddRange_MultipleKeys_FormsCorrectTree (line 43) | [Test]
method Remove_MultipleKeys_TreeStillValid (line 54) | [Test]
method Remove_KeyNotInTree_Throws (line 77) | [Test]
method Remove_EmptyTree_Throws (line 87) | [Test]
method Contains_NonEmptyTree_ReturnsCorrectAnswer (line 96) | [Test]
method Contains_EmptyTree_ReturnsFalse (line 105) | [Test]
method GetMax_NonEmptyTree_ReturnsCorrectAnswer (line 112) | [Test]
method GetMax_EmptyTree_ThrowsCorrectException (line 120) | [Test]
method GetMin_NonEmptyTree_ReturnsCorrectAnswer (line 127) | [Test]
method GetMin_EmptyTree_ThrowsCorrectException (line 135) | [Test]
method GetKeysInOrder_NonEmptyTree_ReturnsCorrectAnswer (line 142) | [Test]
method GetKeysInOrder_EmptyTree_ReturnsCorrectAnswer (line 150) | [Test]
method GetKeysPreOrder_NonEmptyTree_ReturnsCorrectAnswer (line 157) | [Test]
method GetKeysPreOrder_EmptyTree_ReturnsCorrectAnswer (line 166) | [Test]
method GetKeysPostOrder_NonEmptyTree_ReturnsCorrectAnswer (line 173) | [Test]
method GetKeysPostOrder_EmptyTree_ReturnsCorrectAnswer (line 182) | [Test]
method Validate (line 207) | private static bool Validate<T>(AaTreeNode<T>? node)
method CheckLeafNode (line 240) | private static bool CheckLeafNode<T>(AaTreeNode<T> node)
method CheckLeftSubtree (line 251) | private static bool CheckLeftSubtree<T>(AaTreeNode<T> node)
method CheckRightSubtree (line 262) | private static bool CheckRightSubtree<T>(AaTreeNode<T> node)
method CheckRightGrandChild (line 275) | private static bool CheckRightGrandChild<T>(AaTreeNode<T> node)
method CheckNonLeafChildren (line 286) | private static bool CheckNonLeafChildren<T>(AaTreeNode<T> node)
FILE: DataStructures.Tests/AVLTreeTests.cs
class AvlTreeTests (line 6) | internal class AvlTreeTests
method Constructor_UseCustomComparer_FormsCorrectTree (line 12) | [Test]
method Add_MultipleKeys_FormsCorrectTree (line 30) | [Test]
method Add_KeyAlreadyInTree_ThrowsException (line 60) | [Test]
method AddRange_MultipleKeys_FormsCorrectTree (line 69) | [Test]
method Remove_MultipleKeys_TreeStillValid (line 96) | [Test]
method Remove_MultipleKeys_TreeStillValid_Variant2 (line 187) | [Test]
method Remove_EmptyTree_ThrowsException (line 247) | [Test]
method Remove_KeyNotInTree_ThrowsException (line 255) | [Test]
method Contains_CorrectReturn (line 264) | [Test]
method Contains_EmptyTree_ReturnsFalse (line 277) | [Test]
method GetMin_CorrectReturn (line 286) | [Test]
method GetMin_EmptyTree_ThrowsException (line 295) | [Test]
method GetMax_CorrectReturn (line 303) | [Test]
method GetMax_EmptyTree_ThrowsException (line 312) | [Test]
method GetKeysInOrder_CorrectReturn (line 320) | [Test]
method GetKeysInOrder_EmptyTree_CorrectReturn (line 333) | [Test]
method GetKeysPreOrder_CorrectReturn (line 341) | [Test]
method GetKeysPreOrder_EmptyTree_CorrectReturn (line 355) | [Test]
method GetKeysPostOrder_CorrectReturn (line 363) | [Test]
method GetKeysPostOrder_EmptyTree_CorrectReturn (line 376) | [Test]
FILE: DataStructures.Tests/BTreeTests.cs
class BTreeTests (line 6) | internal class BTreeTests
method Constructor_DefaultMinimumDegree_CreatesEmptyTree (line 10) | [Test]
method Constructor_CustomMinimumDegree_SetsCorrectDegree (line 19) | [Test]
method Constructor_MinimumDegreeLessThan2_ThrowsException (line 28) | [Test]
method Constructor_CustomComparerMinimumDegreeLessThan2_ThrowsException (line 37) | [Test]
method Constructor_UseCustomComparer_FormsCorrectTree (line 48) | [Test]
method Add_SingleKey_IncreasesCount (line 65) | [Test]
method Add_MultipleKeys_FormsCorrectTree (line 76) | [Test]
method Add_DuplicateKey_ThrowsException (line 94) | [Test]
method Add_DuplicateKeyInLeaf_ThrowsException (line 106) | [Test]
method Add_CausesNodeSplit_TreeStillValid (line 118) | [Test]
method Add_LargeNumberOfKeys_TreeStillValid (line 132) | [Test]
method AddRange_MultipleKeys_FormsCorrectTree (line 148) | [Test]
method AddRange_EmptyCollection_TreeRemainsEmpty (line 163) | [Test]
method Contains_KeyExists_ReturnsTrue (line 173) | [Test]
method Contains_KeyDoesNotExist_ReturnsFalse (line 184) | [Test]
method Contains_EmptyTree_ReturnsFalse (line 195) | [Test]
method Remove_SingleKey_DecreasesCount (line 204) | [Test]
method Remove_FromLeafNode_TreeStillValid (line 216) | [Test]
method Remove_FromNonLeafNode_TreeStillValid (line 234) | [Test]
method Remove_CausesMerge_TreeStillValid (line 252) | [Test]
method Remove_MultipleKeys_TreeStillValid (line 270) | [Test]
method Remove_AllKeys_TreeBecomesEmpty (line 292) | [Test]
method Remove_EmptyTree_ThrowsException (line 308) | [Test]
method Remove_KeyNotInTree_ThrowsException (line 319) | [Test]
method GetMin_NonEmptyTree_ReturnsMinimum (line 331) | [Test]
method GetMin_SingleElement_ReturnsElement (line 340) | [Test]
method GetMin_EmptyTree_ThrowsException (line 349) | [Test]
method GetMax_NonEmptyTree_ReturnsMaximum (line 360) | [Test]
method GetMax_SingleElement_ReturnsElement (line 369) | [Test]
method GetMax_EmptyTree_ThrowsException (line 378) | [Test]
method GetKeysInOrder_NonEmptyTree_ReturnsCorrectOrder (line 389) | [Test]
method GetKeysInOrder_EmptyTree_ReturnsEmpty (line 402) | [Test]
method GetKeysInOrder_AfterRemoval_ReturnsCorrectOrder (line 410) | [Test]
method GetKeysPreOrder_NonEmptyTree_ReturnsCorrectOrder (line 425) | [Test]
method GetKeysPreOrder_EmptyTree_ReturnsEmpty (line 437) | [Test]
method GetKeysPostOrder_NonEmptyTree_ReturnsCorrectOrder (line 445) | [Test]
method GetKeysPostOrder_EmptyTree_ReturnsEmpty (line 457) | [Test]
method BTree_LargeDataSet_MaintainsCorrectness (line 465) | [Test]
method BTree_RandomInsertion_MaintainsCorrectness (line 486) | [Test]
method BTree_RandomDeletion_MaintainsCorrectness (line 505) | [Test]
method BTree_StringKeys_WorksCorrectly (line 536) | [Test]
method BTree_DifferentMinimumDegrees_AllWorkCorrectly (line 555) | [Test]
method BTree_InsertRemoveInsert_WorksCorrectly (line 572) | [Test]
method Remove_BorrowFromPreviousSibling_TreeStillValid (line 591) | [Test]
method Remove_BorrowFromNextSibling_TreeStillValid (line 610) | [Test]
method Remove_UsesPredecessor_TreeStillValid (line 629) | [Test]
method Remove_UsesSuccessor_TreeStillValid (line 649) | [Test]
method Remove_MergeWithSibling_TreeStillValid (line 668) | [Test]
method Remove_ComplexRebalancing_TreeStillValid (line 688) | [Test]
method Remove_FromMinimumDegree3_AllRebalancingPaths (line 713) | [Test]
method Remove_SequentialFromLargeTree_MaintainsStructure (line 736) | [Test]
method BTree_DegreeThree_CompleteInsertDeleteCycle (line 761) | [Test]
method Remove_RootWithMultipleChildren_HandledCorrectly (line 790) | [Test]
method BTree_HighDegree_StressTest (line 806) | [Test]
FILE: DataStructures.Tests/BagTests.cs
class BagTests (line 9) | internal class BagTests
method Add_ShouldIncreaseCount (line 11) | [Test]
method Add_ShouldHandleDuplicates (line 26) | [Test]
method Clear_ShouldEmptyTheBag (line 41) | [Test]
method IsEmpty_ShouldReturnTrueForEmptyBag (line 59) | [Test]
method IsEmpty_ShouldReturnFalseForNonEmptyBag (line 69) | [Test]
method GetEnumerator_ShouldIterateAllItems (line 82) | [Test]
method Count_ShouldReturnZeroForEmptyBag (line 102) | [Test]
method Count_ShouldReturnCorrectCount (line 112) | [Test]
method IEnumerableGetEnumerator_YieldsAllItemsWithCorrectMultiplicity (line 127) | [Test]
FILE: DataStructures.Tests/BinarySearchTreeTests.cs
class BinarySearchTreeTests (line 5) | public static class BinarySearchTreeTests
method Constructor_UseCustomComparer_FormsCorrectTree (line 7) | [Test]
method Add_MultipleKeys_FormsCorrectBST (line 20) | [Test]
method Add_KeyAlreadyInTree_T
Condensed preview — 627 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (2,064K chars).
[
{
"path": ".devcontainer/devcontainer.json",
"chars": 354,
"preview": "{\n\t\"name\": \"The Algorithms C#\",\n\t\"image\": \"mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm\",\n\t\"customizations\": {\n"
},
{
"path": ".editorconfig",
"chars": 7084,
"preview": "[*]\ncharset = utf-8\nend_of_line = lf\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\nin"
},
{
"path": ".github/CODEOWNERS",
"chars": 10,
"preview": "* @siriak\n"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.md",
"chars": 445,
"preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: Something works wrong\nlabels: bug\nassignees: ''\n\n-"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.md",
"chars": 280,
"preview": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: Add something cool\nlabels: enhancement\nassignee"
},
{
"path": ".github/pull_request_template.md",
"chars": 663,
"preview": "<!--\nPlease include a summary of the change.\nPlease also include relevant motivation and context (if applicable).\nPut 'x"
},
{
"path": ".github/workflows/ci.yml",
"chars": 1139,
"preview": "name: CI\n\non: [push, pull_request]\n\njobs:\n build:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@"
},
{
"path": ".github/workflows/stale.yml",
"chars": 869,
"preview": "name: 'Close stale issues and PRs'\non:\n schedule:\n - cron: '0 0 * * *'\njobs:\n stale:\n runs-on: ubuntu-latest\n "
},
{
"path": ".gitignore",
"chars": 180,
"preview": "# Visual Studio cache/options directory\n.vs/\n\n# Rider cache/options directory\n.idea/\n\n# Rider user config file\nC-Sharp.s"
},
{
"path": "Algorithms/Algorithms.csproj",
"chars": 1129,
"preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n <PropertyGroup>\n <TargetFramework>net8.0</TargetFramework>\n <CodeAnalysisRule"
},
{
"path": "Algorithms/Crypto/Digests/AsconDigest.cs",
"chars": 28102,
"preview": "using System.Runtime.CompilerServices;\nusing Algorithms.Crypto.Utils;\n\nnamespace Algorithms.Crypto.Digests;\n\n/// <summar"
},
{
"path": "Algorithms/Crypto/Digests/IDigest.cs",
"chars": 2612,
"preview": "namespace Algorithms.Crypto.Digests;\n\n/// <summary>\n/// Interface for message digest algorithms, providing methods to up"
},
{
"path": "Algorithms/Crypto/Digests/Md2Digest.cs",
"chars": 9342,
"preview": "namespace Algorithms.Crypto.Digests;\n\n/// <summary>\n/// MD2 is a cryptographic hash function that takes an input message"
},
{
"path": "Algorithms/Crypto/Exceptions/CryptoException.cs",
"chars": 1145,
"preview": "namespace Algorithms.Crypto.Exceptions;\n\n/// <summary>\n/// Represents errors that occur during cryptographic operations."
},
{
"path": "Algorithms/Crypto/Exceptions/DataLengthException.cs",
"chars": 1224,
"preview": "namespace Algorithms.Crypto.Exceptions;\n\n/// <summary>\n/// Represents errors that occur when the length of data in a cry"
},
{
"path": "Algorithms/Crypto/Exceptions/OutputLengthException.cs",
"chars": 2846,
"preview": "namespace Algorithms.Crypto.Exceptions;\n\n/// <summary>\n/// Represents an exception that is thrown when the output buffer"
},
{
"path": "Algorithms/Crypto/Paddings/IBlockCipherPadding.cs",
"chars": 1968,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// A common interface that all block cipher padding schemes shoul"
},
{
"path": "Algorithms/Crypto/Paddings/Iso10126D2Padding.cs",
"chars": 5387,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// <para>\n/// This class implements the ISO10126d2 padding scheme"
},
{
"path": "Algorithms/Crypto/Paddings/Iso7816D4Padding.cs",
"chars": 6390,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// <para>\n/// ISO 7816-4 padding is a padding scheme that is defi"
},
{
"path": "Algorithms/Crypto/Paddings/Pkcs7Padding.cs",
"chars": 7443,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// <para>\n/// This class implements the PKCS7 padding scheme, whi"
},
{
"path": "Algorithms/Crypto/Paddings/TbcPadding.cs",
"chars": 6197,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// <para>\n/// Trailing-Bit-Complement padding is a padding scheme"
},
{
"path": "Algorithms/Crypto/Paddings/X932Padding.cs",
"chars": 5119,
"preview": "namespace Algorithms.Crypto.Paddings;\n\n/// <summary>\n/// <para>\n/// X9.32 padding is a padding scheme for symmetric encr"
},
{
"path": "Algorithms/Crypto/Utils/ByteEncodingUtils.cs",
"chars": 3469,
"preview": "using System.Buffers.Binary;\nusing System.Runtime.CompilerServices;\n\nnamespace Algorithms.Crypto.Utils;\n\n/// <summary>\n/"
},
{
"path": "Algorithms/Crypto/Utils/LongUtils.cs",
"chars": 4208,
"preview": "namespace Algorithms.Crypto.Utils;\n\n/// <summary>\n/// Provides utility methods for performing bitwise rotation operation"
},
{
"path": "Algorithms/Crypto/Utils/ValidationUtils.cs",
"chars": 4870,
"preview": "using Algorithms.Crypto.Exceptions;\n\nnamespace Algorithms.Crypto.Utils;\n\n/// <summary>\n/// Provides utility methods for "
},
{
"path": "Algorithms/DataCompression/BurrowsWheelerTransform.cs",
"chars": 2097,
"preview": "namespace Algorithms.DataCompression;\n\n/// <summary>\n/// The Burrows–Wheeler transform (BWT) rearranges a character "
},
{
"path": "Algorithms/DataCompression/HuffmanCompressor.cs",
"chars": 4848,
"preview": "using Algorithms.Sorters.Comparison;\n\nnamespace Algorithms.DataCompression;\n\n/// <summary>\n/// Greedy lossless compr"
},
{
"path": "Algorithms/DataCompression/ShannonFanoCompressor.cs",
"chars": 4208,
"preview": "using Algorithms.Knapsack;\n\nnamespace Algorithms.DataCompression;\n\n/// <summary>\n/// Greedy lossless compression alg"
},
{
"path": "Algorithms/DataCompression/Translator.cs",
"chars": 953,
"preview": "namespace Algorithms.DataCompression;\n\n/// <summary>\n/// Provides method for text conversion by key mapping.\n/// </s"
},
{
"path": "Algorithms/Encoders/AutokeyEncorder.cs",
"chars": 2609,
"preview": "namespace Algorithms.Encoders\n{\n /// <summary>\n /// Class for AutoKey encoding strings.\n /// </summary>\n "
},
{
"path": "Algorithms/Encoders/BlowfishEncoder.cs",
"chars": 24004,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// <para>\n/// The Blowfish algorithm is a symmetric-key block cipher, whi"
},
{
"path": "Algorithms/Encoders/CaesarEncoder.cs",
"chars": 1725,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Encodes using caesar cypher.\n/// </summary>\npublic class CaesarEnc"
},
{
"path": "Algorithms/Encoders/FeistelCipher.cs",
"chars": 6802,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Encodes using Feistel cipher.\n/// https://en.wikipedia.org/wik"
},
{
"path": "Algorithms/Encoders/HillEncoder.cs",
"chars": 5745,
"preview": "using Algorithms.Numeric;\n\nnamespace Algorithms.Encoders;\n\n/// <summary>\n/// Lester S. Hill's polygraphic substituti"
},
{
"path": "Algorithms/Encoders/IEncoder.cs",
"chars": 818,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Encodes and decodes text based on specified key.\n/// </summary>\n//"
},
{
"path": "Algorithms/Encoders/NysiisEncoder.cs",
"chars": 4674,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Class for NYSIIS encoding strings.\n/// </summary>\npublic class Nys"
},
{
"path": "Algorithms/Encoders/SoundexEncoder.cs",
"chars": 2880,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Class for Soundex encoding strings.\n/// </summary>\npublic class So"
},
{
"path": "Algorithms/Encoders/VigenereEncoder.cs",
"chars": 2233,
"preview": "namespace Algorithms.Encoders;\n\n/// <summary>\n/// Encodes using vigenere cypher.\n/// </summary>\npublic class Vigener"
},
{
"path": "Algorithms/Financial/PresentValue.cs",
"chars": 693,
"preview": "namespace Algorithms.Financial;\n\n/// <summary>\n/// PresentValue is the value of an expected income stream determined as "
},
{
"path": "Algorithms/GlobalUsings.cs",
"chars": 1484,
"preview": "// -----------------------------------------------------------------------------\n// Global using directives for the C-Sh"
},
{
"path": "Algorithms/Graph/ArticulationPoints.cs",
"chars": 5807,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Finds"
},
{
"path": "Algorithms/Graph/BellmanFord.cs",
"chars": 3201,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Bellman-Ford algorithm on directed weighted "
},
{
"path": "Algorithms/Graph/BipartiteGraph.cs",
"chars": 6439,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Check"
},
{
"path": "Algorithms/Graph/BreadthFirstSearch.cs",
"chars": 1925,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Breadth First Search - algorithm for travers"
},
{
"path": "Algorithms/Graph/BreadthFirstTreeTraversal.cs",
"chars": 3007,
"preview": "using DataStructures.BinarySearchTree;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Breadth first tree traversal "
},
{
"path": "Algorithms/Graph/Bridges.cs",
"chars": 5372,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Finds"
},
{
"path": "Algorithms/Graph/DepthFirstSearch.cs",
"chars": 1733,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Depth First Search - algorithm for traversin"
},
{
"path": "Algorithms/Graph/Dijkstra/DijkstraAlgorithm.cs",
"chars": 3343,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph.Dijkstra;\n\npublic static class DijkstraAlgorithm\n{\n /// <summ"
},
{
"path": "Algorithms/Graph/Dijkstra/DistanceModel.cs",
"chars": 681,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph.Dijkstra;\n\n/// <summary>\n/// Entity which represents the Dijkstr"
},
{
"path": "Algorithms/Graph/FloydWarshall.cs",
"chars": 2044,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Floyd Warshall algorithm on directed weighte"
},
{
"path": "Algorithms/Graph/IGraphSearch.cs",
"chars": 502,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\npublic interface IGraphSearch<T>\n{\n /// <summary>\n /// T"
},
{
"path": "Algorithms/Graph/Kosaraju.cs",
"chars": 4232,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Implementation of Kosaraju-Sharir's algorith"
},
{
"path": "Algorithms/Graph/MinimumSpanningTree/Kruskal.cs",
"chars": 6639,
"preview": "using DataStructures.DisjointSet;\n\nnamespace Algorithms.Graph.MinimumSpanningTree;\n\n/// <summary>\n/// Algorithm to d"
},
{
"path": "Algorithms/Graph/MinimumSpanningTree/PrimMatrix.cs",
"chars": 5195,
"preview": "namespace Algorithms.Graph.MinimumSpanningTree;\n\n/// <summary>\n/// Class that uses Prim's (Jarnik's algorithm) to de"
},
{
"path": "Algorithms/Graph/TarjanStronglyConnectedComponents.cs",
"chars": 4435,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Tarja"
},
{
"path": "Algorithms/Graph/TopologicalSort.cs",
"chars": 14411,
"preview": "using DataStructures.Graph;\n\nnamespace Algorithms.Graph;\n\n/// <summary>\n/// Topological Sort is a linear ordering of"
},
{
"path": "Algorithms/Knapsack/BranchAndBoundKnapsackSolver.cs",
"chars": 7211,
"preview": "namespace Algorithms.Knapsack;\n\n/// <summary>\n/// Branch and bound Knapsack solver.\n/// </summary>\n/// <typeparam na"
},
{
"path": "Algorithms/Knapsack/BranchAndBoundNode.cs",
"chars": 936,
"preview": "namespace Algorithms.Knapsack;\n\npublic class BranchAndBoundNode(int level, bool taken, BranchAndBoundNode? parent = null"
},
{
"path": "Algorithms/Knapsack/DynamicProgrammingKnapsackSolver.cs",
"chars": 3797,
"preview": "namespace Algorithms.Knapsack;\n\n/// <summary>\n/// Dynamic Programming Knapsack solver.\n/// </summary>\n/// <typeparam"
},
{
"path": "Algorithms/Knapsack/IHeuristicKnapsackSolver.cs",
"chars": 953,
"preview": "namespace Algorithms.Knapsack;\n\n/// <summary>\n/// Solves knapsack problem using some heuristics\n/// Sum of value"
},
{
"path": "Algorithms/Knapsack/IKnapsackSolver.cs",
"chars": 344,
"preview": "namespace Algorithms.Knapsack;\n\n/// <summary>\n/// Solves knapsack problem:\n/// to maximize sum of values of take"
},
{
"path": "Algorithms/Knapsack/NaiveKnapsackSolver.cs",
"chars": 1267,
"preview": "namespace Algorithms.Knapsack;\n\n/// <summary>\n/// Greedy heurictic solver.\n/// </summary>\n/// <typeparam name=\"T\">Ty"
},
{
"path": "Algorithms/LinearAlgebra/Distances/Chebyshev.cs",
"chars": 1123,
"preview": "namespace Algorithms.LinearAlgebra.Distances;\n\n/// <summary>\n/// Implementation of Chebyshev distance.\n/// It is the max"
},
{
"path": "Algorithms/LinearAlgebra/Distances/Euclidean.cs",
"chars": 836,
"preview": "namespace Algorithms.LinearAlgebra.Distances;\n\n/// <summary>\n/// Implementation for Euclidean distance.\n/// </summary>\np"
},
{
"path": "Algorithms/LinearAlgebra/Distances/Manhattan.cs",
"chars": 1086,
"preview": "namespace Algorithms.LinearAlgebra.Distances;\n\n/// <summary>\n/// Implementation fo Manhattan distance.\n/// It is the sum"
},
{
"path": "Algorithms/LinearAlgebra/Distances/Minkowski.cs",
"chars": 1476,
"preview": "namespace Algorithms.LinearAlgebra.Distances;\n\n/// <summary>\n/// Implementation of Minkowski distance.\n/// It is the sum"
},
{
"path": "Algorithms/LinearAlgebra/Eigenvalue/PowerIteration.cs",
"chars": 3847,
"preview": "namespace Algorithms.LinearAlgebra.Eigenvalue;\n\n/// <summary>\n/// Power iteration method - eigenvalue numeric algori"
},
{
"path": "Algorithms/MachineLearning/KNearestNeighbors.cs",
"chars": 3609,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.MachineLearning;\n\n/// <summary>"
},
{
"path": "Algorithms/MachineLearning/LinearRegression.cs",
"chars": 3329,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.MachineLearning;\n\n/// <summary>"
},
{
"path": "Algorithms/MachineLearning/LogisticRegression.cs",
"chars": 2551,
"preview": "using System;\nusing System.Linq;\n\nnamespace Algorithms.MachineLearning;\n\n/// <summary>\n/// Logistic Regression for binar"
},
{
"path": "Algorithms/ModularArithmetic/ChineseRemainderTheorem.cs",
"chars": 7692,
"preview": "namespace Algorithms.ModularArithmetic;\n\n/// <summary>\n/// Chinese Remainder Theorem: https://en.wikipedia.org/wiki/Chin"
},
{
"path": "Algorithms/ModularArithmetic/ExtendedEuclideanAlgorithm.cs",
"chars": 3361,
"preview": "namespace Algorithms.ModularArithmetic;\n\n/// <summary>\n/// Extended Euclidean algorithm: https://en.wikipedia.org/wi"
},
{
"path": "Algorithms/ModularArithmetic/ModularMultiplicativeInverse.cs",
"chars": 2346,
"preview": "namespace Algorithms.ModularArithmetic;\n\n/// <summary>\n/// Modular multiplicative inverse: https://en.wikipedia.org/wiki"
},
{
"path": "Algorithms/NewtonSquareRoot.cs",
"chars": 848,
"preview": "namespace Algorithms;\n\npublic static class NewtonSquareRoot\n{\n public static BigInteger Calculate(BigInteger number)"
},
{
"path": "Algorithms/Numeric/Abs.cs",
"chars": 2164,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Find the absolute value of a number.\n/// </summary>\npublic static c"
},
{
"path": "Algorithms/Numeric/AdditionWithoutArithmetic.cs",
"chars": 750,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Add the integers without arithmetic operation.\n/// </summary>\npubli"
},
{
"path": "Algorithms/Numeric/AliquotSumCalculator.cs",
"chars": 1211,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// In number theory, the aliquot sum s(n) of a positive integer n is t"
},
{
"path": "Algorithms/Numeric/AmicableNumbersChecker.cs",
"chars": 1162,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Amicable numbers are two different natural numbers related in such a wa"
},
{
"path": "Algorithms/Numeric/AutomorphicNumber.cs",
"chars": 2453,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Calculates Automorphic numbers. A number is said to be an Automorphic n"
},
{
"path": "Algorithms/Numeric/BinomialCoefficient.cs",
"chars": 1710,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// The binomial coefficients are the positive integers\n/// that oc"
},
{
"path": "Algorithms/Numeric/Ceil.cs",
"chars": 636,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Perform ceiling operation on a number.\n/// </summary>\npublic static"
},
{
"path": "Algorithms/Numeric/Decomposition/LU.cs",
"chars": 3680,
"preview": "namespace Algorithms.Numeric.Decomposition;\n\n/// <summary>\n/// LU-decomposition factors the \"source\" matrix as the p"
},
{
"path": "Algorithms/Numeric/Decomposition/ThinSVD.cs",
"chars": 4767,
"preview": "namespace Algorithms.Numeric.Decomposition;\n\n/// <summary>\n/// Singular Vector Decomposition decomposes any general "
},
{
"path": "Algorithms/Numeric/DoubleFactorial.cs",
"chars": 1546,
"preview": "using System.Numerics;\n\nnamespace Algorithms.Numeric;\n\n/// <summary>\n/// The double factorial of a positive integer "
},
{
"path": "Algorithms/Numeric/EulerMethod.cs",
"chars": 3254,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// In mathematics and computational science, the Euler method (also ca"
},
{
"path": "Algorithms/Numeric/Factorial.cs",
"chars": 1122,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// The factorial of a positive integer n, denoted by n!,\n/// is th"
},
{
"path": "Algorithms/Numeric/Factorization/IFactorizer.cs",
"chars": 570,
"preview": "namespace Algorithms.Numeric.Factorization;\n\n/// <summary>\n/// Finds a factor of a given number or returns false if "
},
{
"path": "Algorithms/Numeric/Factorization/TrialDivisionFactorizer.cs",
"chars": 817,
"preview": "namespace Algorithms.Numeric.Factorization;\n\n/// <summary>\n/// Factors number using trial division algorithm.\n/// </"
},
{
"path": "Algorithms/Numeric/Floor.cs",
"chars": 628,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Perform floor operation on a number.\n/// </summary>\npublic static c"
},
{
"path": "Algorithms/Numeric/GaussJordanElimination.cs",
"chars": 4464,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Algorithm used to find the inverse of any matrix that can be invert"
},
{
"path": "Algorithms/Numeric/GreatestCommonDivisor/BinaryGreatestCommonDivisorFinder.cs",
"chars": 1637,
"preview": "namespace Algorithms.Numeric.GreatestCommonDivisor;\n\n/// <summary>\n/// Finds greatest common divisor for numbers u a"
},
{
"path": "Algorithms/Numeric/GreatestCommonDivisor/EuclideanGreatestCommonDivisorFinder.cs",
"chars": 928,
"preview": "namespace Algorithms.Numeric.GreatestCommonDivisor;\n\n/// <summary>\n/// Euclidean algorithm for finding the greatest "
},
{
"path": "Algorithms/Numeric/GreatestCommonDivisor/IGreatestCommonDivisorFinder.cs",
"chars": 134,
"preview": "namespace Algorithms.Numeric.GreatestCommonDivisor;\n\npublic interface IGreatestCommonDivisorFinder\n{\n int FindGcd(int"
},
{
"path": "Algorithms/Numeric/JosephusProblem.cs",
"chars": 951,
"preview": "namespace Algorithms.Numeric;\n\npublic static class JosephusProblem\n{\n /// <summary>\n /// Calculates the winner in"
},
{
"path": "Algorithms/Numeric/KeithNumberChecker.cs",
"chars": 1516,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// In number theory, a Keith number or repfigit number is a natural numbe"
},
{
"path": "Algorithms/Numeric/KrishnamurthyNumberChecker.cs",
"chars": 935,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// A Krishnamurthy number is a number whose sum of the factorial of digits"
},
{
"path": "Algorithms/Numeric/MillerRabinPrimalityChecker.cs",
"chars": 2934,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// https://en.wikipedia.org/wiki/Miller-Rabin_primality_test\n/// The Mille"
},
{
"path": "Algorithms/Numeric/ModularExponentiation.cs",
"chars": 1132,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Modular exponentiation is a type of exponentiation performed over a"
},
{
"path": "Algorithms/Numeric/NarcissisticNumberChecker.cs",
"chars": 1010,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// A Narcissistic number is equal to the sum of the cubes of its digit"
},
{
"path": "Algorithms/Numeric/PerfectCubeChecker.cs",
"chars": 1576,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// A perfect cube is an element of algebraic structure that is equal t"
},
{
"path": "Algorithms/Numeric/PerfectNumberChecker.cs",
"chars": 1126,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// In number theory, a perfect number is a positive integer that is eq"
},
{
"path": "Algorithms/Numeric/PerfectSquareChecker.cs",
"chars": 654,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// A perfect square is an element of algebraic structure that is equal"
},
{
"path": "Algorithms/Numeric/PrimeChecker.cs",
"chars": 1657,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// A prime number (or a prime) is a natural number greater than 1 that"
},
{
"path": "Algorithms/Numeric/Pseudoinverse/PseudoInverse.cs",
"chars": 1595,
"preview": "using Algorithms.Numeric.Decomposition;\n\nnamespace Algorithms.Numeric.Pseudoinverse;\n\n/// <summary>\n/// The Moore–Pe"
},
{
"path": "Algorithms/Numeric/Relu.cs",
"chars": 1348,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Implementation of the Rectified Linear Unit (ReLU) function.\n/// "
},
{
"path": "Algorithms/Numeric/RungeKuttaMethod.cs",
"chars": 2452,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// In numerical analysis, the Runge–Kutta methods are a family of impl"
},
{
"path": "Algorithms/Numeric/Series/Maclaurin.cs",
"chars": 6164,
"preview": "namespace Algorithms.Numeric.Series;\n\n/// <summary>\n/// Maclaurin series calculates nonlinear functions approximatio"
},
{
"path": "Algorithms/Numeric/Sigmoid.cs",
"chars": 844,
"preview": "using System;\n\nnamespace Algorithms.Numeric;\n\n/// <summary>\n/// Provides the Sigmoid (Logistic) function, commonly u"
},
{
"path": "Algorithms/Numeric/SoftMax.cs",
"chars": 1566,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Implementation of the SoftMax function.\n/// Its a function that"
},
{
"path": "Algorithms/Numeric/SumOfDigits.cs",
"chars": 1437,
"preview": "using System;\n\nnamespace Algorithms.Numeric;\n\n/// <summary>\n/// Provides functionality to calculate the sum of the d"
},
{
"path": "Algorithms/Numeric/Tanh.cs",
"chars": 1835,
"preview": "namespace Algorithms.Numeric;\n\n/// <summary>\n/// Implementation of the Hyperbolic Tangent (Tanh) function.\n/// T"
},
{
"path": "Algorithms/Other/BoyerMooreMajorityVote.cs",
"chars": 1137,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Boyer-Moore Majority Vote algorithm.\n/// Finds element appearing more tha"
},
{
"path": "Algorithms/Other/DecisionsConvolutions.cs",
"chars": 2739,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Almost all real complex decision-making task is described by more than on"
},
{
"path": "Algorithms/Other/FermatPrimeChecker.cs",
"chars": 1482,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Fermat's prime tester https://en.wikipedia.org/wiki/Fermat_primality_"
},
{
"path": "Algorithms/Other/FloodFill.cs",
"chars": 4207,
"preview": "using SkiaSharp;\n\nnamespace Algorithms.Other;\n\n/// <summary>\n/// Flood fill, also called seed fill, is an algorithm that"
},
{
"path": "Algorithms/Other/GaussOptimization.cs",
"chars": 2759,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// The Gaussian method (coordinate descent method) refers to zero-order meth"
},
{
"path": "Algorithms/Other/GeoLocation.cs",
"chars": 1369,
"preview": "namespace Algorithms.Other;\n\npublic static class GeoLocation\n{\n private const double EarthRadiusKm = 6371.01d;\n\n /"
},
{
"path": "Algorithms/Other/Geofence.cs",
"chars": 1049,
"preview": "namespace Algorithms.Other;\n\npublic class Geofence(double latitude, double longitude, double radiusInMeters)\n{\n publi"
},
{
"path": "Algorithms/Other/Geohash.cs",
"chars": 2827,
"preview": "namespace Algorithms.Other;\n\npublic static class Geohash\n{\n private const string Base32Characters = \"0123456789bcdefg"
},
{
"path": "Algorithms/Other/Int2Binary.cs",
"chars": 2344,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Manually converts an integer of certain size to a string of the binar"
},
{
"path": "Algorithms/Other/JulianEaster.cs",
"chars": 981,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Date of Easter calculated with Meeus's Julian algorithm.\n/// The "
},
{
"path": "Algorithms/Other/KadanesAlgorithm.cs",
"chars": 6416,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Kadane's Algorithm is used to find the maximum sum of a contiguous su"
},
{
"path": "Algorithms/Other/KochSnowflake.cs",
"chars": 6426,
"preview": "using SkiaSharp;\n\nnamespace Algorithms.Other;\n\n/// <summary>\n/// The Koch snowflake is a fractal curve and one of th"
},
{
"path": "Algorithms/Other/Luhn.cs",
"chars": 2225,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Luhn algorithm is a simple\n/// checksum formula used to validate\n"
},
{
"path": "Algorithms/Other/Mandelbrot.cs",
"chars": 7643,
"preview": "using SkiaSharp;\n\nnamespace Algorithms.Other;\n\n/// <summary>\n/// The Mandelbrot set is the set of complex numbers \"c"
},
{
"path": "Algorithms/Other/ParetoOptimization.cs",
"chars": 2710,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Almost all real complex decision-making task is described by more than on"
},
{
"path": "Algorithms/Other/PollardsRhoFactorizing.cs",
"chars": 806,
"preview": "using Algorithms.Numeric.GreatestCommonDivisor;\n\nnamespace Algorithms.Other;\n\n/// <summary>Implementation of the Pollard"
},
{
"path": "Algorithms/Other/RGBHSVConversion.cs",
"chars": 5254,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// The RGB color model is an additive color model in which red, green, a"
},
{
"path": "Algorithms/Other/SieveOfEratosthenes.cs",
"chars": 2086,
"preview": "namespace Algorithms.Other;\n\n/// <summary>\n/// Implements the Sieve of Eratosthenes.\n/// </summary>\npublic class Sie"
},
{
"path": "Algorithms/Other/Triangulator.cs",
"chars": 1497,
"preview": "namespace Algorithms.Other;\n\npublic class Triangulator\n{\n public (double Latitude, double Longitude) CalculatePositio"
},
{
"path": "Algorithms/Other/WelfordsVariance.cs",
"chars": 1453,
"preview": "namespace Algorithms.Other;\n\n/// <summary>Implementation of Welford's variance algorithm.\n/// </summary>\npublic class We"
},
{
"path": "Algorithms/Problems/DynamicProgramming/CoinChange/DynamicCoinChangeSolver.cs",
"chars": 5348,
"preview": "namespace Algorithms.Problems.DynamicProgramming.CoinChange;\n\npublic static class DynamicCoinChangeSolver\n{\n /// <sum"
},
{
"path": "Algorithms/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistance.cs",
"chars": 1607,
"preview": "namespace Algorithms.Problems.DynamicProgramming;\n\n/// <summary>\n/// <para>\n/// Levenshtein distance between"
},
{
"path": "Algorithms/Problems/GraphColoring/GraphColoringSolver.cs",
"chars": 7131,
"preview": "namespace Algorithms.Problems.GraphColoring;\n\n/// <summary>\n/// Solves the Graph Coloring Problem using backtracking to "
},
{
"path": "Algorithms/Problems/JobScheduling/IntervalSchedulingSolver.cs",
"chars": 1194,
"preview": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace Algorithms.Problems.JobScheduling;\n\n/// <s"
},
{
"path": "Algorithms/Problems/JobScheduling/Job.cs",
"chars": 169,
"preview": "namespace Algorithms.Problems.JobScheduling;\n\n/// <summary>\n/// Represents a single job with a start and end time.\n/// <"
},
{
"path": "Algorithms/Problems/KnightTour/OpenKnightTour.cs",
"chars": 6453,
"preview": "namespace Algorithms.Problems.KnightTour;\n\n/// <summary>\n/// Computes a (single) Knight's Tour on an <c>n × n</c> chessb"
},
{
"path": "Algorithms/Problems/NQueens/BacktrackingNQueensSolver.cs",
"chars": 3096,
"preview": "namespace Algorithms.Problems.NQueens;\n\npublic class BacktrackingNQueensSolver\n{\n /// <summary>\n /// Solves N-"
},
{
"path": "Algorithms/Problems/StableMarriage/Accepter.cs",
"chars": 354,
"preview": "namespace Algorithms.Problems.StableMarriage;\n\npublic class Accepter\n{\n public Proposer? EngagedTo { get; set; }\n\n "
},
{
"path": "Algorithms/Problems/StableMarriage/GaleShapley.cs",
"chars": 1897,
"preview": "namespace Algorithms.Problems.StableMarriage;\n\npublic static class GaleShapley\n{\n /// <summary>\n /// Finds a s"
},
{
"path": "Algorithms/Problems/StableMarriage/Proposer.cs",
"chars": 190,
"preview": "namespace Algorithms.Problems.StableMarriage;\n\npublic class Proposer\n{\n public Accepter? EngagedTo { get; set; }\n\n "
},
{
"path": "Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs",
"chars": 4742,
"preview": "namespace Algorithms.Problems.TravelingSalesman;\n\n/// <summary>\n/// Provides methods to solve the Traveling Salesman Pro"
},
{
"path": "Algorithms/RecommenderSystem/CollaborativeFiltering.cs",
"chars": 3292,
"preview": "namespace Algorithms.RecommenderSystem;\n\npublic class CollaborativeFiltering(ISimilarityCalculator similarityCalculator)"
},
{
"path": "Algorithms/RecommenderSystem/ISimilarityCalculator.cs",
"chars": 216,
"preview": "namespace Algorithms.RecommenderSystem\n{\n public interface ISimilarityCalculator\n {\n double CalculateSimila"
},
{
"path": "Algorithms/Search/AStar/AStar.cs",
"chars": 4534,
"preview": "namespace Algorithms.Search.AStar;\n\n/// <summary>\n/// Contains the code for A* Pathfinding.\n/// </summary>\npublic st"
},
{
"path": "Algorithms/Search/AStar/Node.cs",
"chars": 3324,
"preview": "namespace Algorithms.Search.AStar;\n\n/// <summary>\n/// Contains Positional and other information about a single node."
},
{
"path": "Algorithms/Search/AStar/NodeState.cs",
"chars": 349,
"preview": "namespace Algorithms.Search.AStar;\n\n/// <summary>\n/// The states the nodes can have.\n/// </summary>\npublic enum Node"
},
{
"path": "Algorithms/Search/AStar/PathfindingException.cs",
"chars": 252,
"preview": "namespace Algorithms.Search.AStar;\n\n/// <summary>\n/// A pathfinding exception is thrown when the Pathfinder encounte"
},
{
"path": "Algorithms/Search/AStar/PriorityQueue.cs",
"chars": 3950,
"preview": "// todo: extract to data structures\nnamespace Algorithms.Search.AStar;\n\n/// <summary>\n/// Generic Priority Queue.\n//"
},
{
"path": "Algorithms/Search/AStar/VecN.cs",
"chars": 2909,
"preview": "namespace Algorithms.Search.AStar;\n\n/// <summary>\n/// Vector Struct with N Dimensions.\n/// </summary>\n/// <remarks>\n"
},
{
"path": "Algorithms/Search/BinarySearcher.cs",
"chars": 1411,
"preview": "namespace Algorithms.Search;\n\n/// <summary>\n/// Binary Searcher checks an array for element specified by checking\n//"
},
{
"path": "Algorithms/Search/BoyerMoore.cs",
"chars": 1364,
"preview": "namespace Algorithms.Search;\r\n\r\n/// <summary>\r\n/// A Boyer-Moore majority finder algorithm implementation.\r\n/// </su"
},
{
"path": "Algorithms/Search/FastSearcher.cs",
"chars": 2468,
"preview": "using Utilities.Exceptions;\n\nnamespace Algorithms.Search;\n\n/// <summary>\n/// The idea: you could combine the advanta"
},
{
"path": "Algorithms/Search/FibonacciSearcher.cs",
"chars": 3257,
"preview": "namespace Algorithms.Search;\n\n/// <summary>\n/// Class that implements Fibonacci search algorithm.\n/// </summary>\n///"
},
{
"path": "Algorithms/Search/InterpolationSearch.cs",
"chars": 1458,
"preview": "namespace Algorithms.Search;\n\n/// <summary>\n/// Class that implements interpolation search algorithm.\n/// </summary>"
},
{
"path": "Algorithms/Search/JumpSearcher.cs",
"chars": 1893,
"preview": "namespace Algorithms.Search;\n\n/// <summary>\n/// Jump Search checks fewer elements by jumping ahead by fixed steps.\n/"
},
{
"path": "Algorithms/Search/LinearSearcher.cs",
"chars": 1469,
"preview": "using Utilities.Exceptions;\n\nnamespace Algorithms.Search;\n\n/// <summary>\n/// Class that implements linear search alg"
},
{
"path": "Algorithms/Search/RecursiveBinarySearcher.cs",
"chars": 2271,
"preview": "namespace Algorithms.Search;\n\n/// <summary>\n/// RecursiveBinarySearcher.\n/// </summary>\n/// <typeparam name=\"T\">Type"
},
{
"path": "Algorithms/Sequences/AllOnesSequence.cs",
"chars": 494,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// The all ones sequence.\n/// </para>\n/// "
},
{
"path": "Algorithms/Sequences/AllThreesSequence.cs",
"chars": 425,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// The all threes sequence.\n/// </para>\n/// "
},
{
"path": "Algorithms/Sequences/AllTwosSequence.cs",
"chars": 421,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// The all twos sequence.\n/// </para>\n/// "
},
{
"path": "Algorithms/Sequences/BinaryPrimeConstantSequence.cs",
"chars": 926,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of binary prime constant\n/// "
},
{
"path": "Algorithms/Sequences/BinomialSequence.cs",
"chars": 1352,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of binomial coefficients.\n/// </p"
},
{
"path": "Algorithms/Sequences/CakeNumbersSequence.cs",
"chars": 656,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Cake numbers: maximal number of pieces resulti"
},
{
"path": "Algorithms/Sequences/CatalanSequence.cs",
"chars": 868,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Catalan numbers: C[n+1] = (2*(2*n+1)*C[n])/(n+"
},
{
"path": "Algorithms/Sequences/CentralPolygonalNumbersSequence.cs",
"chars": 680,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Central polygonal numbers (the Lazy Caterer's "
},
{
"path": "Algorithms/Sequences/CubesSequence.cs",
"chars": 665,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of cube numbers.\n/// </para>\n/// "
},
{
"path": "Algorithms/Sequences/DivisorsCountSequence.cs",
"chars": 933,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of the number of divisors of n, start"
},
{
"path": "Algorithms/Sequences/EuclidNumbersSequence.cs",
"chars": 745,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Euclid numbers: 1 + product of the"
},
{
"path": "Algorithms/Sequences/EulerTotientSequence.cs",
"chars": 3185,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Euler totient function phi(n).\n///"
},
{
"path": "Algorithms/Sequences/FactorialSequence.cs",
"chars": 742,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of factorial numbers.\n/// </para>"
},
{
"path": "Algorithms/Sequences/FermatNumbersSequence.cs",
"chars": 694,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Fermat numbers: a(n) = 2^(2^n) + 1"
},
{
"path": "Algorithms/Sequences/FermatPrimesSequence.cs",
"chars": 751,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Fermat primes: primes of the form "
},
{
"path": "Algorithms/Sequences/FibonacciSequence.cs",
"chars": 840,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Fibonacci sequence.\n/// </para>\n/// <p"
},
{
"path": "Algorithms/Sequences/GolombsSequence.cs",
"chars": 1027,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Golomb's sequence. a(n) is the number of times"
},
{
"path": "Algorithms/Sequences/ISequence.cs",
"chars": 269,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// Common interface for all integer sequences.\n/// </summary>\npublic"
},
{
"path": "Algorithms/Sequences/KolakoskiSequence.cs",
"chars": 1098,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Kolakoski sequence; n-th element is the length"
},
{
"path": "Algorithms/Sequences/KolakoskiSequence2.cs",
"chars": 1046,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Kolakoski sequence; n-th element is the length"
},
{
"path": "Algorithms/Sequences/KummerNumbersSequence.cs",
"chars": 822,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Kummer numbers (also called Euclid"
},
{
"path": "Algorithms/Sequences/LucasNumbersBeginningAt2Sequence.cs",
"chars": 2032,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of Lucas number values.\n/// </par"
},
{
"path": "Algorithms/Sequences/MakeChangeSequence.cs",
"chars": 1624,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Number of ways of making change for n cents us"
},
{
"path": "Algorithms/Sequences/MatchstickTriangleSequence.cs",
"chars": 2291,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of number of triangles in triangular "
},
{
"path": "Algorithms/Sequences/NaturalSequence.cs",
"chars": 648,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of natural numbers.\n/// </para>\n/"
},
{
"path": "Algorithms/Sequences/NegativeIntegersSequence.cs",
"chars": 659,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of negative integers.\n/// </para>"
},
{
"path": "Algorithms/Sequences/NumberOfBooleanFunctionsSequence.cs",
"chars": 803,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of number of truth tables generated b"
},
{
"path": "Algorithms/Sequences/NumberOfPrimesByNumberOfDigitsSequence.cs",
"chars": 1047,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Number of primes with n digits\n/// (Th"
},
{
"path": "Algorithms/Sequences/NumberOfPrimesByPowersOf10Sequence.cs",
"chars": 987,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of number of primes less than 10^n (w"
},
{
"path": "Algorithms/Sequences/OnesCountingSequence.cs",
"chars": 3212,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// 1's-counting sequence: number of 1's in binar"
},
{
"path": "Algorithms/Sequences/PowersOf10Sequence.cs",
"chars": 675,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of powers of 10: a(n) = 10^n.\n/// "
},
{
"path": "Algorithms/Sequences/PowersOf2Sequence.cs",
"chars": 671,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of powers of 2: a(n) = 2^n.\n/// <"
},
{
"path": "Algorithms/Sequences/PrimePiSequence.cs",
"chars": 936,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of number of primes less than or equa"
},
{
"path": "Algorithms/Sequences/PrimesSequence.cs",
"chars": 911,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of prime numbers.\n/// </para>\n///"
},
{
"path": "Algorithms/Sequences/PrimorialNumbersSequence.cs",
"chars": 771,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of primorial numbers: product of firs"
},
{
"path": "Algorithms/Sequences/RecamansSequence.cs",
"chars": 1149,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Recaman's sequence. a(0) = 0; for n > 0, a(n) "
},
{
"path": "Algorithms/Sequences/SquaresSequence.cs",
"chars": 664,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of square numbers.\n/// </para>\n//"
},
{
"path": "Algorithms/Sequences/TetrahedralSequence.cs",
"chars": 1152,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Sequence of tetrahedral (triangular pyramids)"
},
{
"path": "Algorithms/Sequences/TetranacciNumbersSequence.cs",
"chars": 811,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Tetranacci numbers: a(n) = a(n-1) + a(n-2) + a"
},
{
"path": "Algorithms/Sequences/ThreeNPlusOneStepsSequence.cs",
"chars": 1270,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Number of halving and tripling steps to reach "
},
{
"path": "Algorithms/Sequences/TribonacciNumbersSequence.cs",
"chars": 738,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Tribonacci numbers: a(n) = a(n-1) + a(n-2) + a"
},
{
"path": "Algorithms/Sequences/VanEcksSequence.cs",
"chars": 1177,
"preview": "namespace Algorithms.Sequences;\n\n/// <summary>\n/// <para>\n/// Van Eck's sequence. For n >= 1, if there exist"
}
]
// ... and 427 more files (download for full content)
About this extraction
This page contains the full source code of the TheAlgorithms/C-Sharp GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 627 files (1.9 MB), approximately 522.9k tokens, and a symbol index with 3248 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.