├── .clang-format ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ ├── feature_request.yml │ └── other.yml ├── dependabot.yml ├── pull_request_template.md └── workflows │ ├── build.yml │ ├── clang-format-lint.yml │ ├── codeql.yml │ ├── stale.yml │ └── update_directory.yml ├── .gitignore ├── .gitpod.dockerfile ├── .gitpod.yml ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE ├── README-ko.md ├── README.md ├── checkstyle.xml ├── pmd-exclude.properties ├── pom.xml ├── spotbugs-exclude.xml └── src ├── main └── java │ └── com │ └── thealgorithms │ ├── audiofilters │ └── IIRFilter.java │ ├── backtracking │ ├── AllPathsFromSourceToTarget.java │ ├── ArrayCombination.java │ ├── Combination.java │ ├── FloodFill.java │ ├── KnightsTour.java │ ├── MColoring.java │ ├── MazeRecursion.java │ ├── NQueens.java │ ├── ParenthesesGenerator.java │ ├── Permutation.java │ ├── PowerSum.java │ ├── SubsequenceFinder.java │ └── WordSearch.java │ ├── bitmanipulation │ ├── BitSwap.java │ ├── HighestSetBit.java │ ├── IndexOfRightMostSetBit.java │ ├── IsEven.java │ ├── IsPowerTwo.java │ ├── NonRepeatingNumberFinder.java │ ├── NumbersDifferentSigns.java │ ├── ReverseBits.java │ └── SingleBitOperations.java │ ├── ciphers │ ├── AES.java │ ├── AESEncryption.java │ ├── AffineCipher.java │ ├── Blowfish.java │ ├── Caesar.java │ ├── ColumnarTranspositionCipher.java │ ├── DES.java │ ├── HillCipher.java │ ├── PlayfairCipher.java │ ├── Polybius.java │ ├── ProductCipher.java │ ├── RSA.java │ ├── SimpleSubCipher.java │ ├── Vigenere.java │ └── a5 │ │ ├── A5Cipher.java │ │ ├── A5KeyStreamGenerator.java │ │ ├── BaseLFSR.java │ │ ├── CompositeLFSR.java │ │ ├── LFSR.java │ │ └── Utils.java │ ├── conversions │ ├── AnyBaseToAnyBase.java │ ├── AnyBaseToDecimal.java │ ├── AnytoAny.java │ ├── BinaryToDecimal.java │ ├── BinaryToHexadecimal.java │ ├── BinaryToOctal.java │ ├── DecimalToAnyBase.java │ ├── DecimalToBinary.java │ ├── DecimalToHexaDecimal.java │ ├── DecimalToOctal.java │ ├── HexToOct.java │ ├── HexaDecimalToBinary.java │ ├── HexaDecimalToDecimal.java │ ├── IntegerToRoman.java │ ├── OctalToBinary.java │ ├── OctalToDecimal.java │ ├── OctalToHexadecimal.java │ ├── RgbHsvConversion.java │ ├── RomanToInteger.java │ └── TurkishToLatinConversion.java │ ├── datastructures │ ├── Node.java │ ├── bags │ │ └── Bag.java │ ├── bloomfilter │ │ └── BloomFilter.java │ ├── buffers │ │ └── CircularBuffer.java │ ├── caches │ │ ├── LFUCache.java │ │ ├── LRUCache.java │ │ └── MRUCache.java │ ├── crdt │ │ ├── GCounter.java │ │ ├── GSet.java │ │ ├── LWWElementSet.java │ │ ├── ORSet.java │ │ ├── PNCounter.java │ │ └── TwoPSet.java │ ├── disjointsetunion │ │ ├── DisjointSetUnion.java │ │ └── Node.java │ ├── dynamicarray │ │ └── DynamicArray.java │ ├── graphs │ │ ├── AStar.java │ │ ├── BellmanFord.java │ │ ├── BipartiteGrapfDFS.java │ │ ├── BoruvkaAlgorithm.java │ │ ├── ConnectedComponent.java │ │ ├── Cycles.java │ │ ├── DIJSKSTRAS_ALGORITHM.java │ │ ├── FloydWarshall.java │ │ ├── Graphs.java │ │ ├── HamiltonianCycle.java │ │ ├── KahnsAlgorithm.java │ │ ├── Kosaraju.java │ │ ├── Kruskal.java │ │ ├── MatrixGraphs.java │ │ ├── PrimMST.java │ │ ├── README.md │ │ ├── TarjansAlgorithm.java │ │ └── WelshPowell.java │ ├── hashmap │ │ ├── Readme.md │ │ └── hashing │ │ │ ├── GenericHashMapUsingArray.java │ │ │ ├── GenericHashMapUsingArrayList.java │ │ │ ├── HashMap.java │ │ │ ├── HashMapCuckooHashing.java │ │ │ ├── Intersection.java │ │ │ ├── LinearProbingHashMap.java │ │ │ ├── Main.java │ │ │ ├── MainCuckooHashing.java │ │ │ ├── MajorityElement.java │ │ │ └── Map.java │ ├── heaps │ │ ├── EmptyHeapException.java │ │ ├── FibonacciHeap.java │ │ ├── GenericHeap.java │ │ ├── Heap.java │ │ ├── HeapElement.java │ │ ├── LeftistHeap.java │ │ ├── MaxHeap.java │ │ ├── MinHeap.java │ │ ├── MinPriorityQueue.java │ │ └── Readme.md │ ├── lists │ │ ├── CircleLinkedList.java │ │ ├── CountSinglyLinkedListRecursion.java │ │ ├── CreateAndDetectLoop.java │ │ ├── CursorLinkedList.java │ │ ├── DoublyLinkedList.java │ │ ├── MergeKSortedLinkedlist.java │ │ ├── MergeSortedArrayList.java │ │ ├── MergeSortedSinglyLinkedList.java │ │ ├── QuickSortLinkedList.java │ │ ├── README.md │ │ ├── RandomNode.java │ │ ├── ReverseKGroup.java │ │ ├── RotateSinglyLinkedLists.java │ │ ├── SearchSinglyLinkedListRecursion.java │ │ ├── SinglyLinkedList.java │ │ └── SkipList.java │ ├── queues │ │ ├── CircularQueue.java │ │ ├── Deques.java │ │ ├── GenericArrayListQueue.java │ │ ├── LinkedQueue.java │ │ ├── PriorityQueues.java │ │ ├── Queues.java │ │ └── README.md │ ├── stacks │ │ ├── NodeStack.java │ │ ├── README.md │ │ ├── ReverseStack.java │ │ ├── StackArray.java │ │ ├── StackArrayList.java │ │ └── StackOfLinkedList.java │ └── trees │ │ ├── AVLSimple.java │ │ ├── AVLTree.java │ │ ├── BSTFromSortedArray.java │ │ ├── BSTIterative.java │ │ ├── BSTRecursive.java │ │ ├── BSTRecursiveGeneric.java │ │ ├── BinaryTree.java │ │ ├── CeilInBinarySearchTree.java │ │ ├── CheckBinaryTreeIsValidBST.java │ │ ├── CheckIfBinaryTreeBalanced.java │ │ ├── CheckTreeIsSymmetric.java │ │ ├── CreateBinaryTreeFromInorderPreorder.java │ │ ├── FenwickTree.java │ │ ├── GenericTree.java │ │ ├── InorderTraversal.java │ │ ├── KDTree.java │ │ ├── LCA.java │ │ ├── LazySegmentTree.java │ │ ├── LevelOrderTraversal.java │ │ ├── PostOrderTraversal.java │ │ ├── PreOrderTraversal.java │ │ ├── PrintTopViewofTree.java │ │ ├── README.md │ │ ├── RedBlackBST.java │ │ ├── SameTreesCheck.java │ │ ├── SegmentTree.java │ │ ├── TreeRandomNode.java │ │ ├── TrieImp.java │ │ ├── VerticalOrderTraversal.java │ │ ├── ZigzagTraversal.java │ │ └── nearestRightKey.java │ ├── devutils │ ├── entities │ │ └── ProcessDetails.java │ ├── nodes │ │ ├── LargeTreeNode.java │ │ ├── Node.java │ │ ├── SimpleNode.java │ │ ├── SimpleTreeNode.java │ │ └── TreeNode.java │ └── searches │ │ ├── MatrixSearchAlgorithm.java │ │ └── SearchAlgorithm.java │ ├── divideandconquer │ ├── BinaryExponentiation.java │ ├── ClosestPair.java │ ├── SkylineAlgorithm.java │ └── StrassenMatrixMultiplication.java │ ├── dynamicprogramming │ ├── BoardPath.java │ ├── BoundaryFill.java │ ├── BruteForceKnapsack.java │ ├── CatalanNumber.java │ ├── ClimbingStairs.java │ ├── CoinChange.java │ ├── CountFriendsPairing.java │ ├── DiceThrow.java │ ├── EditDistance.java │ ├── EggDropping.java │ ├── Fibonacci.java │ ├── FordFulkerson.java │ ├── KadaneAlgorithm.java │ ├── Knapsack.java │ ├── KnapsackMemoization.java │ ├── LevenshteinDistance.java │ ├── LongestAlternatingSubsequence.java │ ├── LongestCommonSubsequence.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestPalindromicSubsequence.java │ ├── LongestPalindromicSubstring.java │ ├── LongestValidParentheses.java │ ├── MatrixChainMultiplication.java │ ├── MatrixChainRecursiveTopDownMemoisation.java │ ├── MinimumPathSum.java │ ├── MinimumSumPartition.java │ ├── NewManShanksPrime.java │ ├── OptimalJobScheduling.java │ ├── PalindromicPartitioning.java │ ├── PartitionProblem.java │ ├── RegexMatching.java │ ├── RodCutting.java │ ├── ShortestCommonSupersequenceLength.java │ ├── SubsetCount.java │ ├── SubsetSum.java │ ├── SumOfSubset.java │ ├── Tribonacci.java │ ├── UniquePaths.java │ ├── WildcardMatching.java │ └── WineProblem.java │ ├── geometry │ └── GrahamScan.java │ ├── greedyalgorithms │ ├── ActivitySelection.java │ ├── CoinChange.java │ ├── FractionalKnapsack.java │ ├── JobSequencing.java │ └── MinimizingLateness.java │ ├── io │ └── BufferedReader.java │ ├── maths │ ├── ADTFraction.java │ ├── AbsoluteMax.java │ ├── AbsoluteMin.java │ ├── AbsoluteValue.java │ ├── AliquotSum.java │ ├── AmicableNumber.java │ ├── Area.java │ ├── Armstrong.java │ ├── AutoCorrelation.java │ ├── AutomorphicNumber.java │ ├── Average.java │ ├── BinaryPow.java │ ├── BinomialCoefficient.java │ ├── Ceil.java │ ├── CircularConvolutionFFT.java │ ├── CollatzConjecture.java │ ├── Combinations.java │ ├── Convolution.java │ ├── ConvolutionFFT.java │ ├── CrossCorrelation.java │ ├── DeterminantOfMatrix.java │ ├── DigitalRoot.java │ ├── DistanceFormula.java │ ├── DudeneyNumber.java │ ├── EulerMethod.java │ ├── FFT.java │ ├── FFTBluestein.java │ ├── Factorial.java │ ├── FactorialRecursion.java │ ├── FastInverseSqrt.java │ ├── FibonacciJavaStreams.java │ ├── FibonacciLoop.java │ ├── FibonacciNumberCheck.java │ ├── FibonacciNumberGoldenRation.java │ ├── FindKthNumber.java │ ├── FindMax.java │ ├── FindMaxRecursion.java │ ├── FindMin.java │ ├── FindMinRecursion.java │ ├── Floor.java │ ├── FrizzyNumber.java │ ├── GCD.java │ ├── GCDRecursion.java │ ├── Gaussian.java │ ├── GenericRoot.java │ ├── HarshadNumber.java │ ├── HeronsFormula.java │ ├── JosephusProblem.java │ ├── JugglerSequence.java │ ├── KaprekarNumbers.java │ ├── KeithNumber.java │ ├── KrishnamurthyNumber.java │ ├── LeastCommonMultiple.java │ ├── LeonardoNumber.java │ ├── LinearDiophantineEquationsSolver.java │ ├── LiouvilleLambdaFunction.java │ ├── LongDivision.java │ ├── LucasSeries.java │ ├── MagicSquare.java │ ├── MatrixRank.java │ ├── MatrixUtil.java │ ├── MaxValue.java │ ├── Means.java │ ├── Median.java │ ├── MillerRabinPrimalityCheck.java │ ├── MinValue.java │ ├── MobiusFunction.java │ ├── Mode.java │ ├── NonRepeatingElement.java │ ├── NthUglyNumber.java │ ├── NumberOfDigits.java │ ├── PalindromeNumber.java │ ├── ParseInteger.java │ ├── PascalTriangle.java │ ├── PerfectCube.java │ ├── PerfectNumber.java │ ├── PerfectSquare.java │ ├── Perimeter.java │ ├── PiNilakantha.java │ ├── PollardRho.java │ ├── Pow.java │ ├── PowerOfTwoOrNot.java │ ├── PowerUsingRecursion.java │ ├── PrimeCheck.java │ ├── PrimeFactorization.java │ ├── PronicNumber.java │ ├── PythagoreanTriple.java │ ├── ReverseNumber.java │ ├── RomanNumeralUtil.java │ ├── SecondMinMax.java │ ├── SimpsonIntegration.java │ ├── SquareFreeInteger.java │ ├── SquareRootWithBabylonianMethod.java │ ├── SquareRootWithNewtonRaphsonMethod.java │ ├── StandardDeviation.java │ ├── StandardScore.java │ ├── StrobogrammaticNumber.java │ ├── SumOfArithmeticSeries.java │ ├── SumOfDigits.java │ ├── SumWithoutArithmeticOperators.java │ ├── TrinomialTriangle.java │ ├── TwinPrime.java │ ├── VampireNumber.java │ ├── VectorCrossProduct.java │ └── Volume.java │ ├── matrixexponentiation │ └── Fibonacci.java │ ├── misc │ ├── ColorContrastRatio.java │ ├── InverseOfMatrix.java │ ├── MapReduce.java │ ├── MatrixTranspose.java │ ├── MedianOfMatrix.java │ ├── MedianOfRunningArray.java │ ├── MedianOfRunningArrayByte.java │ ├── MedianOfRunningArrayDouble.java │ ├── MedianOfRunningArrayFloat.java │ ├── MedianOfRunningArrayInteger.java │ ├── MedianOfRunningArrayLong.java │ ├── MirrorOfMatrix.java │ ├── PalindromePrime.java │ ├── PalindromeSinglyLinkedList.java │ ├── RangeInSortedArray.java │ ├── Sort012D.java │ ├── Sparsity.java │ ├── ThreeSumProblem.java │ ├── TwoSumProblem.java │ └── WordBoggle.java │ ├── others │ ├── ArrayLeftRotation.java │ ├── BFPRT.java │ ├── BankersAlgorithm.java │ ├── BoyerMoore.java │ ├── BrianKernighanAlgorithm.java │ ├── CRC16.java │ ├── CRC32.java │ ├── CRCAlgorithm.java │ ├── Conway.java │ ├── CountChar.java │ ├── CountSetBits.java │ ├── CountWords.java │ ├── Damm.java │ ├── Dijkstra.java │ ├── EulersFunction.java │ ├── FibbonaciSeries.java │ ├── FloydTriangle.java │ ├── GuassLegendre.java │ ├── HappyNumbersSeq.java │ ├── Huffman.java │ ├── Implementing_auto_completing_features_using_trie.java │ ├── InsertDeleteInArray.java │ ├── KMP.java │ ├── KochSnowflake.java │ ├── Krishnamurthy.java │ ├── LineSweep.java │ ├── LinearCongruentialGenerator.java │ ├── LowestBasePalindrome.java │ ├── Luhn.java │ ├── Mandelbrot.java │ ├── MaximumSumOfDistinctSubarraysWithLengthK.java │ ├── MemoryManagementAlgorithms.java │ ├── MiniMaxAlgorithm.java │ ├── PageRank.java │ ├── PasswordGen.java │ ├── PerlinNoise.java │ ├── PrintAMatrixInSpiralOrder.java │ ├── QueueUsingTwoStacks.java │ ├── RabinKarp.java │ ├── RemoveDuplicateFromString.java │ ├── ReturnSubsequence.java │ ├── ReverseStackUsingRecursion.java │ ├── RootPrecision.java │ ├── RotateMatrixBy90Degrees.java │ ├── SieveOfEratosthenes.java │ ├── SkylineProblem.java │ ├── StringMatchFiniteAutomata.java │ ├── Sudoku.java │ ├── TowerOfHanoi.java │ ├── TwoPointers.java │ ├── Verhoeff.java │ └── cn │ │ └── HammingDistance.java │ ├── scheduling │ ├── FCFSScheduling.java │ ├── PreemptivePriorityScheduling.java │ ├── RRScheduling.java │ ├── SJFScheduling.java │ └── SRTFScheduling.java │ ├── searches │ ├── BinarySearch.java │ ├── BinarySearch2dArray.java │ ├── BreadthFirstSearch.java │ ├── DepthFirstSearch.java │ ├── ExponentalSearch.java │ ├── FibonacciSearch.java │ ├── HowManyTimesRotated.java │ ├── InterpolationSearch.java │ ├── IterativeBinarySearch.java │ ├── IterativeTernarySearch.java │ ├── JumpSearch.java │ ├── KMPSearch.java │ ├── LinearSearch.java │ ├── LinearSearchThread.java │ ├── LowerBound.java │ ├── MonteCarloTreeSearch.java │ ├── OrderAgnosticBinarySearch.java │ ├── PerfectBinarySearch.java │ ├── QuickSelect.java │ ├── RabinKarpAlgorithm.java │ ├── RecursiveBinarySearch.java │ ├── RowColumnWiseSorted2dArrayBinarySearch.java │ ├── SaddlebackSearch.java │ ├── SearchInARowAndColWiseSortedMatrix.java │ ├── SortOrderAgnosticBinarySearch.java │ ├── SquareRootBinarySearch.java │ ├── TernarySearch.java │ ├── UnionFind.java │ └── UpperBound.java │ ├── sorts │ ├── BeadSort.java │ ├── BinaryInsertionSort.java │ ├── BitonicSort.java │ ├── BogoSort.java │ ├── BubbleSort.java │ ├── BubbleSortRecursive.java │ ├── BucketSort.java │ ├── CircleSort.java │ ├── CocktailShakerSort.java │ ├── CombSort.java │ ├── CountingSort.java │ ├── CycleSort.java │ ├── DNFSort.java │ ├── DualPivotQuickSort.java │ ├── DutchNationalFlagSort.java │ ├── ExchangeSort.java │ ├── GnomeSort.java │ ├── HeapSort.java │ ├── InsertionSort.java │ ├── IntrospectiveSort.java │ ├── LinkListSort.java │ ├── MergeSort.java │ ├── MergeSortNoExtraSpace.java │ ├── MergeSortRecursive.java │ ├── OddEvenSort.java │ ├── PancakeSort.java │ ├── PigeonholeSort.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── SelectionSort.java │ ├── SelectionSortRecursive.java │ ├── ShellSort.java │ ├── SimpleSort.java │ ├── SlowSort.java │ ├── SortAlgorithm.java │ ├── SortUtils.java │ ├── SortUtilsRandomGenerator.java │ ├── StoogeSort.java │ ├── StrandSort.java │ ├── SwapSort.java │ ├── TimSort.java │ ├── TopologicalSort.java │ ├── TreeSort.java │ ├── WaveSort.java │ └── WiggleSort.java │ ├── stacks │ ├── BalancedBrackets.java │ ├── DecimalToAnyUsingStack.java │ ├── DuplicateBrackets.java │ ├── InfixToPostfix.java │ ├── LargestRectangle.java │ ├── MaximumMinimumWindow.java │ ├── NextGreaterElement.java │ ├── NextSmallerElement.java │ ├── PostfixToInfix.java │ └── StackPostfixNotation.java │ └── strings │ ├── AhoCorasick.java │ ├── Alphabetical.java │ ├── Anagrams.java │ ├── CharactersSame.java │ ├── CheckAnagrams.java │ ├── CheckVowels.java │ ├── HammingDistance.java │ ├── HorspoolSearch.java │ ├── Isomorphic.java │ ├── LetterCombinationsOfPhoneNumber.java │ ├── LongestNonRepeativeSubstring.java │ ├── LongestPalindromicSubstring.java │ ├── Lower.java │ ├── MyAtoi.java │ ├── Palindrome.java │ ├── Pangram.java │ ├── PermuteString.java │ ├── ReverseString.java │ ├── ReverseStringRecursive.java │ ├── ReverseWordsInString.java │ ├── Rotation.java │ ├── StringCompression.java │ ├── Upper.java │ ├── ValidParentheses.java │ ├── WordLadder.java │ └── zigZagPattern │ ├── README.md │ └── ZigZagPattern.java └── test └── java └── com └── thealgorithms ├── backtracking ├── AllPathsFromSourceToTargetTest.java ├── ArrayCombinationTest.java ├── CombinationTest.java ├── FloodFillTest.java ├── MColoringTest.java ├── MazeRecursionTest.java ├── ParenthesesGeneratorTest.java ├── PermutationTest.java ├── PowerSumTest.java ├── SubsequenceFinderTest.java └── WordSearchTest.java ├── bitmanipulation ├── BitSwapTest.java ├── HighestSetBitTest.java ├── IndexOfRightMostSetBitTest.java ├── IsEvenTest.java ├── IsPowerTwoTest.java ├── NonRepeatingNumberFinderTest.java ├── NumbersDifferentSignsTest.java ├── ReverseBitsTest.java └── SingleBitOperationsTest.java ├── ciphers ├── BlowfishTest.java ├── CaesarTest.java ├── DESTest.java ├── PlayfairTest.java ├── PolybiusTest.java ├── RSATest.java ├── SimpleSubCipherTest.java ├── VigenereTest.java └── a5 │ └── LFSRTest.java ├── conversions ├── BinaryToDecimalTest.java ├── BinaryToHexadecimalTest.java ├── BinaryToOctalTest.java ├── DecimalToHexaDecimalTest.java ├── HexToOctTest.java ├── HexaDecimalToBinaryTest.java ├── HexaDecimalToDecimalTest.java ├── IntegerToRomanTest.java ├── OctalToBinaryTest.java ├── OctalToDecimalTest.java ├── OctalToHexadecimalTest.java └── RomanToIntegerTest.java ├── datastructures ├── bloomfilter │ └── BloomFilterTest.java ├── buffers │ └── CircularBufferTest.java ├── caches │ ├── LFUCacheTest.java │ ├── LRUCacheTest.java │ └── MRUCacheTest.java ├── crdt │ ├── GCounterTest.java │ ├── GSetTest.java │ ├── LWWElementSetTest.java │ ├── ORSetTest.java │ ├── PNCounterTest.java │ └── TwoPSetTest.java ├── disjointsetunion │ └── DisjointSetUnionTest.java ├── graphs │ ├── BoruvkaAlgorithmTest.java │ ├── HamiltonianCycleTest.java │ ├── KosarajuTest.java │ ├── TarjansAlgorithmTest.java │ └── WelshPowellTest.java ├── hashmap │ ├── HashMapCuckooHashingTest.java │ └── hashing │ │ ├── GenericHashMapUsingArrayListTest.java │ │ ├── GenericHashMapUsingArrayTest.java │ │ ├── LinearProbingHashMapTest.java │ │ ├── MajorityElementTest.java │ │ └── MapTest.java ├── heaps │ ├── FibonacciHeapTest.java │ └── LeftistHeapTest.java ├── lists │ ├── QuickSortLinkedListTest.java │ ├── ReverseKGroupTest.java │ ├── RotateSinglyLinkedListsTest.java │ ├── SinglyLinkedListTest.java │ └── SkipListTest.java ├── queues │ ├── LinkedQueueTest.java │ └── PriorityQueuesTest.java └── trees │ ├── BSTFromSortedArrayTest.java │ ├── BSTIterativeTest.java │ ├── BSTRecursiveTest.java │ ├── BinaryTreeTest.java │ ├── CeilInBinarySearchTreeTest.java │ ├── CheckBinaryTreeIsValidBSTTest.java │ ├── CheckIfBinaryTreeBalancedTest.java │ ├── CheckTreeIsSymmetricTest.java │ ├── CreateBinaryTreeFromInorderPreorderTest.java │ ├── InorderTraversalTest.java │ ├── KDTreeTest.java │ ├── LazySegmentTreeTest.java │ ├── LevelOrderTraversalTest.java │ ├── PostOrderTraversalTest.java │ ├── PreOrderTraversalTest.java │ ├── SameTreesCheckTest.java │ ├── TreeTestUtils.java │ ├── VerticalOrderTraversalTest.java │ └── ZigzagTraversalTest.java ├── divideandconquer ├── BinaryExponentiationTest.java └── StrassenMatrixMultiplicationTest.java ├── dynamicprogramming ├── CatalanNumberTest.java ├── ClimbStairsTest.java ├── EggDroppingTest.java ├── KnapsackMemoizationTest.java ├── KnapsackTest.java ├── LevenshteinDistanceTests.java ├── LongestIncreasingSubsequenceTests.java ├── LongestValidParenthesesTest ├── MinimumPathSumTest.java ├── MinimumSumPartitionTest.java ├── OptimalJobSchedulingTest.java ├── PartitionProblemTest.java ├── SubsetCountTest.java ├── SumOfSubsetTest.java ├── TribonacciTest.java ├── UniquePathsTests.java └── WildcardMatchingTest.java ├── geometry └── GrahamScanTest.java ├── greedyalgorithms ├── ActivitySelectionTest.java ├── CoinChangeTest.java ├── FractionalKnapsackTest.java ├── JobSequencingTest.java └── MinimizingLatenessTest.java ├── io └── BufferedReaderTest.java ├── maths ├── ADTFractionTest.java ├── AbsoluteMaxTest.java ├── AbsoluteMinTest.java ├── AbsoluteValueTest.java ├── AliquotSumTest.java ├── AmicableNumberTest.java ├── AreaTest.java ├── ArmstrongTest.java ├── AutoCorrelationTest.java ├── AutomorphicNumberTest.java ├── AverageTest.java ├── BinaryPowTest.java ├── BinomialCoefficientTest.java ├── CeilTest.java ├── CollatzConjectureTest.java ├── CombinationsTest.java ├── CrossCorrelationTest.java ├── DigitalRootTest.java ├── DistanceFormulaTest.java ├── DudeneyNumberTest.java ├── FFTTest.java ├── FactorialRecursionTest.java ├── FactorialTest.java ├── FastInverseSqrtTests.java ├── FibonacciJavaStreamsTest.java ├── FibonacciLoopTest.java ├── FibonacciNumberCheckTest.java ├── FibonacciNumberGoldenRationTest.java ├── FindMaxRecursionTest.java ├── FindMaxTest.java ├── FindMinRecursionTest.java ├── FindMinTest.java ├── FloorTest.java ├── FrizzyNumberTest.java ├── GCDTest.java ├── GaussianTest.java ├── GenericRootTest.java ├── HarshadNumberTest.java ├── HeronsFormulaTest.java ├── JosephusProblemTest.java ├── KaprekarNumbersTest.java ├── LeastCommonMultipleTest.java ├── LeonardoNumberTest.java ├── LiouvilleLambdaFunctionTest.java ├── LongDivisionTest.java ├── LucasSeriesTest.java ├── MatrixRankTest.java ├── MatrixUtilTest.java ├── MaxValueTest.java ├── MeansTest.java ├── MedianTest.java ├── MillerRabinPrimalityCheckTest.java ├── MinValueTest.java ├── MobiusFunctionTest.java ├── ModeTest.java ├── NthUglyNumberTest.java ├── NumberOfDigitsTest.java ├── PalindromeNumberTest.java ├── ParseIntegerTest.java ├── PascalTriangleTest.java ├── PerfectCubeTest.java ├── PerfectNumberTest.java ├── PerfectSquareTest.java ├── PerimeterTest.java ├── PollardRhoTest.java ├── PowerOfTwoOrNotTest.java ├── PowerUsingRecursionTest.java ├── PrimeCheckTest.java ├── PrimeFactorizationTest.java ├── PronicNumberTest.java ├── PythagoreanTripleTest.java ├── ReverseNumberTest.java ├── SecondMinMaxTest.java ├── SquareFreeIntegerTest.java ├── SquareRootWithNewtonRaphsonTestMethod.java ├── SquareRootwithBabylonianMethodTest.java ├── StandardDeviationTest.java ├── StandardScoreTest.java ├── StrobogrammaticNumberTest.java ├── SumOfArithmeticSeriesTest.java ├── SumOfDigitsTest.java ├── SumWithoutArithmeticOperatorsTest.java ├── TestArmstrong.java ├── TwinPrimeTest.java └── VolumeTest.java ├── misc ├── MapReduceTest.java ├── MedianOfMatrixtest.java ├── MedianOfRunningArrayTest.java ├── MirrorOfMatrixTest.java ├── PalindromeSinglyLinkedListTest.java └── TwoSumProblemTest.java ├── others ├── ArrayLeftRotationTest.java ├── ArrayRightRotation.java ├── ArrayRightRotationTest.java ├── BestFitCPUTest.java ├── BoyerMooreTest.java ├── CRC16Test.java ├── CRCAlgorithmTest.java ├── ConwayTest.java ├── CountCharTest.java ├── CountFriendsPairingTest.java ├── CountSetBitsTest.java ├── CountWordsTest.java ├── EulersFunctionTest.java ├── FirstFitCPUTest.java ├── KadaneAlogrithmTest.java ├── LineSweepTest.java ├── LinkListSortTest.java ├── LowestBasePalindromeTest.java ├── MaximumSumOfDistinctSubarraysWithLengthKTest.java ├── NewManShanksPrimeTest.java ├── NextFitTest.java ├── PasswordGenTest.java ├── SieveOfEratosthenesTest.java ├── StringMatchFiniteAutomataTest.java ├── TestPrintMatrixInSpiralOrder.java ├── TwoPointersTest.java ├── WorstFitCPUTest.java └── cn │ └── HammingDistanceTest.java ├── scheduling ├── FCFSSchedulingTest.java ├── PreemptivePrioritySchedulingTest.java ├── RRSchedulingTest.java ├── SJFSchedulingTest.java └── SRTFSchedulingTest.java ├── searches ├── BinarySearch2dArrayTest.java ├── BreadthFirstSearchTest.java ├── DepthFirstSearchTest.java ├── HowManyTimesRotatedTest.java ├── KMPSearchTest.java ├── OrderAgnosticBinarySearchTest.java ├── PerfectBinarySearchTest.java ├── QuickSelectTest.java ├── RabinKarpAlgorithmTest.java ├── RecursiveBinarySearchTest.java ├── RowColumnWiseSorted2dArrayBinarySearchTest.java ├── SortOrderAgnosticBinarySearchTest.java └── TestSearchInARowAndColWiseSortedMatrix.java ├── sorts ├── BeadSortTest.java ├── BinaryInsertionSortTest.java ├── BitonicSortTest.java ├── BogoSortTest.java ├── BubbleSortRecursiveTest.java ├── BubbleSortTest.java ├── BucketSortTest.java ├── CircleSortTest.java ├── CocktailShakerSortTest.java ├── CombSortTest.java ├── DualPivotQuickSortTest.java ├── DutchNationalFlagSortTest.java ├── ExchangeSortTest.java ├── GnomeSortTest.java ├── HeapSortTest.java ├── InsertionSortTest.java ├── IntrospectiveSortTest.java ├── MergeSortRecursiveTest.java ├── MergeSortTest.java ├── OddEvenSortTest.java ├── PancakeSortTest.java ├── QuickSortTest.java ├── SelectionSortRecursiveTest.java ├── SelectionSortTest.java ├── ShellSortTest.java ├── SimpleSortTest.java ├── SlowSortTest.java ├── SortUtilsRandomGeneratorTest.java ├── SortUtilsTest.java ├── SortingAlgorithmTest.java ├── StrandSortTest.java ├── SwapSortTest.java ├── TimSortTest.java ├── TopologicalSortTest.java ├── TreeSortTest.java ├── WaveSortTest.java └── WiggleSortTest.java ├── stacks └── StackPostfixNotationTest.java └── strings ├── AhoCorasickTest.java ├── AlphabeticalTest.java ├── AnagramsTest.java ├── CharacterSameTest.java ├── CheckAnagramsTest.java ├── CheckVowelsTest.java ├── HammingDistanceTest.java ├── HorspoolSearchTest.java ├── IsomorphicTest.java ├── LetterCombinationsOfPhoneNumberTest.java ├── LongestNonRepeativeSubstringTest.java ├── LowerTest.java ├── MyAtoiTest.java ├── PalindromeTest.java ├── PangramTest.java ├── ReverseStringRecursiveTest.java ├── ReverseStringTest.java ├── ReverseWordsInStringTest.java ├── RotationTest.java ├── StringCompressionTest.java ├── UpperTest.java ├── ValidParenthesesTest.java ├── WordLadderTest.java └── zigZagPattern └── ZigZagPatternTest.java /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @yanglbme @vil02 @BamaCharanChhandogi 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Discord community 4 | url: https://the-algorithms.com/discord/ 5 | about: Have any questions or found any bugs? Please contact us via Discord 6 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/other.yml: -------------------------------------------------------------------------------- 1 | name: Other 2 | description: Use this for any other issues. Do NOT create blank issues 3 | title: "[OTHER]" 4 | labels: ["awaiting triage"] 5 | body: 6 | - type: textarea 7 | id: issuedescription 8 | attributes: 9 | label: What would you like to share? 10 | description: Provide a clear and concise explanation of your issue. 11 | validations: 12 | required: true 13 | - type: textarea 14 | id: extrainfo 15 | attributes: 16 | label: Additional information 17 | description: Is there anything else we should know about this issue? 18 | validations: 19 | required: false 20 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | --- 2 | version: 2 3 | updates: 4 | - package-ecosystem: "docker" 5 | directory: "/" 6 | schedule: 7 | interval: "weekly" 8 | 9 | - package-ecosystem: "github-actions" 10 | directory: "/.github/workflows/" 11 | schedule: 12 | interval: "daily" 13 | 14 | - package-ecosystem: "maven" 15 | directory: "/" 16 | schedule: 17 | interval: "daily" 18 | ... 19 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | 10 | 11 | - [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md). 12 | - [ ] This pull request is all my own work -- I have not plagiarized it. 13 | - [ ] All filenames are in PascalCase. 14 | - [ ] All functions and variable names follow Java naming conventions. 15 | - [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. 16 | - [ ] All new code is formatted with `clang-format -i --style=file path/to/your/file.java` -------------------------------------------------------------------------------- /.github/workflows/clang-format-lint.yml: -------------------------------------------------------------------------------- 1 | name: Clang format linter 2 | on: 3 | push: {} 4 | pull_request: {} 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@v4 12 | - uses: DoozyX/clang-format-lint-action@v0.17 13 | with: 14 | source: './src' 15 | extensions: 'java' 16 | clangFormatVersion: 16 17 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: "CodeQL" 3 | 4 | on: 5 | workflow_dispatch: 6 | push: 7 | branches: 8 | - master 9 | pull_request: 10 | schedule: 11 | - cron: '53 3 * * 0' 12 | 13 | env: 14 | LANGUAGE: 'java-kotlin' 15 | 16 | jobs: 17 | analyze: 18 | name: Analyze 19 | runs-on: 'ubuntu-latest' 20 | permissions: 21 | actions: read 22 | contents: read 23 | security-events: write 24 | 25 | steps: 26 | - name: Checkout repository 27 | uses: actions/checkout@v4 28 | 29 | - name: Set up JDK 30 | uses: actions/setup-java@v4 31 | with: 32 | java-version: 21 33 | distribution: 'adopt' 34 | 35 | - name: Initialize CodeQL 36 | uses: github/codeql-action/init@v3 37 | with: 38 | languages: ${{ env.LANGUAGE }} 39 | 40 | - name: Build 41 | run: mvn --batch-mode --update-snapshots verify 42 | 43 | - name: Perform CodeQL Analysis 44 | uses: github/codeql-action/analyze@v3 45 | with: 46 | category: "/language:${{env.LANGUAGE}}" 47 | ... 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gradle/wrapper/gradle-wrapper.properties 2 | 3 | ##----------Android---------- 4 | *.apk 5 | *.ap_ 6 | *.dex 7 | *.class 8 | bin/ 9 | gen/ 10 | build/ 11 | out/ 12 | 13 | # Ignoring Gradle build artifacts and project files 14 | ##----------Gradle---------- 15 | .gradle/ 16 | gradle-app.setting 17 | !gradle-wrapper.jar 18 | build/ 19 | 20 | # Ignoring Maven build artifacts and project files 21 | ##----------Maven---------- 22 | *.classpath 23 | *.project 24 | *.settings 25 | /target/ 26 | local.properties 27 | 28 | # Ignoring IntelliJ IDEA project files and configurations 29 | ##----------IDEA---------- 30 | *.iml 31 | .idea/ 32 | *.ipr 33 | *.iws 34 | 35 | # Ignoring Android Studio Navigation editor temporary files 36 | .navigation/ 37 | 38 | # Ignoring common system and editor-generated files 39 | ##----------Other---------- 40 | *~ 41 | .DS_Store 42 | gradle.properties 43 | .vscode 44 | *.log 45 | -------------------------------------------------------------------------------- /.gitpod.dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-java-21:2024-06-24-08-46-07 2 | 3 | ENV LLVM_SCRIPT="tmp_llvm.sh" 4 | 5 | RUN test ! -f "$LLVM_SCRIPT" \ 6 | && wget https://apt.llvm.org/llvm.sh -O "$LLVM_SCRIPT" \ 7 | && chmod +x "$LLVM_SCRIPT" 8 | 9 | USER root 10 | 11 | RUN ./"$LLVM_SCRIPT" 16 \ 12 | && apt-get update \ 13 | && apt-get install -y --no-install-recommends \ 14 | clang-format-16=1:16.0.6~++20231112100510+7cbf1a259152-1~exp1~20231112100554.106 \ 15 | && apt-get clean \ 16 | && rm -rf /var/lib/apt/lists/* 17 | 18 | RUN ln -s "$(command -v clang-format-16)" "/usr/bin/clang-format" 19 | 20 | USER gitpod 21 | 22 | RUN rm "$LLVM_SCRIPT" 23 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | --- 2 | image: 3 | file: .gitpod.dockerfile 4 | 5 | tasks: 6 | - init: | 7 | mvn dependency:resolve 8 | mvn compile 9 | 10 | vscode: 11 | extensions: 12 | - xaver.clang-format 13 | 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 The Algorithms 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/backtracking/ArrayCombination.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import java.util.List; 4 | import java.util.TreeSet; 5 | 6 | /** 7 | * Finds all permutations of 1...n of length k 8 | * @author TheClerici (git-TheClerici) 9 | */ 10 | public final class ArrayCombination { 11 | private ArrayCombination() { 12 | } 13 | private static int length; 14 | 15 | /** 16 | * Find all combinations of 1..n by creating an array and using backtracking in Combination.java 17 | * @param n max value of the array. 18 | * @param k length of combination 19 | * @return a list of all combinations of length k. If k == 0, return null. 20 | */ 21 | public static List> combination(int n, int k) { 22 | if (n <= 0) { 23 | return null; 24 | } 25 | length = k; 26 | Integer[] arr = new Integer[n]; 27 | for (int i = 1; i <= n; i++) { 28 | arr[i - 1] = i; 29 | } 30 | return Combination.combination(arr, length); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | public final class BitSwap { 4 | private BitSwap() { 5 | } 6 | /* 7 | * @brief Swaps the bits at the position posA and posB from data 8 | */ 9 | public static int bitSwap(int data, final int posA, final int posB) { 10 | if (SingleBitOperations.getBit(data, posA) != SingleBitOperations.getBit(data, posB)) { 11 | data ^= (1 << posA) ^ (1 << posB); 12 | } 13 | return data; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | import java.util.Optional; 3 | 4 | /** 5 | * Find Highest Set Bit 6 | * This class provides a function calculating the position (or index) 7 | * of the most significant bit being set to 1 in a given integer. 8 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 9 | */ 10 | 11 | public final class HighestSetBit { 12 | private HighestSetBit() { 13 | } 14 | 15 | public static Optional findHighestSetBit(int num) { 16 | if (num < 0) { 17 | throw new IllegalArgumentException("Input cannot be negative"); 18 | } 19 | 20 | if (num == 0) { 21 | return Optional.empty(); 22 | } 23 | 24 | int position = 0; 25 | while (num > 0) { 26 | num >>= 1; 27 | position++; 28 | } 29 | 30 | return Optional.of(position - 1); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Find The Index Of Right Most SetBit 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public final class IndexOfRightMostSetBit { 9 | private IndexOfRightMostSetBit() { 10 | } 11 | public static int indexOfRightMostSetBit(int n) { 12 | if (n == 0) { 13 | return -1; // No set bits 14 | } 15 | 16 | // Handle negative numbers by finding the two's complement 17 | if (n < 0) { 18 | n = -n; 19 | n = n & (~n + 1); // Get the rightmost set bit in positive form 20 | } 21 | 22 | int index = 0; 23 | while ((n & 1) == 0) { 24 | n = n >> 1; 25 | index++; 26 | } 27 | 28 | return index; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/IsEven.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Checks whether a number is even 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public final class IsEven { 9 | private IsEven() { 10 | } 11 | public static boolean isEven(int number) { 12 | return (number & 1) == 0; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Is number power of 2 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public final class IsPowerTwo { 9 | private IsPowerTwo() { 10 | } 11 | public static boolean isPowerTwo(int number) { 12 | if (number <= 0) { 13 | return false; 14 | } 15 | int ans = number & (number - 1); 16 | return ans == 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Find Non Repeating Number 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public final class NonRepeatingNumberFinder { 9 | private NonRepeatingNumberFinder() { 10 | } 11 | 12 | public static int findNonRepeatingNumber(int[] arr) { 13 | int result = 0; 14 | for (int num : arr) { 15 | result ^= num; 16 | } 17 | return result; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Numbers Different Signs 5 | * @author Bama Charan Chhandogi 6 | */ 7 | 8 | public final class NumbersDifferentSigns { 9 | private NumbersDifferentSigns() { 10 | } 11 | 12 | public static boolean differentSigns(int num1, int num2) { 13 | return (num1 ^ num2) < 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * Converts any Octal Number to a Binary Number 5 | * @author Bama Charan Chhandogi 6 | */ 7 | 8 | public final class ReverseBits { 9 | private ReverseBits() { 10 | } 11 | 12 | public static int reverseBits(int n) { 13 | int result = 0; 14 | int bitCount = 32; 15 | for (int i = 0; i < bitCount; i++) { 16 | result <<= 1; // Left shift the result to make space for the next bit 17 | result |= (n & 1); // OR operation to set the least significant bit of result with the current bit of n 18 | n >>= 1; // Right shift n to move on to the next bit 19 | } 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /* 4 | * Author: lukasb1b (https://github.com/lukasb1b) 5 | */ 6 | 7 | public final class SingleBitOperations { 8 | private SingleBitOperations() { 9 | } 10 | /** 11 | * Flip the bit at position 'bit' in 'num' 12 | */ 13 | public static int flipBit(final int num, final int bit) { 14 | return num ^ (1 << bit); 15 | } 16 | /** 17 | * Set the bit at position 'bit' to 1 in the 'num' variable 18 | */ 19 | public static int setBit(final int num, final int bit) { 20 | return num | (1 << bit); 21 | } 22 | /** 23 | * Clears the bit located at 'bit' from 'num' 24 | */ 25 | public static int clearBit(final int num, final int bit) { 26 | return num & ~(1 << bit); 27 | } 28 | /** 29 | * Get the bit located at 'bit' from 'num' 30 | */ 31 | public static int getBit(final int num, final int bit) { 32 | return ((num >> bit) & 1); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers.a5; 2 | 3 | import java.util.BitSet; 4 | 5 | // https://en.wikipedia.org/wiki/A5/1 6 | public class A5Cipher { 7 | 8 | private final A5KeyStreamGenerator keyStreamGenerator; 9 | private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something 10 | 11 | public A5Cipher(BitSet sessionKey, BitSet frameCounter) { 12 | keyStreamGenerator = new A5KeyStreamGenerator(); 13 | keyStreamGenerator.initialize(sessionKey, frameCounter); 14 | } 15 | 16 | public BitSet encrypt(BitSet plainTextBits) { 17 | // create a copy 18 | var result = new BitSet(KEY_STREAM_LENGTH); 19 | result.xor(plainTextBits); 20 | 21 | var key = keyStreamGenerator.getNextKeyStream(); 22 | result.xor(key); 23 | 24 | return result; 25 | } 26 | 27 | public void resetCounter() { 28 | keyStreamGenerator.reInitialize(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/ciphers/a5/BaseLFSR.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers.a5; 2 | 3 | import java.util.BitSet; 4 | 5 | public interface BaseLFSR { 6 | void initialize(BitSet sessionKey, BitSet frameCounter); 7 | boolean clock(); 8 | int SESSION_KEY_LENGTH = 64; 9 | int FRAME_COUNTER_LENGTH = 22; 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/ciphers/a5/Utils.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers.a5; 2 | 3 | // Source 4 | // http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html 5 | // package com.java2s; 6 | // License from project: Open Source License 7 | 8 | import java.util.BitSet; 9 | 10 | public final class Utils { 11 | private Utils() { 12 | } 13 | 14 | public static boolean increment(BitSet bits, int size) { 15 | int i = size - 1; 16 | while (i >= 0 && bits.get(i)) { 17 | bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/ 18 | } 19 | if (i < 0) { 20 | return false; 21 | } 22 | bits.set(i, true); 23 | return true; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | // given a source number , source base, destination base, this code can give you the destination 6 | // number. 7 | // sn ,sb,db ---> ()dn . this is what we have to do . 8 | 9 | public final class AnytoAny { 10 | private AnytoAny() { 11 | } 12 | 13 | public static void main(String[] args) { 14 | Scanner scn = new Scanner(System.in); 15 | int sn = scn.nextInt(); 16 | int sb = scn.nextInt(); 17 | int db = scn.nextInt(); 18 | int m = 1; 19 | int dec = 0; 20 | int dn = 0; 21 | while (sn != 0) { 22 | dec = dec + (sn % 10) * m; 23 | m *= sb; 24 | sn /= 10; 25 | } 26 | m = 1; 27 | while (dec != 0) { 28 | dn = dn + (dec % db) * m; 29 | m *= 10; 30 | dec /= db; 31 | } 32 | System.out.println(dn); 33 | scn.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | */ 8 | final class BinaryToDecimal { 9 | private BinaryToDecimal() { 10 | } 11 | 12 | public static long binaryToDecimal(long binNum) { 13 | long binCopy; 14 | long d; 15 | long s = 0; 16 | long power = 0; 17 | binCopy = binNum; 18 | while (binCopy != 0) { 19 | d = binCopy % 10; 20 | s += d * (long) Math.pow(2, power++); 21 | binCopy /= 10; 22 | } 23 | return s; 24 | } 25 | 26 | /** 27 | * Main Method 28 | * 29 | * @param args Command line arguments 30 | */ 31 | public static void main(String[] args) { 32 | Scanner sc = new Scanner(System.in); 33 | System.out.print("Binary number: "); 34 | System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong())); 35 | sc.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | */ 8 | public final class DecimalToOctal { 9 | private DecimalToOctal() { 10 | } 11 | 12 | /** 13 | * Main Method 14 | * 15 | * @param args Command line Arguments 16 | */ 17 | 18 | // enter in a decimal value to get Octal output 19 | public static void main(String[] args) { 20 | Scanner sc = new Scanner(System.in); 21 | int n; 22 | int k; 23 | int d; 24 | int s = 0; 25 | int c = 0; 26 | System.out.print("Decimal number: "); 27 | n = sc.nextInt(); 28 | k = n; 29 | while (k != 0) { 30 | d = k % 8; 31 | s += d * (int) Math.pow(10, c++); 32 | k /= 8; 33 | } 34 | 35 | System.out.println("Octal equivalent:" + s); 36 | sc.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Node { 7 | 8 | private final T value; 9 | private final List> children; 10 | 11 | public Node(final T value) { 12 | this.value = value; 13 | this.children = new ArrayList<>(); 14 | } 15 | 16 | public Node(final T value, final List> children) { 17 | this.value = value; 18 | this.children = children; 19 | } 20 | 21 | public T getValue() { 22 | return value; 23 | } 24 | 25 | public void addChild(Node child) { 26 | children.add(child); 27 | } 28 | 29 | public List> getChildren() { 30 | return children; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.disjointsetunion; 2 | 3 | public class Node { 4 | 5 | /** 6 | * The rank of the node, used for optimizing union operations. 7 | */ 8 | public int rank; 9 | 10 | /** 11 | * Reference to the parent node in the set. 12 | * Initially, a node is its own parent (represents a singleton set). 13 | */ 14 | public Node parent; 15 | 16 | /** 17 | * The data element associated with the node. 18 | */ 19 | public T data; 20 | 21 | public Node(final T data) { 22 | this.data = data; 23 | parent = this; // Initially, a node is its own parent. 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | 3 | public abstract class Map { 4 | 5 | abstract boolean put(Key key, Value value); 6 | 7 | abstract Value get(Key key); 8 | 9 | abstract boolean delete(Key key); 10 | 11 | abstract Iterable keys(); 12 | 13 | abstract int size(); 14 | 15 | public boolean contains(Key key) { 16 | return get(key) != null; 17 | } 18 | 19 | protected int hash(Key key, int size) { 20 | return (key.hashCode() & Integer.MAX_VALUE) % size; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/heaps/EmptyHeapException.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | /** 4 | * @author Nicolas Renard Exception to be thrown if the getElement method is 5 | * used on an empty heap. 6 | */ 7 | @SuppressWarnings("serial") 8 | public class EmptyHeapException extends Exception { 9 | 10 | public EmptyHeapException(String message) { 11 | super(message); 12 | } 13 | 14 | public EmptyHeapException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class CountSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 5; ++i) { 8 | list.insert(i); 9 | } 10 | assert list.count() == 5; 11 | } 12 | 13 | /** 14 | * Calculate the count of the list manually using recursion. 15 | * 16 | * @param head head of the list. 17 | * @return count of the list. 18 | */ 19 | private int countRecursion(Node head) { 20 | return head == null ? 0 : 1 + countRecursion(head.next); 21 | } 22 | 23 | /** 24 | * Returns the count of the list. 25 | */ 26 | @Override 27 | public int count() { 28 | return countRecursion(getHead()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | /** 4 | * Rotate a list 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public class RotateSinglyLinkedLists { 9 | public Node rotateRight(Node head, int k) { 10 | if (head == null || head.next == null || k == 0) { 11 | return head; 12 | } 13 | 14 | Node curr = head; 15 | int len = 1; 16 | while (curr.next != null) { 17 | curr = curr.next; 18 | len++; 19 | } 20 | 21 | curr.next = head; 22 | k = k % len; 23 | k = len - k; 24 | while (k > 0) { 25 | curr = curr.next; 26 | k--; 27 | } 28 | 29 | head = curr.next; 30 | curr.next = null; 31 | return head; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 10; ++i) { 8 | list.insert(i); 9 | } 10 | 11 | for (int i = 1; i <= 10; ++i) { 12 | assert list.search(i); 13 | } 14 | assert !list.search(-1) && !list.search(100); 15 | } 16 | 17 | /** 18 | * Test if the value key is present in the list using recursion. 19 | * 20 | * @param node the head node. 21 | * @param key the value to be searched. 22 | * @return {@code true} if key is present in the list, otherwise 23 | * {@code false}. 24 | */ 25 | private boolean searchRecursion(Node node, int key) { 26 | return (node != null && (node.value == key || searchRecursion(node.next, key))); 27 | } 28 | 29 | @Override 30 | public boolean search(int key) { 31 | return searchRecursion(getHead(), key); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class FenwickTree { 4 | 5 | private int n; 6 | private int[] fenTree; 7 | 8 | /* Constructor which takes the size of the array as a parameter */ 9 | public FenwickTree(int n) { 10 | this.n = n; 11 | this.fenTree = new int[n + 1]; 12 | } 13 | 14 | /* A function which will add the element val at index i*/ 15 | public void update(int i, int val) { 16 | // As index starts from 0, increment the index by 1 17 | i += 1; 18 | while (i <= n) { 19 | fenTree[i] += val; 20 | i += i & (-i); 21 | } 22 | } 23 | 24 | /* A function which will return the cumulative sum from index 1 to index i*/ 25 | public int query(int i) { 26 | // As index starts from 0, increment the index by 1 27 | i += 1; 28 | int cumSum = 0; 29 | while (i > 0) { 30 | cumSum += fenTree[i]; 31 | i -= i & (-i); 32 | } 33 | return cumSum; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/nodes/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.nodes; 2 | 3 | /** 4 | * Base class for any node implementation which contains a generic type 5 | * variable. 6 | * 7 | * All known subclasses: {@link TreeNode}, {@link SimpleNode}. 8 | * 9 | * @param The type of the data held in the Node. 10 | * 11 | * @author aitorfi 12 | */ 13 | public abstract class Node { 14 | 15 | /** 16 | * Generic type data stored in the Node. 17 | */ 18 | private E data; 19 | 20 | /** 21 | * Empty constructor. 22 | */ 23 | public Node() { 24 | } 25 | 26 | /** 27 | * Initializes the Nodes' data. 28 | * 29 | * @param data Value to which data will be initialized. 30 | */ 31 | public Node(E data) { 32 | this.data = data; 33 | } 34 | 35 | public E getData() { 36 | return data; 37 | } 38 | 39 | public void setData(E data) { 40 | this.data = data; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.searches; 2 | 3 | /** 4 | * The common interface of most searching algorithms that search in matrixes. 5 | * 6 | * @author Aitor Fidalgo (https://github.com/aitorfi) 7 | */ 8 | public interface MatrixSearchAlgorithm { 9 | /** 10 | * @param key is an element which should be found 11 | * @param matrix is a matrix where the element should be found 12 | * @param Comparable type 13 | * @return array containing the first found coordinates of the element 14 | */ 15 | > int[] find(T[][] matrix, T key); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.searches; 2 | 3 | /** 4 | * The common interface of most searching algorithms 5 | * 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | */ 8 | public interface SearchAlgorithm { 9 | /** 10 | * @param key is an element which should be found 11 | * @param array is an array where the element should be found 12 | * @param Comparable type 13 | * @return first found index of the element 14 | */ 15 | > int find(T[] array, T key); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /* A DynamicProgramming solution for Climbing Stairs' problem Returns the 4 | distinct ways can you climb to the staircase by either climbing 1 or 2 steps. 5 | 6 | Link : https://medium.com/analytics-vidhya/leetcode-q70-climbing-stairs-easy-444a4aae54e8 7 | */ 8 | public final class ClimbingStairs { 9 | private ClimbingStairs() { 10 | } 11 | 12 | public static int numberOfWays(int n) { 13 | 14 | if (n == 1 || n == 0) { 15 | return n; 16 | } 17 | int prev = 1; 18 | int curr = 1; 19 | 20 | int next; 21 | 22 | for (int i = 2; i <= n; i++) { 23 | next = curr + prev; 24 | prev = curr; 25 | 26 | curr = next; 27 | } 28 | 29 | return curr; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * @author Siddhant Swarup Mallick 5 | * Program description - To find the New Man Shanks Prime. 6 | * Wikipedia 7 | */ 8 | public final class NewManShanksPrime { 9 | private NewManShanksPrime() { 10 | } 11 | 12 | public static boolean nthManShanksPrime(int n, int expectedAnswer) { 13 | int[] a = new int[n + 1]; 14 | // array of n+1 size is initialized 15 | a[0] = 1; 16 | a[1] = 1; 17 | // The 0th and 1st index position values are fixed. They are initialized as 1 18 | for (int i = 2; i <= n; i++) { 19 | a[i] = 2 * a[i - 1] + a[i - 2]; 20 | } 21 | // The loop is continued till n 22 | return a[n] == expectedAnswer; 23 | // returns true if calculated answer matches with expected answer 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | public final class SumOfSubset { 4 | private SumOfSubset() { 5 | } 6 | 7 | public static boolean subsetSum(int[] arr, int num, int key) { 8 | if (key == 0) { 9 | return true; 10 | } 11 | if (num < 0 || key < 0) { 12 | return false; 13 | } 14 | 15 | boolean include = subsetSum(arr, num - 1, key - arr[num]); 16 | boolean exclude = subsetSum(arr, num - 1, key); 17 | 18 | return include || exclude; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * The {@code Tribonacci} class provides a method to compute the n-th number in the Tribonacci sequence. 5 | * N-th Tribonacci Number - https://leetcode.com/problems/n-th-tribonacci-number/description/ 6 | */ 7 | public final class Tribonacci { 8 | private Tribonacci() { 9 | } 10 | 11 | /** 12 | * Computes the n-th Tribonacci number. 13 | * 14 | * @param n the index of the Tribonacci number to compute 15 | * @return the n-th Tribonacci number 16 | */ 17 | public static int compute(int n) { 18 | if (n == 0) { 19 | return 0; 20 | } 21 | if (n == 1 || n == 2) { 22 | return 1; 23 | } 24 | 25 | int first = 0; 26 | int second = 1; 27 | int third = 1; 28 | 29 | for (int i = 3; i <= n; i++) { 30 | int next = first + second + third; 31 | first = second; 32 | second = third; 33 | third = next; 34 | } 35 | 36 | return third; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class AbsoluteMax { 4 | private AbsoluteMax() { 5 | } 6 | 7 | /** 8 | * Finds the absolute maximum value among the given numbers. 9 | * 10 | * @param numbers The numbers to compare. 11 | * @return The absolute maximum value. 12 | * @throws IllegalArgumentException If the input array is empty or null. 13 | */ 14 | public static int getMaxValue(int... numbers) { 15 | if (numbers == null || numbers.length == 0) { 16 | throw new IllegalArgumentException("Numbers array cannot be empty or null"); 17 | } 18 | int absMax = numbers[0]; 19 | for (int i = 1; i < numbers.length; i++) { 20 | if (Math.abs(numbers[i]) > Math.abs(absMax)) { 21 | absMax = numbers[i]; 22 | } 23 | } 24 | return absMax; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | public final class AbsoluteMin { 6 | private AbsoluteMin() { 7 | } 8 | 9 | /** 10 | * Compares the numbers given as arguments to get the absolute min value. 11 | * 12 | * @param numbers The numbers to compare 13 | * @return The absolute min value 14 | */ 15 | public static int getMinValue(int... numbers) { 16 | if (numbers.length == 0) { 17 | throw new IllegalArgumentException("Numbers array cannot be empty"); 18 | } 19 | 20 | var absMinWrapper = new Object() { int value = numbers[0]; }; 21 | 22 | Arrays.stream(numbers).skip(1).filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)).forEach(number -> absMinWrapper.value = number); 23 | 24 | return absMinWrapper.value; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class AbsoluteValue { 4 | private AbsoluteValue() { 5 | } 6 | 7 | /** 8 | * Returns the absolute value of a number. 9 | * 10 | * @param number The number to be transformed 11 | * @return The absolute value of the {@code number} 12 | */ 13 | public static int getAbsValue(int number) { 14 | return number < 0 ? -number : number; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/BinaryPow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class BinaryPow { 4 | private BinaryPow() { 5 | } 6 | 7 | /** 8 | * Calculate a^p using binary exponentiation 9 | * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) 10 | * 11 | * @param a the base for exponentiation 12 | * @param p the exponent - must be greater than 0 13 | * @return a^p 14 | */ 15 | public static int binPow(int a, int p) { 16 | int res = 1; 17 | while (p > 0) { 18 | if ((p & 1) == 1) { 19 | res = res * a; 20 | } 21 | a = a * a; 22 | p >>>= 1; 23 | } 24 | return res; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Ceil.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class Ceil { 4 | private Ceil() { 5 | } 6 | 7 | /** 8 | * Returns the smallest (closest to negative infinity) 9 | * 10 | * @param number the number 11 | * @return the smallest (closest to negative infinity) of given 12 | * {@code number} 13 | */ 14 | public static double ceil(double number) { 15 | if (number - (int) number == 0) { 16 | return number; 17 | } else if (number - (int) number > 0) { 18 | return (int) (number + 1); 19 | } else { 20 | return (int) number; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Factorial.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class Factorial { 4 | private Factorial() { 5 | } 6 | 7 | /** 8 | * Calculate factorial N using iteration 9 | * 10 | * @param n the number 11 | * @return the factorial of {@code n} 12 | */ 13 | public static long factorial(int n) { 14 | if (n < 0) { 15 | throw new IllegalArgumentException("Input number cannot be negative"); 16 | } 17 | long factorial = 1; 18 | for (int i = 1; i <= n; ++i) { 19 | factorial *= i; 20 | } 21 | return factorial; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FactorialRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class FactorialRecursion { 4 | private FactorialRecursion() { 5 | } 6 | /** 7 | * Recursive FactorialRecursion Method 8 | * 9 | * @param n The number to factorial 10 | * @return The factorial of the number 11 | */ 12 | public static long factorial(int n) { 13 | if (n < 0) { 14 | throw new IllegalArgumentException("number is negative"); 15 | } 16 | return n == 0 || n == 1 ? 1 : n * factorial(n - 1); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class FindMax { 4 | private FindMax() { 5 | } 6 | 7 | /** 8 | * @brief finds the maximum value stored in the input array 9 | * 10 | * @param array the input array 11 | * @exception IllegalArgumentException input array is empty 12 | * @return the maximum value stored in the input array 13 | */ 14 | public static int findMax(final int[] array) { 15 | int n = array.length; 16 | if (n == 0) { 17 | throw new IllegalArgumentException("Array must be non-empty."); 18 | } 19 | int max = array[0]; 20 | for (int i = 1; i < n; i++) { 21 | if (array[i] > max) { 22 | max = array[i]; 23 | } 24 | } 25 | return max; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class FindMin { 4 | private FindMin() { 5 | } 6 | 7 | /** 8 | * @brief finds the minimum value stored in the input array 9 | * 10 | * @param array the input array 11 | * @exception IllegalArgumentException input array is empty 12 | * @return the mimum value stored in the input array 13 | */ 14 | public static int findMin(final int[] array) { 15 | if (array.length == 0) { 16 | throw new IllegalArgumentException("Array must be non-empty."); 17 | } 18 | int min = array[0]; 19 | for (int i = 1; i < array.length; i++) { 20 | if (array[i] < min) { 21 | min = array[i]; 22 | } 23 | } 24 | return min; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Floor.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class Floor { 4 | 5 | private Floor() { 6 | } 7 | 8 | /** 9 | * Returns the largest (closest to positive infinity) 10 | * 11 | * @param number the number 12 | * @return the largest (closest to positive infinity) of given 13 | * {@code number} 14 | */ 15 | public static double floor(double number) { 16 | if (number - (int) number == 0) { 17 | return number; 18 | } else if (number - (int) number > 0) { 19 | return (int) number; 20 | } else { 21 | return (int) number - 1; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FrizzyNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * @author Siddhant Swarup Mallick 5 | * Program description - To find the FrizzyNumber 6 | */ 7 | public final class FrizzyNumber { 8 | private FrizzyNumber() { 9 | } 10 | 11 | /** 12 | * Returns the n-th number that is a sum of powers 13 | * of the given base. 14 | * Example: base = 3 and n = 4 15 | * Ascending order of sums of powers of 3 = 16 | * 3^0 = 1, 3^1 = 3, 3^1 + 3^0 = 4, 3^2 + 3^0 = 9 17 | * Ans = 9 18 | * 19 | * @param base The base whose n-th sum of powers is required 20 | * @param n Index from ascending order of sum of powers of base 21 | * @return n-th sum of powers of base 22 | */ 23 | public static double getNthFrizzy(int base, int n) { 24 | double final1 = 0.0; 25 | int i = 0; 26 | do { 27 | final1 += Math.pow(base, i++) * (n % 2); 28 | } while ((n /= 2) > 0); 29 | return final1; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GCDRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * @author https://github.com/shellhub/ 5 | */ 6 | public final class GCDRecursion { 7 | private GCDRecursion() { 8 | } 9 | 10 | public static void main(String[] args) { 11 | System.out.println(gcd(20, 15)); 12 | /* output: 5 */ 13 | System.out.println(gcd(10, 8)); 14 | /* output: 2 */ 15 | System.out.println(gcd(gcd(10, 5), gcd(5, 10))); 16 | /* output: 5 */ 17 | } 18 | 19 | /** 20 | * get greatest common divisor 21 | * 22 | * @param a the first number 23 | * @param b the second number 24 | * @return gcd 25 | */ 26 | public static int gcd(int a, int b) { 27 | if (a < 0 || b < 0) { 28 | throw new ArithmeticException(); 29 | } 30 | 31 | if (a == 0 || b == 0) { 32 | return Math.abs(a - b); 33 | } 34 | 35 | if (a % b == 0) { 36 | return b; 37 | } else { 38 | return gcd(b, a % b); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GenericRoot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Algorithm explanation: 5 | * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. 6 | */ 7 | public final class GenericRoot { 8 | private GenericRoot() { 9 | } 10 | 11 | private static int base = 10; 12 | 13 | private static int sumOfDigits(final int n) { 14 | assert n >= 0; 15 | if (n < base) { 16 | return n; 17 | } 18 | return n % base + sumOfDigits(n / base); 19 | } 20 | 21 | public static int genericRoot(final int n) { 22 | if (n < 0) { 23 | return genericRoot(-n); 24 | } 25 | if (n > base) { 26 | return genericRoot(sumOfDigits(n)); 27 | } 28 | return n; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/LeonardoNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Leonardo_number 5 | */ 6 | public final class LeonardoNumber { 7 | private LeonardoNumber() { 8 | } 9 | 10 | /** 11 | * Calculate nth Leonardo Number (1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, ...) 12 | * 13 | * @param n the index of Leonardo Number to calculate 14 | * @return nth number of Leonardo sequences 15 | */ 16 | public static int leonardoNumber(int n) { 17 | if (n < 0) { 18 | throw new ArithmeticException(); 19 | } 20 | if (n == 0 || n == 1) { 21 | return 1; 22 | } 23 | return (leonardoNumber(n - 1) + leonardoNumber(n - 2) + 1); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/LucasSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Lucas_number 5 | */ 6 | public final class LucasSeries { 7 | private LucasSeries() { 8 | } 9 | 10 | /** 11 | * Calculate nth number of Lucas Series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 12 | * 123, ....) using recursion 13 | * 14 | * @param n nth 15 | * @return nth number of Lucas Series 16 | */ 17 | public static int lucasSeries(int n) { 18 | return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); 19 | } 20 | 21 | /** 22 | * Calculate nth number of Lucas Series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 23 | * 123, ....) using iteration 24 | * 25 | * @param n nth 26 | * @return nth number of lucas series 27 | */ 28 | public static int lucasSeriesIteration(int n) { 29 | int previous = 2; 30 | int current = 1; 31 | for (int i = 1; i < n; i++) { 32 | int next = previous + current; 33 | previous = current; 34 | current = next; 35 | } 36 | return previous; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MaxValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class MaxValue { 4 | private MaxValue() { 5 | } 6 | /** 7 | * Returns the greater of two {@code int} values. That is, the result is the 8 | * argument closer to the value of {@link Integer#MAX_VALUE}. If the 9 | * arguments have the same value, the result is that same value. 10 | * 11 | * @param a an argument. 12 | * @param b another argument. 13 | * @return the larger of {@code a} and {@code b}. 14 | */ 15 | public static int max(int a, int b) { 16 | return a >= b ? a : b; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Median.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Wikipedia: https://en.wikipedia.org/wiki/Median 7 | */ 8 | public final class Median { 9 | private Median() { 10 | } 11 | 12 | /** 13 | * Calculate average median 14 | * @param values sorted numbers to find median of 15 | * @return median of given {@code values} 16 | */ 17 | public static double median(int[] values) { 18 | Arrays.sort(values); 19 | int length = values.length; 20 | return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2]; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MinValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class MinValue { 4 | private MinValue() { 5 | } 6 | /** 7 | * Returns the smaller of two {@code int} values. That is, the result the 8 | * argument closer to the value of {@link Integer#MIN_VALUE}. If the 9 | * arguments have the same value, the result is that same value. 10 | * 11 | * @param a an argument. 12 | * @param b another argument. 13 | * @return the smaller of {@code a} and {@code b}. 14 | */ 15 | public static int min(int a, int b) { 16 | return a <= b ? a : b; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class PalindromeNumber { 4 | private PalindromeNumber() { 5 | } 6 | /** 7 | * Check if {@code n} is palindrome number or not 8 | * 9 | * @param number the number 10 | * @return {@code true} if {@code n} is palindrome number, otherwise 11 | * {@code false} 12 | */ 13 | public static boolean isPalindrome(int number) { 14 | if (number < 0) { 15 | throw new IllegalArgumentException("Input parameter must not be negative!"); 16 | } 17 | int numberCopy = number; 18 | int reverseNumber = 0; 19 | while (numberCopy != 0) { 20 | int remainder = numberCopy % 10; 21 | reverseNumber = reverseNumber * 10 + remainder; 22 | numberCopy /= 10; 23 | } 24 | return number == reverseNumber; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectCube.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Cube_(algebra) 5 | */ 6 | public final class PerfectCube { 7 | private PerfectCube() { 8 | } 9 | 10 | /** 11 | * Check if a number is perfect cube or not 12 | * 13 | * @param number number to check 14 | * @return {@code true} if {@code number} is perfect cube, otherwise 15 | * {@code false} 16 | */ 17 | public static boolean isPerfectCube(int number) { 18 | number = Math.abs(number); // converting negative number to positive number 19 | int a = (int) Math.pow(number, 1.0 / 3); 20 | return a * a * a == number; 21 | } 22 | 23 | /** 24 | * Check if a number is perfect cube or not by using Math.cbrt function 25 | * 26 | * @param number number to check 27 | * @return {@code true} if {@code number} is perfect cube, otherwise 28 | * {@code false} 29 | */ 30 | public static boolean isPerfectCubeMathCbrt(int number) { 31 | double cubeRoot = Math.cbrt(number); 32 | return cubeRoot == (int) cubeRoot; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectSquare.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Perfect_square 5 | */ 6 | public final class PerfectSquare { 7 | private PerfectSquare() { 8 | } 9 | 10 | /** 11 | * Check if a number is perfect square number 12 | * 13 | * @param number the number to be checked 14 | * @return true if {@code number} is perfect square, otherwise 15 | * false 16 | */ 17 | public static boolean isPerfectSquare(final int number) { 18 | final int sqrt = (int) Math.sqrt(number); 19 | return sqrt * sqrt == number; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Pow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | // POWER (exponentials) Examples (a^b) 4 | public final class Pow { 5 | private Pow() { 6 | } 7 | 8 | public static void main(String[] args) { 9 | assert pow(2, 0) == Math.pow(2, 0); // == 1 10 | assert pow(0, 2) == Math.pow(0, 2); // == 0 11 | assert pow(2, 10) == Math.pow(2, 10); // == 1024 12 | assert pow(10, 2) == Math.pow(10, 2); // == 100 13 | } 14 | 15 | /** 16 | * Returns the value of the first argument raised to the power of the second 17 | * argument 18 | * 19 | * @param a the base. 20 | * @param b the exponent. 21 | * @return the value {@code a}{@code b}. 22 | */ 23 | public static long pow(int a, int b) { 24 | long result = 1; 25 | for (int i = 1; i <= b; i++) { 26 | result *= a; 27 | } 28 | return result; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PowerOfTwoOrNot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * A utility to check if a given number is power of two or not. For example 8,16 5 | * etc. 6 | */ 7 | public final class PowerOfTwoOrNot { 8 | private PowerOfTwoOrNot() { 9 | } 10 | 11 | /** 12 | * Checks whether given number is power of two or not. 13 | * 14 | * @param number the number to check 15 | * @return {@code true} if given number is power of two, otherwise 16 | * {@code false} 17 | */ 18 | public static boolean checkIfPowerOfTwoOrNot(final int number) { 19 | return number != 0 && ((number & (number - 1)) == 0); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * calculate Power using Recursion 5 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 6 | */ 7 | 8 | public final class PowerUsingRecursion { 9 | private PowerUsingRecursion() { 10 | } 11 | 12 | public static double power(double base, int exponent) { 13 | // Base case: anything raised to the power of 0 is 1 14 | if (exponent == 0) { 15 | return 1; 16 | } 17 | 18 | // Recursive case: base ^ exponent = base * base ^ (exponent - 1) 19 | // Recurse with a smaller exponent and multiply with base 20 | return base * power(base, exponent - 1); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PrimeFactorization.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Authors: 5 | * (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi) 6 | * (2) Akshay Dubey (https://github.com/itsAkshayDubey) 7 | */ 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public final class PrimeFactorization { 13 | private PrimeFactorization() { 14 | } 15 | 16 | public static List pfactors(int n) { 17 | List primeFactors = new ArrayList<>(); 18 | 19 | if (n == 0) { 20 | return primeFactors; 21 | } 22 | 23 | while (n % 2 == 0) { 24 | primeFactors.add(2); 25 | n /= 2; 26 | } 27 | 28 | for (int i = 3; i <= Math.sqrt(n); i += 2) { 29 | while (n % i == 0) { 30 | primeFactors.add(i); 31 | n /= i; 32 | } 33 | } 34 | 35 | if (n > 2) { 36 | primeFactors.add(n); 37 | } 38 | return primeFactors; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/ReverseNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * @brief utility class reversing numbers 5 | */ 6 | public final class ReverseNumber { 7 | private ReverseNumber() { 8 | } 9 | 10 | /** 11 | * @brief reverses the input number 12 | * @param number the input number 13 | * @exception IllegalArgumentException number is negative 14 | * @return the number created by reversing the order of digits of the input number 15 | */ 16 | public static int reverseNumber(int number) { 17 | if (number < 0) { 18 | throw new IllegalArgumentException("number must be nonnegative."); 19 | } 20 | 21 | int result = 0; 22 | while (number > 0) { 23 | result *= 10; 24 | result += number % 10; 25 | number /= 10; 26 | } 27 | return result; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class SquareRootWithBabylonianMethod { 4 | private SquareRootWithBabylonianMethod() { 5 | } 6 | 7 | /** 8 | * get the value, return the square root 9 | * 10 | * @param num contains elements 11 | * @return the square root of num 12 | */ 13 | public static float squareRoot(float num) { 14 | float a = num; 15 | float b = 1; 16 | double e = 0.000001; 17 | while (a - b > e) { 18 | a = (a + b) / 2; 19 | b = num / a; 20 | } 21 | return a; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/StandardDeviation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class StandardDeviation { 4 | private StandardDeviation() { 5 | } 6 | 7 | public static double stdDev(double[] data) { 8 | double variance = 0; 9 | double avg = 0; 10 | for (int i = 0; i < data.length; i++) { 11 | avg += data[i]; 12 | } 13 | avg /= data.length; 14 | for (int j = 0; j < data.length; j++) { 15 | variance += Math.pow((data[j] - avg), 2); 16 | } 17 | variance /= data.length; 18 | return Math.sqrt(variance); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/StandardScore.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public final class StandardScore { 4 | private StandardScore() { 5 | } 6 | 7 | public static double zScore(double num, double mean, double stdDev) { 8 | return (num - mean) / stdDev; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class SumWithoutArithmeticOperators { 4 | 5 | /** 6 | * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). 7 | * All the integers associated are unsigned 32-bit integers 8 | *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator 9 | *@param a - It is the first number 10 | *@param b - It is the second number 11 | *@return returns an integer which is the sum of the first and second number 12 | */ 13 | 14 | public int getSum(int a, int b) { 15 | if (b == 0) { 16 | return a; 17 | } 18 | int sum = a ^ b; 19 | int carry = (a & b) << 1; 20 | return getSum(sum, carry); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | 7 | /** 8 | * Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116) 9 | * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 10 | */ 11 | 12 | public final class MedianOfMatrix { 13 | private MedianOfMatrix() { 14 | } 15 | 16 | public static int median(List> matrix) { 17 | // Flatten the matrix into a 1D list 18 | List linear = new ArrayList<>(); 19 | for (List row : matrix) { 20 | linear.addAll(row); 21 | } 22 | 23 | // Sort the 1D list 24 | Collections.sort(linear); 25 | 26 | // Calculate the middle index 27 | int mid = (0 + linear.size() - 1) / 2; 28 | 29 | // Return the median 30 | return linear.get(mid); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArrayByte.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | public final class MedianOfRunningArrayByte extends MedianOfRunningArray { 4 | @Override 5 | public Byte calculateAverage(final Byte a, final Byte b) { 6 | return (byte) ((a + b) / 2); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArrayDouble.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | public final class MedianOfRunningArrayDouble extends MedianOfRunningArray { 4 | @Override 5 | public Double calculateAverage(final Double a, final Double b) { 6 | return (a + b) / 2.0d; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArrayFloat.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | public final class MedianOfRunningArrayFloat extends MedianOfRunningArray { 4 | @Override 5 | public Float calculateAverage(final Float a, final Float b) { 6 | return (a + b) / 2.0f; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | public final class MedianOfRunningArrayInteger extends MedianOfRunningArray { 4 | @Override 5 | public Integer calculateAverage(final Integer a, final Integer b) { 6 | return (a + b) / 2; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | public final class MedianOfRunningArrayLong extends MedianOfRunningArray { 4 | @Override 5 | public Long calculateAverage(final Long a, final Long b) { 6 | return (a + b) / 2L; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import com.thealgorithms.datastructures.lists.SinglyLinkedList; 4 | import java.util.Stack; 5 | 6 | /** 7 | * A simple way of knowing if a singly linked list is palindrome is to push all 8 | * the values into a Stack and then compare the list to popped vales from the 9 | * Stack. 10 | * 11 | * See more: 12 | * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ 13 | */ 14 | public final class PalindromeSinglyLinkedList { 15 | private PalindromeSinglyLinkedList() { 16 | } 17 | 18 | public static boolean isPalindrome(final SinglyLinkedList linkedList) { 19 | Stack linkedListValues = new Stack<>(); 20 | 21 | for (final var x : linkedList) { 22 | linkedListValues.push(x); 23 | } 24 | 25 | for (final var x : linkedList) { 26 | if (x != linkedListValues.pop()) { 27 | return false; 28 | } 29 | } 30 | 31 | return true; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/ArrayLeftRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /* 4 | * A left rotation operation on an array 5 | * shifts each of the array's elements 6 | * given integer n unit to the left. 7 | * 8 | * @author sangin-lee 9 | */ 10 | 11 | public final class ArrayLeftRotation { 12 | private ArrayLeftRotation() { 13 | } 14 | 15 | /* 16 | * Returns the result of left rotation of given array arr and integer n 17 | * 18 | * @param arr : int[] given array 19 | * 20 | * @param n : int given integer 21 | * 22 | * @return : int[] result of left rotation 23 | */ 24 | public static int[] rotateLeft(int[] arr, int n) { 25 | int size = arr.length; 26 | int[] dst = new int[size]; 27 | n = n % size; 28 | for (int i = 0; i < size; i++) { 29 | dst[i] = arr[n]; 30 | n = (n + 1) % size; 31 | } 32 | return dst; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CRC16.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Generates a crc16 checksum for a given string 5 | */ 6 | public final class CRC16 { 7 | private CRC16() { 8 | } 9 | 10 | public static void main(String[] args) { 11 | System.out.println(crc16("Hello World!")); 12 | } 13 | 14 | public static String crc16(String message) { 15 | int crc = 0xFFFF; // initial value 16 | int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) 17 | byte[] bytes = message.getBytes(); 18 | 19 | for (byte b : bytes) { 20 | for (int i = 0; i < 8; i++) { 21 | boolean bit = ((b >> (7 - i) & 1) == 1); 22 | boolean c15 = ((crc >> 15 & 1) == 1); 23 | crc <<= 1; 24 | if (c15 ^ bit) { 25 | crc ^= polynomial; 26 | } 27 | } 28 | } 29 | crc &= 0xffff; 30 | return Integer.toHexString(crc).toUpperCase(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CRC32.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.BitSet; 4 | 5 | /** 6 | * Generates a crc32 checksum for a given string or byte array 7 | */ 8 | public final class CRC32 { 9 | private CRC32() { 10 | } 11 | 12 | public static void main(String[] args) { 13 | System.out.println(Integer.toHexString(crc32("Hello World"))); 14 | } 15 | 16 | public static int crc32(String str) { 17 | return crc32(str.getBytes()); 18 | } 19 | 20 | public static int crc32(byte[] data) { 21 | BitSet bitSet = BitSet.valueOf(data); 22 | int crc32 = 0xFFFFFFFF; // initial value 23 | for (int i = 0; i < data.length * 8; i++) { 24 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { 25 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial 26 | } else { 27 | crc32 = (crc32 << 1); 28 | } 29 | } 30 | crc32 = Integer.reverse(crc32); // result reflect 31 | return crc32 ^ 0xFFFFFFFF; // final xor value 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | public final class CountChar { 4 | private CountChar() { 5 | } 6 | 7 | /** 8 | * Count non space character in string 9 | * 10 | * @param str String to count the characters 11 | * @return number of character in the specified string 12 | */ 13 | 14 | public static int countCharacters(String str) { 15 | return str.replaceAll("\\s", "").length(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FibbonaciSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Fibonacci sequence, and characterized by the fact that every number after the 7 | * first two is the sum of the two preceding ones. 8 | * 9 | *

10 | * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... 11 | * 12 | *

13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number 14 | * 15 | * Problem Statement: print all Fibonacci numbers that are smaller than your 16 | * given input N 17 | */ 18 | public final class FibbonaciSeries { 19 | private FibbonaciSeries() { 20 | } 21 | 22 | public static void main(String[] args) { 23 | // Get input from the user 24 | Scanner scan = new Scanner(System.in); 25 | int n = scan.nextInt(); 26 | int first = 0; 27 | int second = 1; 28 | scan.close(); 29 | while (first <= n) { 30 | // print first fibo 0 then add second fibo into it while updating second as well 31 | System.out.println(first); 32 | int next = first + second; 33 | first = second; 34 | second = next; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | final class FloydTriangle { 6 | private FloydTriangle() { 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner sc = new Scanner(System.in); 11 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 12 | int r = sc.nextInt(); 13 | int n = 0; 14 | sc.close(); 15 | for (int i = 0; i < r; i++) { 16 | for (int j = 0; j <= i; j++) { 17 | System.out.print(++n + " "); 18 | } 19 | System.out.println(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/HappyNumbersSeq.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | public final class HappyNumbersSeq { 9 | private HappyNumbersSeq() { 10 | } 11 | 12 | private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); 13 | 14 | public static void main(String[] args) { 15 | Scanner in = new Scanner(System.in); 16 | System.out.print("Enter number: "); 17 | int n = in.nextInt(); 18 | while (n != 1 && !isSad(n)) { 19 | System.out.print(n + " "); 20 | n = sumSquares(n); 21 | } 22 | String res = n == 1 ? "1 Happy number" : "Sad number"; 23 | System.out.println(res); 24 | in.close(); 25 | } 26 | 27 | private static int sumSquares(int n) { 28 | int s = 0; 29 | for (; n > 0; n /= 10) { 30 | int r = n % 10; 31 | s += r * r; 32 | } 33 | return s; 34 | } 35 | 36 | private static boolean isSad(int n) { 37 | return CYCLE_NUMS.contains(n); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | final class Krishnamurthy { 6 | private Krishnamurthy() { 7 | } 8 | 9 | static int fact(int n) { 10 | int i; 11 | int p = 1; 12 | for (i = n; i >= 1; i--) { 13 | p = p * i; 14 | } 15 | return p; 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner sc = new Scanner(System.in); 20 | int a; 21 | int b; 22 | int s = 0; 23 | System.out.print("Enter the number : "); 24 | a = sc.nextInt(); 25 | int n = a; 26 | while (a > 0) { 27 | b = a % 10; 28 | s = s + fact(b); 29 | a = a / 10; 30 | } 31 | if (s == n) { 32 | System.out.print(n + " is a krishnamurthy number"); 33 | } else { 34 | System.out.print(n + " is not a krishnamurthy number"); 35 | } 36 | sc.close(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/RootPrecision.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public final class RootPrecision { 6 | private RootPrecision() { 7 | } 8 | 9 | public static void main(String[] args) { 10 | // take input 11 | Scanner scn = new Scanner(System.in); 12 | 13 | // n is the input number 14 | int n = scn.nextInt(); 15 | 16 | // p is precision value for eg - p is 3 in 2.564 and 5 in 3.80870. 17 | int p = scn.nextInt(); 18 | System.out.println(squareRoot(n, p)); 19 | 20 | scn.close(); 21 | } 22 | 23 | public static double squareRoot(int n, int p) { 24 | // rv means return value 25 | double rv; 26 | 27 | double root = Math.pow(n, 0.5); 28 | 29 | // calculate precision to power of 10 and then multiply it with root value. 30 | int precision = (int) Math.pow(10, p); 31 | root = root * precision; 32 | /*typecast it into integer then divide by precision and again typecast into double 33 | so as to have decimal points upto p precision */ 34 | 35 | rv = (int) root; 36 | return rv / precision; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/cn/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others.cn; 2 | 3 | public final class HammingDistance { 4 | private HammingDistance() { 5 | } 6 | 7 | private static void checkChar(char inChar) { 8 | if (inChar != '0' && inChar != '1') { 9 | throw new IllegalArgumentException("Input must be a binary string."); 10 | } 11 | } 12 | 13 | public static int compute(char charA, char charB) { 14 | checkChar(charA); 15 | checkChar(charB); 16 | return charA == charB ? 0 : 1; 17 | } 18 | 19 | public static int compute(String bitsStrA, String bitsStrB) { 20 | if (bitsStrA.length() != bitsStrB.length()) { 21 | throw new IllegalArgumentException("Input strings must have the same length."); 22 | } 23 | 24 | int totalErrorBitCount = 0; 25 | 26 | for (int i = 0; i < bitsStrA.length(); i++) { 27 | totalErrorBitCount += compute(bitsStrA.charAt(i), bitsStrB.charAt(i)); 28 | } 29 | 30 | return totalErrorBitCount; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.datastructures.Node; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | /** 9 | * @author: caos321 10 | * @date: 31 October 2021 (Sunday) 11 | * @wiki: https://en.wikipedia.org/wiki/Depth-first_search 12 | */ 13 | public class DepthFirstSearch { 14 | 15 | private final List visited = new ArrayList<>(); 16 | 17 | public Optional> recursiveSearch(final Node node, final Integer value) { 18 | if (node == null) { 19 | return Optional.empty(); 20 | } 21 | visited.add(node.getValue()); 22 | if (node.getValue().equals(value)) { 23 | return Optional.of(node); 24 | } 25 | 26 | return node.getChildren().stream().map(v -> recursiveSearch(v, value)).flatMap(Optional::stream).findAny(); 27 | } 28 | 29 | public List getVisited() { 30 | return visited; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | public class SearchInARowAndColWiseSortedMatrix { 4 | /** 5 | * Search a key in row and column wise sorted matrix 6 | * 7 | * @param matrix matrix to be searched 8 | * @param value Key being searched for 9 | * @author Sadiul Hakim : https://github.com/sadiul-hakim 10 | */ 11 | 12 | public int[] search(int[][] matrix, int value) { 13 | int n = matrix.length; 14 | // This variable iterates over rows 15 | int i = 0; 16 | // This variable iterates over columns 17 | int j = n - 1; 18 | int[] result = {-1, -1}; 19 | 20 | while (i < n && j >= 0) { 21 | if (matrix[i][j] == value) { 22 | result[0] = i; 23 | result[1] = j; 24 | return result; 25 | } 26 | if (value > matrix[i][j]) { 27 | i++; 28 | } else { 29 | j--; 30 | } 31 | } 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | public final class SortOrderAgnosticBinarySearch { 3 | private SortOrderAgnosticBinarySearch() { 4 | } 5 | public static int find(int[] arr, int key) { 6 | int start = 0; 7 | int end = arr.length - 1; 8 | boolean arrDescending = arr[start] > arr[end]; // checking for Array is in ascending order or descending order. 9 | while (start <= end) { 10 | int mid = end - start / 2; 11 | if (arr[mid] == key) { 12 | return mid; 13 | } 14 | if (arrDescending) { // boolean is true then our array is in descending order 15 | if (key < arr[mid]) { 16 | start = mid + 1; 17 | } else { 18 | end = mid - 1; 19 | } 20 | } else { // otherwise our array is in ascending order 21 | if (key > arr[mid]) { 22 | start = mid + 1; 23 | } else { 24 | end = mid - 1; 25 | } 26 | } 27 | } 28 | return -1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | * @author Podshivalov Nikita (https://github.com/nikitap492) 6 | * @see SortAlgorithm 7 | */ 8 | class BubbleSort implements SortAlgorithm { 9 | 10 | /** 11 | * Implements generic bubble sort algorithm. 12 | * 13 | * @param array the array to be sorted. 14 | * @param the type of elements in the array. 15 | * @return the sorted array. 16 | */ 17 | @Override 18 | public > T[] sort(T[] array) { 19 | for (int i = 1, size = array.length; i < size; ++i) { 20 | boolean swapped = false; 21 | for (int j = 0; j < size - i; ++j) { 22 | if (SortUtils.greater(array[j], array[j + 1])) { 23 | SortUtils.swap(array, j, j + 1); 24 | swapped = true; 25 | } 26 | } 27 | if (!swapped) { 28 | break; 29 | } 30 | } 31 | return array; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * BubbleSort algorithm implemented using recursion 5 | */ 6 | public class BubbleSortRecursive implements SortAlgorithm { 7 | /** 8 | * @param array - an array should be sorted 9 | * @return sorted array 10 | */ 11 | @Override 12 | public > T[] sort(T[] array) { 13 | bubbleSort(array, array.length); 14 | return array; 15 | } 16 | 17 | /** 18 | * BubbleSort algorithm implements using recursion 19 | * 20 | * @param array array contains elements 21 | * @param len length of given array 22 | */ 23 | private static > void bubbleSort(T[] array, int len) { 24 | boolean swapped = false; 25 | for (int i = 0; i < len - 1; ++i) { 26 | if (SortUtils.greater(array[i], array[i + 1])) { 27 | SortUtils.swap(array, i, i + 1); 28 | swapped = true; 29 | } 30 | } 31 | if (swapped) { 32 | bubbleSort(array, len - 1); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SelectionSort implements SortAlgorithm { 4 | /** 5 | * Sorts an array of comparable elements in increasing order using the selection sort algorithm. 6 | * 7 | * @param array the array to be sorted 8 | * @param the class of array elements 9 | * @return the sorted array 10 | */ 11 | @Override 12 | public > T[] sort(T[] array) { 13 | // One by one move the boundary of the unsorted subarray 14 | for (int i = 0; i < array.length - 1; i++) { 15 | 16 | // Swap the remaining minimum element with the current element 17 | SortUtils.swap(array, i, findIndexOfMin(array, i)); 18 | } 19 | return array; 20 | } 21 | 22 | private static > int findIndexOfMin(T[] array, final int start) { 23 | int minIndex = start; 24 | for (int i = start + 1; i < array.length; i++) { 25 | if (array[i].compareTo(array[minIndex]) < 0) { 26 | minIndex = i; 27 | } 28 | } 29 | return minIndex; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SlowSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Amir Hassan (https://github.com/ahsNT) 5 | * @see SortAlgorithm 6 | */ 7 | public class SlowSort implements SortAlgorithm { 8 | 9 | @Override 10 | public > T[] sort(T[] unsortedArray) { 11 | sort(unsortedArray, 0, unsortedArray.length - 1); 12 | return unsortedArray; 13 | } 14 | 15 | private > void sort(T[] array, int i, int j) { 16 | if (SortUtils.greaterOrEqual(i, j)) { 17 | return; 18 | } 19 | final int m = (i + j) >>> 1; 20 | sort(array, i, m); 21 | sort(array, m + 1, j); 22 | if (SortUtils.less(array[j], array[m])) { 23 | SortUtils.swap(array, j, m); 24 | } 25 | sort(array, i, j - 1); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SortAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * The common interface of most sorting algorithms 8 | * 9 | * @author Podshivalov Nikita (https://github.com/nikitap492) 10 | */ 11 | public interface SortAlgorithm { 12 | /** 13 | * Main method arrays sorting algorithms 14 | * 15 | * @param unsorted - an array should be sorted 16 | * @return a sorted array 17 | */ 18 | > T[] sort(T[] unsorted); 19 | 20 | /** 21 | * Auxiliary method for algorithms what wanted to work with lists from JCF 22 | * 23 | * @param unsorted - a list should be sorted 24 | * @return a sorted list 25 | */ 26 | @SuppressWarnings("unchecked") 27 | default> List sort(List unsorted) { 28 | return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public final class CharactersSame { 4 | private CharactersSame() { 5 | } 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | assert isAllCharactersSame(""); 12 | assert !isAllCharactersSame("aab"); 13 | assert isAllCharactersSame("aaa"); 14 | assert isAllCharactersSame("11111"); 15 | } 16 | 17 | /** 18 | * check if all the characters of a string are same 19 | * 20 | * @param s the string to check 21 | * @return {@code true} if all characters of a string are same, otherwise 22 | * {@code false} 23 | */ 24 | public static boolean isAllCharactersSame(String s) { 25 | for (int i = 1, length = s.length(); i < length; ++i) { 26 | if (s.charAt(i) != s.charAt(0)) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Vowel Count is a system whereby character strings are placed in order based 9 | * on the position of the characters in the conventional ordering of an 10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 11 | */ 12 | public final class CheckVowels { 13 | private CheckVowels() { 14 | } 15 | 16 | private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); 17 | 18 | /** 19 | * Check if a string is has vowels or not 20 | * 21 | * @param input a string 22 | * @return {@code true} if given string has vowels, otherwise {@code false} 23 | */ 24 | public static boolean hasVowels(String input) { 25 | if (input == null) { 26 | return false; 27 | } 28 | input = input.toLowerCase(); 29 | for (int i = 0; i < input.length(); i++) { 30 | if (VOWELS.contains(input.charAt(i))) { 31 | return true; 32 | } 33 | } 34 | return false; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /* In information theory, the Hamming distance between two strings of equal length 4 | is the number of positions at which the corresponding symbols are different. 5 | https://en.wikipedia.org/wiki/Hamming_distance 6 | */ 7 | public final class HammingDistance { 8 | private HammingDistance() { 9 | } 10 | 11 | /** 12 | * calculate the hamming distance between two strings of equal length 13 | * 14 | * @param s1 the first string 15 | * @param s2 the second string 16 | * @return {@code int} hamming distance 17 | * @throws Exception 18 | */ 19 | public static int calculateHammingDistance(String s1, String s2) throws Exception { 20 | if (s1.length() != s2.length()) { 21 | throw new Exception("String lengths must be equal"); 22 | } 23 | 24 | int stringLength = s1.length(); 25 | int counter = 0; 26 | 27 | for (int i = 0; i < stringLength; i++) { 28 | if (s1.charAt(i) != s2.charAt(i)) { 29 | counter++; 30 | } 31 | } 32 | return counter; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Lower.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public final class Lower { 4 | private Lower() { 5 | } 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 12 | for (String s : strings) { 13 | assert toLowerCase(s).equals(s.toLowerCase()); 14 | } 15 | } 16 | 17 | /** 18 | * Converts all of the characters in this {@code String} to lower case 19 | * 20 | * @param s the string to convert 21 | * @return the {@code String}, converted to lowercase. 22 | */ 23 | public static String toLowerCase(String s) { 24 | char[] values = s.toCharArray(); 25 | for (int i = 0; i < values.length; ++i) { 26 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { 27 | values[i] = Character.toLowerCase(values[i]); 28 | } 29 | } 30 | return new String(values); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using Recursion 5 | */ 6 | 7 | public final class ReverseStringRecursive { 8 | private ReverseStringRecursive() { 9 | } 10 | /** 11 | * @param str string to be reversed 12 | * @return reversed string 13 | */ 14 | public static String reverse(String str) { 15 | if (str.isEmpty()) { 16 | return str; 17 | } else { 18 | return reverse(str.substring(1)) + str.charAt(0); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/ReverseWordsInString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | import java.util.Collections; 5 | 6 | public final class ReverseWordsInString { 7 | 8 | private ReverseWordsInString() { 9 | } 10 | 11 | /** 12 | * @brief Reverses words in the input string 13 | * @param s the input string 14 | * @return A string created by reversing the order of the words in {@code s} 15 | */ 16 | 17 | public static String reverseWordsInString(final String s) { 18 | var words = s.trim().split("\\s+"); 19 | Collections.reverse(Arrays.asList(words)); 20 | return String.join(" ", words); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Upper.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public final class Upper { 4 | private Upper() { 5 | } 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 12 | for (String s : strings) { 13 | assert toUpperCase(s).equals(s.toUpperCase()); 14 | } 15 | } 16 | 17 | /** 18 | * Converts all of the characters in this {@code String} to upper case 19 | * 20 | * @param s the string to convert 21 | * @return the {@code String}, converted to uppercase. 22 | */ 23 | public static String toUpperCase(String s) { 24 | if (s == null || "".equals(s)) { 25 | return s; 26 | } 27 | char[] values = s.toCharArray(); 28 | for (int i = 0; i < values.length; ++i) { 29 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { 30 | values[i] = Character.toUpperCase(values[i]); 31 | } 32 | } 33 | return new String(values); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/CombinationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import java.util.List; 6 | import java.util.TreeSet; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class CombinationTest { 10 | 11 | @Test 12 | void testNoElement() { 13 | List> result = Combination.combination(new Integer[] {1, 2}, 0); 14 | assertTrue(result == null); 15 | } 16 | 17 | @Test 18 | void testLengthOne() { 19 | List> result = Combination.combination(new Integer[] {1, 2}, 1); 20 | assertTrue(result.get(0).iterator().next() == 1); 21 | assertTrue(result.get(1).iterator().next() == 2); 22 | } 23 | 24 | @Test 25 | void testLengthTwo() { 26 | List> result = Combination.combination(new Integer[] {1, 2}, 2); 27 | Integer[] arr = result.get(0).toArray(new Integer[2]); 28 | assertTrue(arr[0] == 1); 29 | assertTrue(arr[1] == 2); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/PermutationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import org.junit.jupiter.api.Test; 9 | 10 | public class PermutationTest { 11 | 12 | @Test 13 | void testNoElement() { 14 | List result = Permutation.permutation(new Integer[] {}); 15 | assertEquals(result.get(0).length, 0); 16 | } 17 | 18 | @Test 19 | void testSingleElement() { 20 | List result = Permutation.permutation(new Integer[] {1}); 21 | assertEquals(result.get(0)[0], 1); 22 | } 23 | 24 | @Test 25 | void testMultipleElements() { 26 | List result = Permutation.permutation(new Integer[] {1, 2}); 27 | assertTrue(Arrays.equals(result.get(0), new Integer[] {1, 2})); 28 | assertTrue(Arrays.equals(result.get(1), new Integer[] {2, 1})); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/PowerSumTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PowerSumTest { 7 | 8 | @Test 9 | void testNumberZeroAndPowerZero() { 10 | PowerSum powerSum = new PowerSum(); 11 | int result = powerSum.powSum(0, 0); 12 | assertEquals(1, result); 13 | } 14 | 15 | @Test 16 | void testNumberHundredAndPowerTwo() { 17 | PowerSum powerSum = new PowerSum(); 18 | int result = powerSum.powSum(100, 2); 19 | assertEquals(3, result); 20 | } 21 | 22 | @Test 23 | void testNumberHundredAndPowerThree() { 24 | PowerSum powerSum = new PowerSum(); 25 | int result = powerSum.powSum(100, 3); 26 | assertEquals(1, result); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/WordSearchTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class WordSearchTest { 9 | @Test 10 | void test1() { 11 | WordSearch ws = new WordSearch(); 12 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; 13 | String word = "ABCCED"; 14 | assertTrue(ws.exist(board, word)); 15 | } 16 | 17 | @Test 18 | void test2() { 19 | WordSearch ws = new WordSearch(); 20 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; 21 | String word = "SEE"; 22 | assertTrue(ws.exist(board, word)); 23 | } 24 | 25 | @Test 26 | void test3() { 27 | WordSearch ws = new WordSearch(); 28 | char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; 29 | String word = "ABCB"; 30 | Assertions.assertFalse(ws.exist(board, word)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | public class BitSwapTest { 7 | @Test 8 | void testHighestSetBit() { 9 | assertEquals(3, BitSwap.bitSwap(3, 0, 1)); 10 | assertEquals(5, BitSwap.bitSwap(6, 0, 1)); 11 | assertEquals(7, BitSwap.bitSwap(7, 1, 1)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Test case for Index Of Right Most SetBit 9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 10 | */ 11 | 12 | class IndexOfRightMostSetBitTest { 13 | 14 | @Test 15 | void testIndexOfRightMostSetBit() { 16 | assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(40)); 17 | assertEquals(-1, IndexOfRightMostSetBit.indexOfRightMostSetBit(0)); 18 | assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(-40)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/IsEvenTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | class IsEvenTest { 9 | @Test 10 | void testIsEven() { 11 | assertTrue(IsEven.isEven(0)); 12 | assertTrue(IsEven.isEven(2)); 13 | assertTrue(IsEven.isEven(-12)); 14 | assertFalse(IsEven.isEven(21)); 15 | assertFalse(IsEven.isEven(-1)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinderTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Test case for Non Repeating Number Finder 9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 10 | */ 11 | 12 | class NonRepeatingNumberFinderTest { 13 | 14 | @Test 15 | void testNonRepeatingNumberFinder() { 16 | int[] arr = {1, 2, 1, 2, 6}; 17 | assertEquals(6, NonRepeatingNumberFinder.findNonRepeatingNumber(arr)); 18 | int[] arr1 = {1, 2, 1, 2}; 19 | assertEquals(0, NonRepeatingNumberFinder.findNonRepeatingNumber(arr1)); 20 | int[] arr2 = {12}; 21 | assertEquals(12, NonRepeatingNumberFinder.findNonRepeatingNumber(arr2)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/NumbersDifferentSignsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | /** 8 | * test Cases of Numbers Different Signs 9 | * @author Bama Charan Chhandogi 10 | */ 11 | class NumbersDifferentSignsTest { 12 | 13 | @Test 14 | void testDifferentSignsPositiveNegative() { 15 | assertTrue(NumbersDifferentSigns.differentSigns(2, -1)); 16 | } 17 | 18 | @Test 19 | void testDifferentSignsNegativePositive() { 20 | assertTrue(NumbersDifferentSigns.differentSigns(-3, 7)); 21 | } 22 | 23 | @Test 24 | void testSameSignsPositive() { 25 | assertFalse(NumbersDifferentSigns.differentSigns(10, 20)); 26 | } 27 | 28 | @Test 29 | void testSameSignsNegative() { 30 | assertFalse(NumbersDifferentSigns.differentSigns(-5, -8)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/ReverseBitsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class ReverseBitsTest { 8 | 9 | @Test 10 | void testReverseBits() { 11 | assertEquals(0, ReverseBits.reverseBits(0)); 12 | assertEquals(-1, ReverseBits.reverseBits(-1)); 13 | assertEquals(964176192, ReverseBits.reverseBits(43261596)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/BlowfishTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class BlowfishTest { 8 | 9 | Blowfish blowfish = new Blowfish(); 10 | 11 | @Test 12 | void testEncrypt() { 13 | // given 14 | String plainText = "123456abcd132536"; 15 | String key = "aabb09182736ccdd"; 16 | String expectedOutput = "d748ec383d3405f7"; 17 | 18 | // when 19 | String cipherText = blowfish.encrypt(plainText, key); 20 | 21 | // then 22 | assertEquals(expectedOutput, cipherText); 23 | } 24 | 25 | @Test 26 | void testDecrypt() { 27 | // given 28 | String cipherText = "d748ec383d3405f7"; 29 | String key = "aabb09182736ccdd"; 30 | String expectedOutput = "123456abcd132536"; 31 | 32 | // when 33 | String plainText = blowfish.decrypt(cipherText, key); 34 | 35 | // then 36 | assertEquals(expectedOutput, plainText); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/PolybiusTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class PolybiusTest { 8 | 9 | @Test 10 | void testEncrypt() { 11 | // Given 12 | String plaintext = "HELLOWORLD"; 13 | 14 | // When 15 | String actual = Polybius.encrypt(plaintext); 16 | 17 | // Then 18 | assertEquals("12042121244124322103", actual); 19 | } 20 | 21 | @Test 22 | void testDecrypt() { 23 | // Given 24 | String ciphertext = "12042121244124322103"; 25 | 26 | // When 27 | String actual = Polybius.decrypt(ciphertext); 28 | 29 | // Then 30 | assertEquals("HELLOWORLD", actual); 31 | } 32 | 33 | @Test 34 | void testIsTextTheSameAfterEncryptionAndDecryption() { 35 | // Given 36 | String plaintext = "HELLOWORLD"; 37 | 38 | // When 39 | String encryptedText = Polybius.encrypt(plaintext); 40 | String actual = Polybius.decrypt(encryptedText); 41 | 42 | // Then 43 | assertEquals(plaintext, actual); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/RSATest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class RSATest { 8 | 9 | RSA rsa = new RSA(1024); 10 | 11 | @Test 12 | void testRSA() { 13 | // given 14 | String textToEncrypt = "Such secure"; 15 | 16 | // when 17 | String cipherText = rsa.encrypt(textToEncrypt); 18 | String decryptedText = rsa.decrypt(cipherText); 19 | 20 | // then 21 | assertEquals("Such secure", decryptedText); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class SimpleSubCipherTest { 8 | 9 | SimpleSubCipher simpleSubCipher = new SimpleSubCipher(); 10 | 11 | @Test 12 | void simpleSubCipherEncryptTest() { 13 | // given 14 | String text = "defend the east wall of the castle"; 15 | String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb"; 16 | 17 | // when 18 | String cipherText = simpleSubCipher.encode(text, cipherSmall); 19 | 20 | // then 21 | assertEquals("giuifg cei iprc tpnn du cei qprcni", cipherText); 22 | } 23 | 24 | @Test 25 | void simpleSubCipherDecryptTest() { 26 | // given 27 | String encryptedText = "giuifg cei iprc tpnn du cei qprcni"; 28 | String cipherSmall = "phqgiumeaylnofdxjkrcvstzwb"; 29 | 30 | // when 31 | String decryptedText = simpleSubCipher.decode(encryptedText, cipherSmall); 32 | 33 | // then 34 | assertEquals("defend the east wall of the castle", decryptedText); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/VigenereTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class VigenereTest { 8 | 9 | Vigenere vigenere = new Vigenere(); 10 | 11 | @Test 12 | void vigenereEncryptTest() { 13 | // given 14 | String text = "Hello World!"; 15 | String key = "suchsecret"; 16 | 17 | // when 18 | String cipherText = vigenere.encrypt(text, key); 19 | 20 | // then 21 | assertEquals("Zynsg Yfvev!", cipherText); 22 | } 23 | 24 | @Test 25 | void vigenereDecryptTest() { 26 | // given 27 | String encryptedText = "Zynsg Yfvev!"; 28 | String key = "suchsecret"; 29 | 30 | // when 31 | String decryptedText = vigenere.decrypt(encryptedText, key); 32 | 33 | // then 34 | assertEquals("Hello World!", decryptedText); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class BinaryToHexadecimalTest { 8 | 9 | @Test 10 | public void testBinaryToHexadecimal() { 11 | assertEquals("6A", BinaryToHexadecimal.binToHex(1101010)); 12 | assertEquals("C", BinaryToHexadecimal.binToHex(1100)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class BinaryToOctalTest { 8 | 9 | @Test 10 | public void testBinaryToOctal() { 11 | assertEquals("226", BinaryToOctal.convertBinaryToOctal(10010110)); 12 | assertEquals("135", BinaryToOctal.convertBinaryToOctal(1011101)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/DecimalToHexaDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class DecimalToHexaDecimalTest { 8 | 9 | @Test 10 | public void testDecimalToHexaDecimal() { 11 | assertEquals("000000be", DecimalToHexaDecimal.decToHex(190)); 12 | assertEquals("00000708", DecimalToHexaDecimal.decToHex(1800)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/HexToOctTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class HexToOctTest { 8 | 9 | @Test 10 | public void testHexToOct() { 11 | assertEquals(110, HexToOct.decimal2octal(HexToOct.hex2decimal("48"))); 12 | assertEquals(255, HexToOct.decimal2octal(HexToOct.hex2decimal("AD"))); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class HexaDecimalToBinaryTest { 8 | 9 | @Test 10 | public void testHexaDecimalToBinary() { 11 | HexaDecimalToBinary hexaDecimalToBinary = new HexaDecimalToBinary(); 12 | assertEquals("1111111111111111111111111111111", hexaDecimalToBinary.convert("7fffffff")); 13 | assertEquals("101010111100110111101111", hexaDecimalToBinary.convert("abcdef")); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class HexaDecimalToDecimalTest { 8 | 9 | @Test 10 | public void testhexaDecimalToDecimal() { 11 | assertEquals(161, HexaDecimalToDecimal.getHexaToDec("A1")); 12 | assertEquals(428, HexaDecimalToDecimal.getHexaToDec("1ac")); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class IntegerToRomanTest { 8 | 9 | @Test 10 | public void testIntegerToRoman() { 11 | assertEquals("MCMXCIV", IntegerToRoman.integerToRoman(1994)); 12 | assertEquals("LVIII", IntegerToRoman.integerToRoman(58)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class OctalToBinaryTest { 8 | @Test 9 | public void testConvertOctalToBinary() { 10 | assertEquals(101, OctalToBinary.convertOctalToBinary(5)); 11 | assertEquals(1001, OctalToBinary.convertOctalToBinary(11)); 12 | assertEquals(101010, OctalToBinary.convertOctalToBinary(52)); 13 | assertEquals(110, OctalToBinary.convertOctalToBinary(6)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class OctalToDecimalTest { 8 | 9 | @Test 10 | public void testOctalToDecimal() { 11 | assertEquals(1465, OctalToDecimal.convertOctalToDecimal("2671")); 12 | assertEquals(189, OctalToDecimal.convertOctalToDecimal("275")); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class OctalToHexadecimalTest { 8 | 9 | @Test 10 | public void testOctalToHexadecimal() { 11 | assertEquals("1EA", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("752"))); 12 | assertEquals("15E", OctalToHexadecimal.decimalToHex(OctalToHexadecimal.octToDec("536"))); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class RomanToIntegerTest { 8 | 9 | @Test 10 | public void testRomanToInteger() { 11 | assertEquals(1994, RomanToInteger.romanToInt("MCMXCIV")); 12 | assertEquals(58, RomanToInteger.romanToInt("LVIII")); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.bloomfilter; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class BloomFilterTest { 7 | 8 | @Test 9 | public void test1() { 10 | BloomFilter bloomFilter = new BloomFilter<>(3, 10); 11 | bloomFilter.insert(3); 12 | bloomFilter.insert(17); 13 | 14 | Assertions.assertTrue(bloomFilter.contains(3)); 15 | Assertions.assertTrue(bloomFilter.contains(17)); 16 | } 17 | 18 | @Test 19 | public void test2() { 20 | BloomFilter bloomFilter = new BloomFilter<>(4, 20); 21 | bloomFilter.insert("omar"); 22 | bloomFilter.insert("mahamid"); 23 | 24 | Assertions.assertTrue(bloomFilter.contains("omar")); 25 | Assertions.assertTrue(bloomFilter.contains("mahamid")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | 3 | class LinearProbingHashMapTest extends MapTest { 4 | @Override 5 | , Value> Map getMap() { 6 | return new LinearProbingHashMap<>(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class FibonacciHeapTest { 7 | 8 | @Test 9 | void testHeap() { 10 | FibonacciHeap fibonacciHeap = new FibonacciHeap(); 11 | fibonacciHeap.insert(5); 12 | fibonacciHeap.insert(3); 13 | fibonacciHeap.insert(1); 14 | fibonacciHeap.insert(18); 15 | fibonacciHeap.insert(33); 16 | 17 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 1); 18 | fibonacciHeap.deleteMin(); 19 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 3); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class LeftistHeapTest { 7 | 8 | @Test 9 | void testLeftistHeap() { 10 | LeftistHeap heap = new LeftistHeap(); 11 | Assertions.assertTrue(heap.isEmpty()); 12 | heap.insert(6); 13 | Assertions.assertTrue(!heap.isEmpty()); 14 | heap.insert(2); 15 | heap.insert(3); 16 | heap.insert(1); 17 | heap.inOrder(); 18 | Assertions.assertTrue(heap.inOrder().toString().equals("[6, 2, 3, 1]")); 19 | Assertions.assertTrue(heap.extractMin() == 1); 20 | Assertions.assertTrue(heap.inOrder().toString().equals("[6, 2, 3]")); 21 | heap.insert(8); 22 | heap.insert(12); 23 | heap.insert(4); 24 | Assertions.assertTrue(heap.inOrder().toString().equals("[8, 3, 12, 2, 6, 4]")); 25 | heap.clear(); 26 | Assertions.assertTrue(heap.isEmpty()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.queues; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class LinkedQueueTest { 8 | @Test 9 | public void testQue() { 10 | LinkedQueue queue = new LinkedQueue<>(); 11 | for (int i = 1; i < 5; i++) { 12 | queue.enqueue(i); 13 | } 14 | 15 | assertEquals(queue.peekRear(), 4); 16 | assertEquals(queue.peek(2), 2); 17 | 18 | assertEquals(queue.peek(4), 4); 19 | 20 | final int[] element = {1}; 21 | 22 | // iterates over all the elements present 23 | // as in the form of nodes 24 | queue.forEach(integer -> { 25 | if (element[0]++ != integer) { 26 | throw new AssertionError(); 27 | } 28 | }); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CatalanNumberTest { 8 | 9 | @Test 10 | public void testCatalanNumber() { 11 | assertEquals(42, CatalanNumber.findNthCatalan(5)); 12 | assertEquals(16796, CatalanNumber.findNthCatalan(10)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class ClimbStairsTest { 8 | 9 | @Test 10 | void climbStairsTestForTwo() { 11 | assertEquals(2, ClimbingStairs.numberOfWays(2)); 12 | } 13 | 14 | @Test 15 | void climbStairsTestForZero() { 16 | assertEquals(0, ClimbingStairs.numberOfWays(0)); 17 | } 18 | 19 | @Test 20 | void climbStairsTestForOne() { 21 | assertEquals(1, ClimbingStairs.numberOfWays(1)); 22 | } 23 | 24 | @Test 25 | void climbStairsTestForFive() { 26 | assertEquals(8, ClimbingStairs.numberOfWays(5)); 27 | } 28 | 29 | @Test 30 | void climbStairsTestForThree() { 31 | assertEquals(3, ClimbingStairs.numberOfWays(3)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class EggDroppingTest { 8 | 9 | @Test 10 | void hasMultipleEggSingleFloor() { 11 | assertEquals(1, EggDropping.minTrials(3, 1)); 12 | } 13 | 14 | @Test 15 | void hasSingleEggSingleFloor() { 16 | assertEquals(1, EggDropping.minTrials(1, 1)); 17 | } 18 | 19 | @Test 20 | void hasSingleEggMultipleFloor() { 21 | assertEquals(3, EggDropping.minTrials(1, 3)); 22 | } 23 | 24 | @Test 25 | void hasMultipleEggMultipleFloor() { 26 | assertEquals(7, EggDropping.minTrials(100, 101)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class KnapsackMemoizationTest { 8 | 9 | KnapsackMemoization knapsackMemoization = new KnapsackMemoization(); 10 | 11 | @Test 12 | void test1() { 13 | int[] weight = {1, 3, 4, 5}; 14 | int[] value = {1, 4, 5, 7}; 15 | int capacity = 10; 16 | assertEquals(13, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); 17 | } 18 | 19 | @Test 20 | void test2() { 21 | int[] weight = {95, 4, 60, 32, 23, 72, 80, 62, 65, 46}; 22 | int[] value = {55, 10, 47, 5, 4, 50, 8, 61, 85, 87}; 23 | int capacity = 269; 24 | assertEquals(295, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); 25 | } 26 | 27 | @Test 28 | void test3() { 29 | int[] weight = {10, 20, 30}; 30 | int[] value = {60, 100, 120}; 31 | int capacity = 50; 32 | assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | class PartitionProblemTest { 9 | @Test 10 | public void testIfSumOfTheArrayIsOdd() { 11 | assertFalse(PartitionProblem.partition(new int[] {1, 2, 2})); 12 | } 13 | @Test 14 | public void testIfSizeOfTheArrayIsOne() { 15 | assertFalse(PartitionProblem.partition(new int[] {2})); 16 | } 17 | @Test 18 | public void testIfSumOfTheArrayIsEven1() { 19 | assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6})); 20 | } 21 | @Test 22 | public void testIfSumOfTheArrayIsEven2() { 23 | assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8})); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class SubsetCountTest { 8 | @Test 9 | void hasMultipleSubset() { 10 | int[] arr = new int[] {1, 2, 3, 3}; 11 | assertEquals(3, SubsetCount.getCount(arr, 6)); 12 | } 13 | @Test 14 | void singleElementSubset() { 15 | int[] arr = new int[] {1, 1, 1, 1}; 16 | assertEquals(4, SubsetCount.getCount(arr, 1)); 17 | } 18 | 19 | @Test 20 | void hasMultipleSubsetSO() { 21 | int[] arr = new int[] {1, 2, 3, 3}; 22 | assertEquals(3, SubsetCount.getCountSO(arr, 6)); 23 | } 24 | @Test 25 | void singleSubsetSO() { 26 | int[] arr = new int[] {1, 1, 1, 1}; 27 | assertEquals(1, SubsetCount.getCountSO(arr, 4)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | class SumOfSubsetTest { 9 | 10 | @Test 11 | void basicCheck() { 12 | assertFalse(SumOfSubset.subsetSum(new int[] {1, 2, 7, 10, 9}, 4, 14)); 13 | assertFalse(SumOfSubset.subsetSum(new int[] {2, 15, 1, 6, 7}, 4, 4)); 14 | assertTrue(SumOfSubset.subsetSum(new int[] {7, 3, 2, 5, 8}, 4, 14)); 15 | assertTrue(SumOfSubset.subsetSum(new int[] {4, 3, 2, 1}, 3, 5)); 16 | assertTrue(SumOfSubset.subsetSum(new int[] {1, 7, 2, 9, 10}, 4, 13)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Test class for {@code Tribonacci}. 9 | */ 10 | public class TribonacciTest { 11 | 12 | /** 13 | * Tests the Tribonacci computation for a set of known values. 14 | */ 15 | @Test 16 | public void testKnownValues() { 17 | assertEquals(0, Tribonacci.compute(0), "The 0th Tribonacci should be 0."); 18 | assertEquals(1, Tribonacci.compute(1), "The 1st Tribonacci should be 1."); 19 | assertEquals(1, Tribonacci.compute(2), "The 2nd Tribonacci should be 1."); 20 | assertEquals(2, Tribonacci.compute(3), "The 3rd Tribonacci should be 2."); 21 | assertEquals(4, Tribonacci.compute(4), "The 4th Tribonacci should be 4."); 22 | assertEquals(7, Tribonacci.compute(5), "The 5th Tribonacci should be 7."); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/WildcardMatchingTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | import static org.junit.jupiter.api.Assertions.assertFalse; 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class WildcardMatchingTest { 8 | 9 | @Test 10 | public void testMatchingPattern() { 11 | assertTrue(WildcardMatching.isMatch("aa", "a*")); 12 | assertTrue(WildcardMatching.isMatch("adceb", "*a*b")); 13 | } 14 | 15 | @Test 16 | public void testNonMatchingPattern() { 17 | assertFalse(WildcardMatching.isMatch("cb", "?a")); 18 | assertFalse(WildcardMatching.isMatch("acdcb", "a*c?b")); 19 | assertFalse(WildcardMatching.isMatch("mississippi", "m*issi*iss?*i")); 20 | } 21 | 22 | @Test 23 | public void testEmptyPattern() { 24 | assertTrue(WildcardMatching.isMatch("", "")); 25 | assertFalse(WildcardMatching.isMatch("abc", "")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/geometry/GrahamScanTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.geometry; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class GrahamScanTest { 8 | @Test 9 | void testGrahamScan() { 10 | GrahamScan.Point[] points = {new GrahamScan.Point(0, 3), new GrahamScan.Point(1, 1), new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), new GrahamScan.Point(0, 0), new GrahamScan.Point(1, 2), new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)}; 11 | String expectedResult = "[(0, 0), (3, 1), (4, 4), (0, 3)]"; 12 | 13 | GrahamScan graham = new GrahamScan(points); 14 | assertEquals(expectedResult, graham.hull().toString()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class FractionalKnapsackTest { 8 | 9 | @Test 10 | public void testFractionalKnapsackWithExampleCase() { 11 | int[] weight = {10, 20, 30}; 12 | int[] value = {60, 100, 120}; 13 | int capacity = 50; 14 | assertEquals(240, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); 15 | } 16 | 17 | @Test 18 | public void testFractionalKnapsackWithZeroCapacity() { 19 | int[] weight = {10, 20, 30}; 20 | int[] value = {60, 100, 120}; 21 | int capacity = 0; 22 | assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); 23 | } 24 | 25 | @Test 26 | public void testFractionalKnapsackWithEmptyItems() { 27 | int[] weight = {}; 28 | int[] value = {}; 29 | int capacity = 50; 30 | assertEquals(0, FractionalKnapsack.fractionalKnapsack(weight, value, capacity)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collections; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class JobSequencingTest { 10 | @Test 11 | public void testJobSequencingWithExampleCase() { 12 | ArrayList jobs = new ArrayList<>(); 13 | jobs.add(new JobSequencing.Job('a', 2, 100)); 14 | jobs.add(new JobSequencing.Job('b', 1, 19)); 15 | jobs.add(new JobSequencing.Job('c', 2, 27)); 16 | jobs.add(new JobSequencing.Job('d', 1, 25)); 17 | jobs.add(new JobSequencing.Job('e', 3, 15)); 18 | Collections.sort(jobs); 19 | String jobSequence = JobSequencing.findJobSequence(jobs, jobs.size()); 20 | 21 | assertEquals("Job Sequence: c -> a -> e", jobSequence); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class AbsoluteMaxTest { 9 | 10 | @Test 11 | void testGetMaxValue() { 12 | assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16)); 13 | assertEquals(-22, AbsoluteMax.getMaxValue(-3, -10, -22)); 14 | assertEquals(-888, AbsoluteMax.getMaxValue(-888)); 15 | } 16 | 17 | @Test 18 | void testGetMaxValueWithNoArguments() { 19 | assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class AbsoluteMinTest { 9 | 10 | @Test 11 | void testGetMinValue() { 12 | assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16)); 13 | assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2)); 14 | } 15 | 16 | @Test 17 | void testGetMinValueWithNoArguments() { 18 | Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); 19 | assertEquals("Numbers array cannot be empty", exception.getMessage()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.concurrent.ThreadLocalRandom; 6 | import java.util.stream.Stream; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class AbsoluteValueTest { 10 | 11 | @Test 12 | void testGetAbsValue() { 13 | Stream.generate(() -> ThreadLocalRandom.current().nextInt()).limit(1000).forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AliquotSumTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class AliquotSumTest { 8 | 9 | @Test 10 | void testGetMaxValue() { 11 | assertEquals(0, AliquotSum.getAliquotValue(1)); 12 | assertEquals(6, AliquotSum.getAliquotValue(6)); 13 | assertEquals(9, AliquotSum.getAliquotValue(15)); 14 | assertEquals(1, AliquotSum.getAliquotValue(19)); 15 | assertEquals(0, AliquotSum.getAliquotSum(1)); 16 | assertEquals(6, AliquotSum.getAliquotSum(6)); 17 | assertEquals(9, AliquotSum.getAliquotSum(15)); 18 | assertEquals(1, AliquotSum.getAliquotSum(19)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/ArmstrongTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * @author satyabarghav 9 | * @since 4/10/2023 10 | */ 11 | class ArmstrongTest { 12 | 13 | @Test 14 | void testIsArmstrong() { 15 | Armstrong armstrong = new Armstrong(); 16 | assertThat(armstrong.isArmstrong(0)).isTrue(); 17 | assertThat(armstrong.isArmstrong(1)).isTrue(); 18 | assertThat(armstrong.isArmstrong(153)).isTrue(); 19 | assertThat(armstrong.isArmstrong(371)).isTrue(); 20 | assertThat(armstrong.isArmstrong(1634)).isTrue(); 21 | assertThat(armstrong.isArmstrong(200)).isFalse(); 22 | assertThat(armstrong.isArmstrong(548834)).isTrue(); 23 | assertThat(armstrong.isArmstrong(9474)).isTrue(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AverageTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class AverageTest { 7 | 8 | private static final double SMALL_VALUE = 0.00001d; 9 | 10 | @Test 11 | public void testAverageDouble12() { 12 | double[] numbers = {3d, 6d, 9d, 12d, 15d, 18d, 21d}; 13 | Assertions.assertEquals(12d, Average.average(numbers), SMALL_VALUE); 14 | } 15 | 16 | @Test 17 | public void testAverageDouble20() { 18 | double[] numbers = {5d, 10d, 15d, 20d, 25d, 30d, 35d}; 19 | Assertions.assertEquals(20d, Average.average(numbers), SMALL_VALUE); 20 | } 21 | 22 | @Test 23 | public void testAverageDouble() { 24 | double[] numbers = {1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d}; 25 | Assertions.assertEquals(4.5d, Average.average(numbers), SMALL_VALUE); 26 | } 27 | 28 | @Test 29 | public void testAverageInt() { 30 | int[] numbers = {2, 4, 10}; 31 | Assertions.assertEquals(5, Average.average(numbers)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/BinaryPowTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class BinaryPowTest { 8 | 9 | @Test 10 | void testBinPow() { 11 | assertEquals(4, BinaryPow.binPow(2, 2)); 12 | assertEquals(256, BinaryPow.binPow(4, 4)); 13 | assertEquals(729, BinaryPow.binPow(9, 3)); 14 | assertEquals(262144, BinaryPow.binPow(8, 6)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/BinomialCoefficientTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class BinomialCoefficientTest { 8 | 9 | @Test 10 | void testBinomialCoefficient() { 11 | assertEquals(190, BinomialCoefficient.binomialCoefficient(20, 2)); 12 | assertEquals(792, BinomialCoefficient.binomialCoefficient(12, 5)); 13 | assertEquals(84, BinomialCoefficient.binomialCoefficient(9, 3)); 14 | assertEquals(1, BinomialCoefficient.binomialCoefficient(17, 17)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/CeilTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CeilTest { 8 | 9 | @Test 10 | void testCeil() { 11 | assertEquals(8, Ceil.ceil(7.057)); 12 | assertEquals(8, Ceil.ceil(7.004)); 13 | assertEquals(-13, Ceil.ceil(-13.004)); 14 | assertEquals(1, Ceil.ceil(.98)); 15 | assertEquals(-11, Ceil.ceil(-11.357)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/CombinationsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CombinationsTest { 8 | 9 | @Test 10 | void testCombination() { 11 | assertEquals(1, Combinations.combinations(1, 1)); 12 | assertEquals(252, Combinations.combinations(10, 5)); 13 | assertEquals(20, Combinations.combinations(6, 3)); 14 | assertEquals(15504, Combinations.combinations(20, 5)); 15 | } 16 | 17 | @Test 18 | void testCombinationOptimised() { 19 | assertEquals(100, Combinations.combinationsOptimized(100, 1)); 20 | assertEquals(1, Combinations.combinationsOptimized(1, 1)); 21 | assertEquals(252, Combinations.combinationsOptimized(10, 5)); 22 | assertEquals(20, Combinations.combinationsOptimized(6, 3)); 23 | assertEquals(15504, Combinations.combinationsOptimized(20, 5)); 24 | assertEquals(2535650040L, Combinations.combinationsOptimized(200, 5)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/DigitalRootTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class DigitalRootTest { 8 | 9 | @Test 10 | void testDigitalroot() { 11 | assertEquals(4, DigitalRoot.digitalRoot(4)); 12 | assertEquals(9, DigitalRoot.digitalRoot(9)); 13 | assertEquals(4, DigitalRoot.digitalRoot(49)); 14 | assertEquals(6, DigitalRoot.digitalRoot(78)); 15 | assertEquals(4, DigitalRoot.digitalRoot(1228)); 16 | assertEquals(5, DigitalRoot.digitalRoot(71348)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | class DudeneyNumberTest { 11 | @ParameterizedTest 12 | @CsvSource({"1", "512", "4913", "5832", "17576", "19683"}) 13 | void positiveDudeneyBase10Power3(final int n) { 14 | assertTrue(DudeneyNumber.isDudeney(n)); 15 | } 16 | 17 | @ParameterizedTest 18 | @CsvSource({"2", "19", "21", "125", "27", "343", "729", "19682", "19684"}) 19 | void negativeDudeneyBase10Power3(final int n) { 20 | assertFalse(DudeneyNumber.isDudeney(n)); 21 | } 22 | 23 | @ParameterizedTest 24 | @CsvSource({"0", "-1"}) 25 | void throwsInputLessThanOne(final int n) { 26 | assertThrows(IllegalArgumentException.class, () -> DudeneyNumber.isDudeney(n)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.util.stream.Stream; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.Arguments; 10 | import org.junit.jupiter.params.provider.MethodSource; 11 | 12 | public class FactorialRecursionTest { 13 | @ParameterizedTest 14 | @MethodSource("inputStream") 15 | void testFactorialRecursion(long expected, int number) { 16 | assertEquals(expected, FactorialRecursion.factorial(number)); 17 | } 18 | 19 | private static Stream inputStream() { 20 | return Stream.of(Arguments.of(1, 0), Arguments.of(1, 1), Arguments.of(2, 2), Arguments.of(6, 3), Arguments.of(120, 5)); 21 | } 22 | 23 | @Test 24 | void testThrowsForNegativeInput() { 25 | assertThrows(IllegalArgumentException.class, () -> FactorialRecursion.factorial(-1)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FactorialTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class FactorialTest { 9 | private static final String EXCEPTION_MESSAGE = "Input number cannot be negative"; 10 | 11 | @Test 12 | public void testWhenInvalidInoutProvidedShouldThrowException() { 13 | IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> Factorial.factorial(-1)); 14 | assertEquals(exception.getMessage(), EXCEPTION_MESSAGE); 15 | } 16 | 17 | @Test 18 | public void testCorrectFactorialCalculation() { 19 | assertEquals(1, Factorial.factorial(0)); 20 | assertEquals(1, Factorial.factorial(1)); 21 | assertEquals(120, Factorial.factorial(5)); 22 | assertEquals(3628800, Factorial.factorial(10)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.math.BigInteger; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class FibonacciLoopTest { 10 | @Test 11 | public void checkValueAtZero() { 12 | assertEquals(BigInteger.ZERO, FibonacciLoop.compute(0)); 13 | } 14 | 15 | @Test 16 | public void checkValueAtOne() { 17 | assertEquals(BigInteger.ONE, FibonacciLoop.compute(1)); 18 | } 19 | 20 | @Test 21 | public void checkValueAtTwo() { 22 | assertEquals(BigInteger.ONE, FibonacciLoop.compute(2)); 23 | } 24 | 25 | @Test 26 | public void checkRecurrenceRelation() { 27 | for (int i = 0; i < 100; ++i) { 28 | assertEquals(FibonacciLoop.compute(i + 2), FibonacciLoop.compute(i + 1).add(FibonacciLoop.compute(i))); 29 | } 30 | } 31 | 32 | @Test 33 | public void checkNegativeInput() { 34 | assertThrows(IllegalArgumentException.class, () -> { FibonacciLoop.compute(-1); }); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.math.BigInteger; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class FibonacciNumberGoldenRationTest { 10 | 11 | @Test 12 | public void returnsCorrectValues() { 13 | for (int n = 0; n <= FibonacciNumberGoldenRation.MAX_ARG; ++n) { 14 | final var actual = FibonacciNumberGoldenRation.compute(n); 15 | final var expected = FibonacciLoop.compute(n); 16 | assertEquals(expected, BigInteger.valueOf(actual)); 17 | } 18 | } 19 | 20 | @Test 21 | public void throwsIllegalArgumentExceptionForNegativeInput() { 22 | assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(-1); }); 23 | } 24 | 25 | @Test 26 | public void throwsIllegalArgumentExceptionForLargeInput() { 27 | assertThrows(IllegalArgumentException.class, () -> { FibonacciNumberGoldenRation.compute(FibonacciNumberGoldenRation.MAX_ARG + 1); }); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.Arguments; 10 | import org.junit.jupiter.params.provider.MethodSource; 11 | 12 | public class FindMaxRecursionTest { 13 | 14 | @ParameterizedTest 15 | @MethodSource("inputStream") 16 | void numberTests(int expected, int[] input) { 17 | Assertions.assertEquals(expected, FindMaxRecursion.max(input)); 18 | } 19 | 20 | private static Stream inputStream() { 21 | return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3})); 22 | } 23 | 24 | @Test 25 | public void testFindMaxThrowsExceptionForEmptyInput() { 26 | assertThrows(IllegalArgumentException.class, () -> FindMaxRecursion.max(new int[] {})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FindMaxTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.Arguments; 10 | import org.junit.jupiter.params.provider.MethodSource; 11 | 12 | public class FindMaxTest { 13 | 14 | @ParameterizedTest 15 | @MethodSource("inputStream") 16 | void numberTests(int expected, int[] input) { 17 | Assertions.assertEquals(expected, FindMax.findMax(input)); 18 | } 19 | 20 | private static Stream inputStream() { 21 | return Stream.of(Arguments.of(10, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(0, new int[] {-1, 0}), Arguments.of(-1, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(9, new int[] {3, -2, 3, 9, -4, -4, 8})); 22 | } 23 | 24 | @Test 25 | public void testFindMaxThrowsExceptionForEmptyInput() { 26 | assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[] {})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.api.Assertions; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.Arguments; 10 | import org.junit.jupiter.params.provider.MethodSource; 11 | 12 | public class FindMinRecursionTest { 13 | 14 | @ParameterizedTest 15 | @MethodSource("inputStream") 16 | void numberTests(int expected, int[] input) { 17 | Assertions.assertEquals(expected, FindMinRecursion.min(input)); 18 | } 19 | 20 | private static Stream inputStream() { 21 | return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 5, 5}), Arguments.of(-1, new int[] {-1, 0}), Arguments.of(-10, new int[] {-10, -9, -8, -7, -6, -5, -4, -3, -2, -1}), Arguments.of(-4, new int[] {3, -2, 3, 9, -4, -4, 8}), Arguments.of(3, new int[] {3})); 22 | } 23 | 24 | @Test 25 | public void testFindMaxThrowsExceptionForEmptyInput() { 26 | assertThrows(IllegalArgumentException.class, () -> FindMinRecursion.min(new int[] {})); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FloorTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | public class FloorTest { 7 | @Test 8 | public void testFloorWholeNumber() { 9 | assertEquals(0, Floor.floor(0)); 10 | assertEquals(1, Floor.floor(1)); 11 | assertEquals(-1, Floor.floor(-1)); 12 | assertEquals(42, Floor.floor(42)); 13 | assertEquals(-42, Floor.floor(-42)); 14 | } 15 | 16 | @Test 17 | public void testFloorDoubleNumber() { 18 | assertEquals(0, Floor.floor(0.1)); 19 | assertEquals(1, Floor.floor(1.9)); 20 | assertEquals(-2, Floor.floor(-1.1)); 21 | assertEquals(-43, Floor.floor(-42.7)); 22 | } 23 | 24 | @Test 25 | public void testFloorNegativeZero() { 26 | assertEquals(-0.0, Floor.floor(-0.0)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | public class FrizzyNumberTest { 7 | @Test 8 | public void testFrizziesForBase2() { 9 | assertEquals(1, FrizzyNumber.getNthFrizzy(2, 1)); 10 | assertEquals(3, FrizzyNumber.getNthFrizzy(2, 3)); 11 | assertEquals(1000, FrizzyNumber.getNthFrizzy(2, 1000)); 12 | } 13 | 14 | @Test 15 | public void testFrizziesForBase3() { 16 | assertEquals(1, FrizzyNumber.getNthFrizzy(3, 1)); 17 | assertEquals(3, FrizzyNumber.getNthFrizzy(3, 2)); 18 | assertEquals(29430, FrizzyNumber.getNthFrizzy(3, 1000)); 19 | } 20 | 21 | @Test 22 | public void testFrizziesForBase69() { 23 | assertEquals(1, FrizzyNumber.getNthFrizzy(69, 1)); 24 | assertEquals(69, FrizzyNumber.getNthFrizzy(69, 2)); 25 | assertEquals(328510, FrizzyNumber.getNthFrizzy(69, 9)); 26 | assertEquals(333340, FrizzyNumber.getNthFrizzy(69, 15)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/GaussianTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static com.thealgorithms.maths.Gaussian.gaussian; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | import java.util.ArrayList; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class GaussianTest { 10 | 11 | // easy pass test for the whole class. Matrix of 2*3. 12 | @Test 13 | void passTest1() { 14 | ArrayList list = new ArrayList(); 15 | ArrayList gaussian = new ArrayList(); 16 | ArrayList answer = new ArrayList(); 17 | answer.add(0.0); 18 | answer.add(1.0); 19 | 20 | int matrixSize = 2; 21 | list.add(1.0); 22 | list.add(1.0); 23 | list.add(1.0); 24 | list.add(2.0); 25 | list.add(1.0); 26 | list.add(1.0); 27 | gaussian = gaussian(matrixSize, list); 28 | 29 | assertEquals(answer, gaussian); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/GenericRootTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.Arguments; 8 | import org.junit.jupiter.params.provider.MethodSource; 9 | 10 | public class GenericRootTest { 11 | @ParameterizedTest 12 | @MethodSource("tcStream") 13 | public void testGenericRoot(final int input, final int expected) { 14 | assertEquals(expected, GenericRoot.genericRoot(input)); 15 | } 16 | 17 | @ParameterizedTest 18 | @MethodSource("tcStream") 19 | public void testGenericRootWithNegativeInputs(final int input, final int expected) { 20 | assertEquals(expected, GenericRoot.genericRoot(-input)); 21 | } 22 | 23 | private static Stream tcStream() { 24 | return Stream.of(Arguments.of(0, 0), Arguments.of(1, 1), Arguments.of(12345, 6), Arguments.of(123, 6), Arguments.of(15937, 7), Arguments.of(222222, 3), Arguments.of(99999, 9)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/HarshadNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class HarshadNumberTest { 9 | 10 | @Test 11 | public void harshadNumber() { 12 | 13 | assertTrue(HarshadNumber.isHarshad(18)); 14 | assertFalse(HarshadNumber.isHarshad(-18)); 15 | assertFalse(HarshadNumber.isHarshad(19)); 16 | assertTrue(HarshadNumber.isHarshad(999999999)); 17 | assertFalse(HarshadNumber.isHarshad(0)); 18 | 19 | assertTrue(HarshadNumber.isHarshad("18")); 20 | assertFalse(HarshadNumber.isHarshad("-18")); 21 | assertFalse(HarshadNumber.isHarshad("19")); 22 | assertTrue(HarshadNumber.isHarshad("999999999")); 23 | assertTrue(HarshadNumber.isHarshad("99999999999100")); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/JosephusProblemTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class JosephusProblemTest { 8 | 9 | @Test 10 | void testJosephusProblem() { 11 | assertEquals(3, JosephusProblem.findTheWinner(5, 2)); 12 | assertEquals(5, JosephusProblem.findTheWinner(6, 4)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class LeastCommonMultipleTest { 7 | 8 | /* 9 | * Test for first number greater than second number 10 | */ 11 | @Test 12 | public void testForFirst() { 13 | int result = LeastCommonMultiple.lcm(6, 8); 14 | int expected = 24; 15 | Assertions.assertEquals(result, expected); 16 | } 17 | 18 | /* 19 | * Test for second number greater than first number 20 | */ 21 | @Test 22 | public void testForSecond() { 23 | int result = LeastCommonMultiple.lcm(8, 6); 24 | int expected = 24; 25 | Assertions.assertEquals(result, expected); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class LeonardoNumberTest { 9 | @Test 10 | void leonardoNumberNegative() { 11 | assertThrows(ArithmeticException.class, () -> LeonardoNumber.leonardoNumber(-1)); 12 | } 13 | @Test 14 | void leonardoNumberZero() { 15 | assertEquals(1, LeonardoNumber.leonardoNumber(0)); 16 | } 17 | @Test 18 | void leonardoNumberOne() { 19 | assertEquals(1, LeonardoNumber.leonardoNumber(1)); 20 | } 21 | @Test 22 | void leonardoNumberFive() { 23 | assertEquals(15, LeonardoNumber.leonardoNumber(5)); 24 | } 25 | @Test 26 | void leonardoNumberTwenty() { 27 | assertEquals(21891, LeonardoNumber.leonardoNumber(20)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/LucasSeriesTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class LucasSeriesTest { 8 | @Test 9 | void lucasSeriesTwo() { 10 | assertEquals(2, LucasSeries.lucasSeries(1)); 11 | assertEquals(2, LucasSeries.lucasSeriesIteration(1)); 12 | } 13 | @Test 14 | void lucasSeriesOne() { 15 | assertEquals(1, LucasSeries.lucasSeries(2)); 16 | assertEquals(1, LucasSeries.lucasSeriesIteration(2)); 17 | } 18 | @Test 19 | void lucasSeriesSeven() { 20 | assertEquals(7, LucasSeries.lucasSeries(5)); 21 | assertEquals(7, LucasSeries.lucasSeriesIteration(5)); 22 | } 23 | @Test 24 | void lucasSeriesEleven() { 25 | assertEquals(123, LucasSeries.lucasSeries(11)); 26 | assertEquals(123, LucasSeries.lucasSeriesIteration(11)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/MaxValueTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MaxValueTest { 8 | @Test 9 | public void maxTest() { 10 | assertEquals(-1, MaxValue.max(-1, -3)); 11 | assertEquals(3, MaxValue.max(3, 2)); 12 | assertEquals(5, MaxValue.max(5, 5)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/MedianTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MedianTest { 8 | @Test 9 | void medianSingleValue() { 10 | int[] arr = {0}; 11 | assertEquals(0, Median.median(arr)); 12 | } 13 | 14 | @Test 15 | void medianTwoValues() { 16 | int[] arr = {1, 2}; 17 | assertEquals(1.5, Median.median(arr)); 18 | } 19 | 20 | @Test 21 | void medianThreeValues() { 22 | int[] arr = {1, 2, 3}; 23 | assertEquals(2, Median.median(arr)); 24 | } 25 | 26 | @Test 27 | void medianDecimalValueReturn() { 28 | int[] arr = {1, 2, 3, 4, 5, 6, 8, 9}; 29 | assertEquals(4.5, Median.median(arr)); 30 | } 31 | 32 | @Test 33 | void medianNegativeValues() { 34 | int[] arr = {-27, -16, -7, -4, -2, -1}; 35 | assertEquals(-5.5, Median.median(arr)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/MinValueTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MinValueTest { 8 | @Test 9 | public void minTest() { 10 | assertEquals(-1, MinValue.min(-1, 3)); 11 | assertEquals(2, MinValue.min(3, 2)); 12 | assertEquals(5, MinValue.min(5, 5)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/ModeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | 5 | import java.util.stream.Stream; 6 | import org.junit.jupiter.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.Arguments; 8 | import org.junit.jupiter.params.provider.MethodSource; 9 | 10 | public class ModeTest { 11 | @ParameterizedTest 12 | @MethodSource("tcStream") 13 | void basicTest(final int[] expected, final int[] numbers) { 14 | assertArrayEquals(expected, Mode.mode(numbers)); 15 | } 16 | 17 | private static Stream tcStream() { 18 | return Stream.of(Arguments.of(null, new int[] {}), Arguments.of(new int[] {5}, new int[] {5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {5, 4, 3, 2, 1}), 19 | Arguments.of(new int[] {7}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), Arguments.of(new int[] {7, 9}, new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9})); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PerfectNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | class PerfectNumberTest { 9 | 10 | @Test 11 | public void perfectNumber() { 12 | int[] trueTestCases = {6, 28, 496, 8128, 33550336}; 13 | int[] falseTestCases = {-6, 0, 1, 9, 123}; 14 | for (Integer n : trueTestCases) { 15 | assertTrue(PerfectNumber.isPerfectNumber(n)); 16 | assertTrue(PerfectNumber.isPerfectNumber2(n)); 17 | } 18 | for (Integer n : falseTestCases) { 19 | assertFalse(PerfectNumber.isPerfectNumber(n)); 20 | assertFalse(PerfectNumber.isPerfectNumber2(n)); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PerfectSquareTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.ValueSource; 6 | 7 | public class PerfectSquareTest { 8 | @ParameterizedTest 9 | @ValueSource(ints = {0, 1, 2 * 2, 3 * 3, 4 * 4, 5 * 5, 6 * 6, 7 * 7, 8 * 8, 9 * 9, 10 * 10, 11 * 11, 123 * 123}) 10 | void positiveTest(final int number) { 11 | Assertions.assertTrue(PerfectSquare.isPerfectSquare(number)); 12 | } 13 | 14 | @ParameterizedTest 15 | @ValueSource(ints = {-1, -2, -3, -4, -5, -100, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 17, 99, 101, 257, 999, 1001}) 16 | void negativeTest(final int number) { 17 | Assertions.assertFalse(PerfectSquare.isPerfectSquare(number)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PowerOfTwoOrNotTest { 9 | @Test 10 | public void testPowerOfTwoOrNotForPowersOfTwo() { 11 | final var powersOfTwo = new int[] {1, 2, 4, 8, 16, 32, 64}; 12 | for (final var n : powersOfTwo) { 13 | assertTrue(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n)); 14 | } 15 | } 16 | 17 | @Test 18 | public void testPowerOfTwoOrNotForNotPowersOfTwo() { 19 | final var notPowersOfTwo = new int[] {-16, -8, -6, -5, -4, -3, -2, -1, 0, 3, 5, 6, 7, 9, 10, 11, 33, 63, 65, 1000, 9999}; 20 | for (final var n : notPowersOfTwo) { 21 | assertFalse(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Test case for Power using Recursion 9 | * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) 10 | */ 11 | 12 | class PowerUsingRecursionTest { 13 | 14 | @Test 15 | void testPowerUsingRecursion() { 16 | assertEquals(32.0, PowerUsingRecursion.power(2.0, 5)); 17 | assertEquals(97.65625, PowerUsingRecursion.power(2.5, 5)); 18 | assertEquals(81, PowerUsingRecursion.power(3, 4)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PrimeCheckTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PrimeCheckTest { 7 | 8 | @Test 9 | void test1() { 10 | Assertions.assertTrue(PrimeCheck.isPrime(2)); 11 | } 12 | 13 | @Test 14 | void test2() { 15 | Assertions.assertFalse(PrimeCheck.isPrime(-1)); 16 | } 17 | 18 | @Test 19 | void test3() { 20 | Assertions.assertFalse(PrimeCheck.isPrime(4)); 21 | } 22 | 23 | @Test 24 | void test4() { 25 | Assertions.assertTrue(PrimeCheck.isPrime(5)); 26 | } 27 | 28 | @Test 29 | void test5() { 30 | Assertions.assertFalse(PrimeCheck.isPrime(15)); 31 | } 32 | 33 | @Test 34 | void test6() { 35 | Assertions.assertTrue(PrimeCheck.isPrime(11)); 36 | } 37 | 38 | @Test 39 | void test7() { 40 | Assertions.assertFalse(PrimeCheck.isPrime(49)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import java.util.List; 7 | import org.junit.jupiter.api.Test; 8 | 9 | class PrimeFactorizationTest { 10 | 11 | @Test 12 | void testpFactorsMustReturnEmptyList() { 13 | // given 14 | int n = 0; 15 | 16 | // then 17 | assertTrue(PrimeFactorization.pfactors(n).isEmpty()); 18 | } 19 | 20 | @Test 21 | void testpFactorsMustReturnNonEmptyList() { 22 | // given 23 | int n = 198; 24 | int expectedListSize = 4; 25 | 26 | // when 27 | List actualResultList = PrimeFactorization.pfactors(n); 28 | 29 | // then 30 | assertEquals(expectedListSize, actualResultList.size()); 31 | assertEquals(2, actualResultList.get(0)); 32 | assertEquals(3, actualResultList.get(1)); 33 | assertEquals(3, actualResultList.get(2)); 34 | assertEquals(11, actualResultList.get(3)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PronicNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PronicNumberTest { 9 | 10 | @Test 11 | void testForPronicNumber() { 12 | // given 13 | int number = 30; 14 | 15 | // when 16 | boolean result = PronicNumber.isPronic(number); 17 | 18 | // then 19 | assertTrue(result); 20 | } 21 | 22 | @Test 23 | void testForNonPronicNumber() { 24 | // given 25 | int number = 21; 26 | 27 | // when 28 | boolean result = PronicNumber.isPronic(number); 29 | 30 | // then 31 | assertFalse(result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PythagoreanTripleTest { 9 | 10 | @Test 11 | public void testPythagoreanTriple() { 12 | assertTrue(PythagoreanTriple.isPythagTriple(3, 4, 5)); 13 | assertTrue(PythagoreanTriple.isPythagTriple(6, 8, 10)); 14 | assertTrue(PythagoreanTriple.isPythagTriple(9, 12, 15)); 15 | assertTrue(PythagoreanTriple.isPythagTriple(12, 16, 20)); 16 | assertTrue(PythagoreanTriple.isPythagTriple(15, 20, 25)); 17 | assertTrue(PythagoreanTriple.isPythagTriple(18, 24, 30)); 18 | assertFalse(PythagoreanTriple.isPythagTriple(5, 20, 30)); 19 | assertFalse(PythagoreanTriple.isPythagTriple(6, 8, 100)); 20 | assertFalse(PythagoreanTriple.isPythagTriple(-2, -2, 2)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/ReverseNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.util.HashMap; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class ReverseNumberTest { 10 | 11 | @Test 12 | public void testReverseNumber() { 13 | HashMap testCases = new HashMap<>(); 14 | testCases.put(0, 0); 15 | testCases.put(1, 1); 16 | testCases.put(10, 1); 17 | testCases.put(123, 321); 18 | testCases.put(7890, 987); 19 | 20 | for (final var tc : testCases.entrySet()) { 21 | assertEquals(ReverseNumber.reverseNumber(tc.getKey()), tc.getValue()); 22 | } 23 | } 24 | 25 | @Test 26 | public void testReverseNumberThrowsExceptionForNegativeInput() { 27 | assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(-1)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class SquareRootWithNewtonRaphsonTestMethod { 7 | 8 | @Test 9 | void testfor1() { 10 | Assertions.assertEquals(1, SquareRootWithNewtonRaphsonMethod.squareRoot(1)); 11 | } 12 | 13 | @Test 14 | void testfor2() { 15 | Assertions.assertEquals(1.414213562373095, SquareRootWithNewtonRaphsonMethod.squareRoot(2)); 16 | } 17 | 18 | @Test 19 | void testfor625() { 20 | Assertions.assertEquals(25.0, SquareRootWithNewtonRaphsonMethod.squareRoot(625)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class SquareRootwithBabylonianMethodTest { 7 | 8 | @Test 9 | void testfor4() { 10 | Assertions.assertEquals(2, SquareRootWithBabylonianMethod.squareRoot(4)); 11 | } 12 | 13 | @Test 14 | void testfor1() { 15 | Assertions.assertEquals(1, SquareRootWithBabylonianMethod.squareRoot(1)); 16 | } 17 | 18 | @Test 19 | void testfor2() { 20 | Assertions.assertEquals(1.4142135381698608, SquareRootWithBabylonianMethod.squareRoot(2)); 21 | } 22 | 23 | @Test 24 | void testfor625() { 25 | Assertions.assertEquals(25, SquareRootWithBabylonianMethod.squareRoot(625)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/StandardDeviationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class StandardDeviationTest { 7 | 8 | @Test 9 | void test1() { 10 | double[] t1 = new double[] {1, 1, 1, 1, 1}; 11 | Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); 12 | } 13 | 14 | @Test 15 | void test2() { 16 | double[] t2 = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 17 | Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143); 18 | } 19 | 20 | @Test 21 | void test3() { 22 | double[] t3 = new double[] {1.1, 8.5, 20.3, 2.4, 6.2}; 23 | Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265); 24 | } 25 | 26 | @Test 27 | void test4() { 28 | double[] t4 = new double[] { 29 | 3.14, 30 | 2.22222, 31 | 9.89898989, 32 | 100.00045, 33 | 56.7, 34 | }; 35 | Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/StandardScoreTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class StandardScoreTest { 7 | 8 | @Test 9 | void test1() { 10 | Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4); 11 | } 12 | 13 | @Test 14 | void test2() { 15 | Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0); 16 | } 17 | 18 | @Test 19 | void test3() { 20 | Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0); 21 | } 22 | 23 | @Test 24 | void test4() { 25 | Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/StrobogrammaticNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class StrobogrammaticNumberTest { 8 | 9 | @Test 10 | void testIsStrobogrammatic() { 11 | StrobogrammaticNumber strobogrammaticNumber = new StrobogrammaticNumber(); 12 | assertThat(strobogrammaticNumber.isStrobogrammatic("69")).isTrue(); 13 | assertThat(strobogrammaticNumber.isStrobogrammatic("88")).isTrue(); 14 | assertThat(strobogrammaticNumber.isStrobogrammatic("818")).isTrue(); 15 | assertThat(strobogrammaticNumber.isStrobogrammatic("101")).isTrue(); 16 | assertThat(strobogrammaticNumber.isStrobogrammatic("609")).isTrue(); 17 | assertThat(strobogrammaticNumber.isStrobogrammatic("120")).isFalse(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class SumWithoutArithmeticOperatorsTest { 8 | SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators(); 9 | 10 | @Test 11 | void addZerotoZero() { 12 | assertEquals(0, obj.getSum(0, 0)); 13 | } 14 | 15 | @Test 16 | void addZerotoNumber() { 17 | assertEquals(5, obj.getSum(0, 5)); 18 | assertEquals(28, obj.getSum(28, 0)); 19 | } 20 | 21 | @Test 22 | void addOddtoEven() { 23 | assertEquals(13, obj.getSum(3, 10)); 24 | assertEquals(55, obj.getSum(49, 6)); 25 | } 26 | 27 | @Test 28 | void addEventoOdd() { 29 | assertEquals(13, obj.getSum(10, 3)); 30 | assertEquals(41, obj.getSum(40, 1)); 31 | } 32 | 33 | @Test 34 | void addRandoms() { 35 | assertEquals(88, obj.getSum(44, 44)); 36 | assertEquals(370, obj.getSum(100, 270)); 37 | assertEquals(3, obj.getSum(1, 2)); 38 | assertEquals(5, obj.getSum(2, 3)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/TestArmstrong.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class TestArmstrong { 8 | 9 | @Test 10 | public void testArmstrong() { 11 | Armstrong armstrong = new Armstrong(); 12 | assertThat(armstrong.isArmstrong(371)).isTrue(); 13 | assertThat(armstrong.isArmstrong(200)).isFalse(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/VolumeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class VolumeTest { 8 | 9 | @Test 10 | public void volume() { 11 | 12 | /* test cube */ 13 | assertTrue(Volume.volumeCube(7) == 343.0); 14 | 15 | /* test cuboid */ 16 | assertTrue(Volume.volumeCuboid(2, 5, 7) == 70.0); 17 | 18 | /* test sphere */ 19 | assertTrue(Volume.volumeSphere(7) == 1436.7550402417319); 20 | 21 | /* test cylinder */ 22 | assertTrue(Volume.volumeCylinder(3, 7) == 197.92033717615698); 23 | 24 | /* test hemisphere */ 25 | assertTrue(Volume.volumeHemisphere(7) == 718.3775201208659); 26 | 27 | /* test cone */ 28 | assertTrue(Volume.volumeCone(3, 7) == 65.97344572538566); 29 | 30 | /* test prism */ 31 | assertTrue(Volume.volumePrism(10, 2) == 20.0); 32 | 33 | /* test pyramid */ 34 | assertTrue(Volume.volumePyramid(10, 3) == 10.0); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/misc/MapReduceTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MapReduceTest { 8 | @Test 9 | public void testMapReduceWithSingleWordSentence() { 10 | String oneWordSentence = "Hactober"; 11 | String result = MapReduce.mapreduce(oneWordSentence); 12 | 13 | assertEquals("Hactober: 1", result); 14 | } 15 | 16 | @Test 17 | public void testMapReduceWithMultipleWordSentence() { 18 | String multipleWordSentence = "I Love Love HactoberFest"; 19 | String result = MapReduce.mapreduce(multipleWordSentence); 20 | 21 | assertEquals("I: 1,Love: 2,HactoberFest: 1", result); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | import org.junit.jupiter.api.Test; 9 | 10 | public class MedianOfMatrixtest { 11 | 12 | @Test 13 | public void testMedianWithOddNumberOfElements() { 14 | List> matrix = new ArrayList<>(); 15 | matrix.add(Arrays.asList(1, 3, 5)); 16 | matrix.add(Arrays.asList(2, 4, 6)); 17 | matrix.add(Arrays.asList(7, 8, 9)); 18 | 19 | int result = MedianOfMatrix.median(matrix); 20 | 21 | assertEquals(5, result); 22 | } 23 | 24 | @Test 25 | public void testMedianWithEvenNumberOfElements() { 26 | List> matrix = new ArrayList<>(); 27 | matrix.add(Arrays.asList(2, 4)); 28 | matrix.add(Arrays.asList(1, 3)); 29 | 30 | int result = MedianOfMatrix.median(matrix); 31 | 32 | assertEquals(2, result); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/ArrayRightRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | public final class ArrayRightRotation { 4 | private ArrayRightRotation() { 5 | } 6 | public static int[] rotateRight(int[] arr, int k) { 7 | if (arr == null || arr.length == 0 || k < 0) { 8 | throw new IllegalArgumentException("Invalid input"); 9 | } 10 | 11 | int n = arr.length; 12 | k = k % n; // Handle cases where k is larger than the array length 13 | 14 | reverseArray(arr, 0, n - 1); 15 | reverseArray(arr, 0, k - 1); 16 | reverseArray(arr, k, n - 1); 17 | 18 | return arr; 19 | } 20 | 21 | private static void reverseArray(int[] arr, int start, int end) { 22 | while (start < end) { 23 | int temp = arr[start]; 24 | arr[start] = arr[end]; 25 | arr[end] = temp; 26 | start++; 27 | end--; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CRC16Test.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class CRC16Test { 8 | @Test 9 | void testCRC16() { 10 | // given 11 | String textToCRC16 = "hacktoberfest!"; 12 | 13 | // when 14 | String resultCRC16 = CRC16.crc16(textToCRC16); // Algorithm CRC16-CCITT-FALSE 15 | 16 | // then 17 | assertEquals("10FC", resultCRC16); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java: -------------------------------------------------------------------------------- 1 | 2 | package com.thealgorithms.others; 3 | 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class CRCAlgorithmTest { 9 | 10 | @Test 11 | void test1() { 12 | CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 0.0); 13 | 14 | // A bit-error rate of 0.0 should not provide any wrong messages 15 | c.changeMess(); 16 | c.divideMessageWithP(false); 17 | assertEquals(c.getWrongMess(), 0); 18 | } 19 | 20 | @Test 21 | void test2() { 22 | CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 1.0); 23 | 24 | // A bit error rate of 1.0 should not provide any correct messages 25 | c.changeMess(); 26 | c.divideMessageWithP(false); 27 | assertEquals(c.getCorrectMess(), 0); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CountCharTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class CountCharTest { 8 | 9 | @Test 10 | void testCountCharacters() { 11 | String input = "12345"; 12 | int expectedValue = 5; 13 | 14 | assertEquals(expectedValue, CountChar.countCharacters(input)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CountSetBitsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CountSetBitsTest { 8 | 9 | @Test 10 | void testSetBits() { 11 | CountSetBits csb = new CountSetBits(); 12 | assertEquals(1L, csb.countSetBits(16)); 13 | assertEquals(4, csb.countSetBits(15)); 14 | assertEquals(5, csb.countSetBits(10000)); 15 | assertEquals(5, csb.countSetBits(31)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/LineSweepTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | public class LineSweepTest { 8 | 9 | @Test 10 | void testForOverlap() { 11 | int[][] arr = {{0, 10}, {7, 20}, {15, 24}}; 12 | assertTrue(LineSweep.isOverlap(arr)); 13 | } 14 | 15 | @Test 16 | void testForNoOverlap() { 17 | int[][] arr = {{0, 10}, {11, 20}, {21, 24}}; 18 | assertFalse(LineSweep.isOverlap(arr)); 19 | } 20 | @Test 21 | void testForOverlapWhenEndAEqualsStartBAndViceVersa() { 22 | int[][] arr = {{0, 10}, {10, 20}, {21, 24}}; 23 | assertTrue(LineSweep.isOverlap(arr)); 24 | } 25 | @Test 26 | void testForMaximumEndPoint() { 27 | int[][] arr = {{10, 20}, {1, 100}, {14, 16}, {1, 8}}; 28 | assertEquals(100, LineSweep.findMaximumEndPoint(arr)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthKTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MaximumSumOfDistinctSubarraysWithLengthKTest { 8 | @Test 9 | public void sampleTestCase1() { 10 | assertEquals(15, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 1, 5, 4, 2, 9, 9, 9)); 11 | } 12 | 13 | @Test 14 | public void sampleTestCase2() { 15 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 4, 4, 4)); 16 | } 17 | 18 | @Test 19 | public void sampleTestCase3() { 20 | assertEquals(12, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(3, 9, 9, 9, 1, 2, 3)); 21 | } 22 | 23 | @Test 24 | public void edgeCase1() { 25 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(0, 9, 9, 9)); 26 | } 27 | 28 | @Test 29 | public void edgeCase2() { 30 | assertEquals(0, MaximumSumOfDistinctSubarraysWithLengthK.maximumSubarraySum(5, 9, 9, 9)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/PasswordGenTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class PasswordGenTest { 9 | 10 | @Test 11 | public void failGenerationWithSameMinMaxLengthTest() { 12 | int length = 10; 13 | assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(length, length); }); 14 | } 15 | 16 | @Test 17 | public void generateOneCharacterPassword() { 18 | String tempPassword = PasswordGen.generatePassword(1, 2); 19 | assertTrue(tempPassword.length() == 1); 20 | } 21 | 22 | @Test 23 | public void failGenerationWithMinLengthSmallerThanMaxLengthTest() { 24 | int minLength = 10; 25 | int maxLength = 5; 26 | assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(minLength, maxLength); }); 27 | } 28 | 29 | @Test 30 | public void generatePasswordNonEmptyTest() { 31 | String tempPassword = PasswordGen.generatePassword(8, 16); 32 | assertTrue(tempPassword.length() != 0); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertIterableEquals; 4 | 5 | import java.util.List; 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class TestPrintMatrixInSpiralOrder { 9 | @Test 10 | public void testOne() { 11 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; 12 | var printClass = new PrintAMatrixInSpiralOrder(); 13 | List res = printClass.print(matrix, matrix.length, matrix[0].length); 14 | List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, 10, 11, 17, 26, 25, 24, 15, 16); 15 | assertIterableEquals(res, list); 16 | } 17 | 18 | @Test 19 | public void testTwo() { 20 | int[][] matrix = {{2, 2}}; 21 | var printClass = new PrintAMatrixInSpiralOrder(); 22 | List res = printClass.print(matrix, matrix.length, matrix[0].length); 23 | List list = List.of(2, 2); 24 | assertIterableEquals(res, list); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class HowManyTimesRotatedTest { 8 | 9 | @Test 10 | public void testHowManyTimesRotated() { 11 | int[] arr1 = {5, 1, 2, 3, 4}; 12 | assertEquals(1, HowManyTimesRotated.rotated(arr1)); 13 | int[] arr2 = {15, 17, 2, 3, 5}; 14 | assertEquals(2, HowManyTimesRotated.rotated(arr2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.CsvSource; 7 | 8 | class RabinKarpAlgorithmTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"This is an example for rabin karp algorithmn, algorithmn, 101", "AAABBDDG, AAA, 137", "AAABBCCBB, BBCC, 101", "AAABBCCBB, BBCC, 131", "AAAABBBBCCC, CCC, 41", "ABCBCBCAAB, AADB, 293", "Algorithm The Algorithm, Algorithm, 101"}) 12 | void rabinKarpAlgorithmTestExample(String txt, String pat, int q) { 13 | int indexFromOurAlgorithm = RabinKarpAlgorithm.search(pat, txt, q); 14 | int indexFromLinearSearch = txt.indexOf(pat); 15 | assertEquals(indexFromOurAlgorithm, indexFromLinearSearch); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class SortOrderAgnosticBinarySearchTest { 8 | 9 | @Test 10 | public void testAscending() { 11 | int[] arr = {1, 2, 3, 4, 5}; // for ascending order. 12 | int target = 2; 13 | int ans = SortOrderAgnosticBinarySearch.find(arr, target); 14 | int excepted = 1; 15 | assertEquals(excepted, ans); 16 | } 17 | 18 | @Test 19 | public void testDescending() { 20 | int[] arr = {5, 4, 3, 2, 1}; // for descending order. 21 | int target = 2; 22 | int ans = SortOrderAgnosticBinarySearch.find(arr, target); 23 | int excepted = 3; 24 | assertEquals(excepted, ans); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class TestSearchInARowAndColWiseSortedMatrix { 8 | @Test 9 | public void searchItem() { 10 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; 11 | 12 | var test = new SearchInARowAndColWiseSortedMatrix(); 13 | int[] res = test.search(matrix, 16); 14 | int[] expectedResult = {2, 2}; 15 | assertArrayEquals(expectedResult, res); 16 | } 17 | 18 | @Test 19 | public void notFound() { 20 | int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; 21 | 22 | var test = new SearchInARowAndColWiseSortedMatrix(); 23 | int[] res = test.search(matrix, 96); 24 | int[] expectedResult = {-1, -1}; 25 | assertArrayEquals(expectedResult, res); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class BinaryInsertionSortTest extends SortingAlgorithmTest { 4 | private final BinaryInsertionSort binaryInsertionSort = new BinaryInsertionSort(); 5 | 6 | @Override 7 | SortAlgorithm getSortAlgorithm() { 8 | return binaryInsertionSort; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/BitonicSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class BitonicSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new BitonicSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/BubbleSortRecursiveTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class BubbleSortRecursiveTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new BubbleSortRecursive(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/CircleSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class CircleSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new CircleSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class ExchangeSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new ExchangeSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/HeapSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class HeapSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new HeapSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class MergeSortRecursiveTest { 10 | 11 | // private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(); 12 | 13 | @Test 14 | void testMergeSortRecursiveCase1() { 15 | MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); 16 | 17 | List expected = Arrays.asList(3, 5, 9, 12, 15, 88); 18 | List sorted = mergeSortRecursive.mergeSort(); 19 | 20 | assertEquals(expected, sorted); 21 | } 22 | 23 | @Test 24 | void testMergeSortRecursiveCase2() { 25 | MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); 26 | 27 | List expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); 28 | List sorted = mergeSortRecursive.mergeSort(); 29 | 30 | assertEquals(expected, sorted); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/MergeSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class MergeSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new MergeSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Tabbygray (https://github.com/Tabbygray) 5 | * @see OddEvenSort 6 | */ 7 | 8 | public class OddEvenSortTest extends SortingAlgorithmTest { 9 | private final OddEvenSort oddEvenSort = new OddEvenSort(); 10 | 11 | @Override 12 | SortAlgorithm getSortAlgorithm() { 13 | return oddEvenSort; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/QuickSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Akshay Dubey (https://github.com/itsAkshayDubey) 5 | * @see QuickSort 6 | */ 7 | class QuickSortTest extends SortingAlgorithmTest { 8 | @Override 9 | SortAlgorithm getSortAlgorithm() { 10 | return new QuickSort(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SelectionSortRecursiveTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new SelectionSortRecursive(); 7 | } 8 | 9 | protected int getGeneratedArraySize() { 10 | return 5000; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/SelectionSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class SelectionSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new SelectionSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.RepeatedTest; 6 | import org.junit.jupiter.api.Test; 7 | 8 | class SortUtilsRandomGeneratorTest { 9 | 10 | @RepeatedTest(1000) 11 | void generateArray() { 12 | int size = 1_000; 13 | Double[] doubles = SortUtilsRandomGenerator.generateArray(size); 14 | assertThat(doubles).hasSize(size); 15 | assertThat(doubles).doesNotContainNull(); 16 | } 17 | 18 | @Test 19 | void generateArrayEmpty() { 20 | int size = 0; 21 | Double[] doubles = SortUtilsRandomGenerator.generateArray(size); 22 | assertThat(doubles).hasSize(size); 23 | } 24 | 25 | @RepeatedTest(1000) 26 | void generateDouble() { 27 | Double randomDouble = SortUtilsRandomGenerator.generateDouble(); 28 | assertThat(randomDouble).isBetween(0.0, 1.0); 29 | assertThat(randomDouble).isNotEqualTo(1.0); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/StrandSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class StrandSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new StrandSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/SwapSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SwapSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new SwapSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/TimSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class TimSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new TimSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/AlphabeticalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class AlphabeticalTest { 9 | 10 | @Test 11 | public void isAlphabetical() { 12 | // expected to be true 13 | String input1 = "abcdefghijklmno"; 14 | String input2 = "abcdxxxyzzzz"; 15 | String input3 = "fpw"; 16 | 17 | // expected to be false 18 | String input4 = "123a"; 19 | String input5 = "abcABC"; 20 | String input6 = "abcdefghikjlmno"; 21 | 22 | assertTrue(Alphabetical.isAlphabetical(input1)); 23 | assertTrue(Alphabetical.isAlphabetical(input2)); 24 | assertTrue(Alphabetical.isAlphabetical(input3)); 25 | 26 | assertFalse(Alphabetical.isAlphabetical(input4)); 27 | assertFalse(Alphabetical.isAlphabetical(input5)); 28 | assertFalse(Alphabetical.isAlphabetical(input6)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/AnagramsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertTrue; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class AnagramsTest { 8 | 9 | @Test 10 | public void isAlphabetical() { 11 | String input1 = "late"; 12 | Anagrams anagrams = new Anagrams(); 13 | assertTrue(anagrams.approach1(input1, "tale")); 14 | assertTrue(anagrams.approach1(input1, "teal")); 15 | assertTrue(anagrams.approach2(input1, "tale")); 16 | assertTrue(anagrams.approach2(input1, "teal")); 17 | assertTrue(anagrams.approach3(input1, "tale")); 18 | assertTrue(anagrams.approach3(input1, "teal")); 19 | assertTrue(anagrams.approach4(input1, "tale")); 20 | assertTrue(anagrams.approach4(input1, "teal")); 21 | assertTrue(anagrams.approach5(input1, "teal")); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/CharacterSameTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class CharacterSameTest { 9 | 10 | @Test 11 | public void isAllCharactersSame() { 12 | String input1 = "aaa"; 13 | String input2 = "abc"; 14 | String input3 = "1 1 1 1"; 15 | String input4 = "111"; 16 | String input5 = ""; 17 | String input6 = " "; 18 | String input7 = ". "; 19 | 20 | assertTrue(CharactersSame.isAllCharactersSame(input1)); 21 | assertFalse(CharactersSame.isAllCharactersSame(input2)); 22 | assertFalse(CharactersSame.isAllCharactersSame(input3)); 23 | assertTrue(CharactersSame.isAllCharactersSame(input4)); 24 | assertTrue(CharactersSame.isAllCharactersSame(input5)); 25 | assertTrue(CharactersSame.isAllCharactersSame(input6)); 26 | assertFalse(CharactersSame.isAllCharactersSame(input7)); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/CheckVowelsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class CheckVowelsTest { 9 | 10 | @Test 11 | public void isVowel() { 12 | assertTrue(CheckVowels.hasVowels("foo")); 13 | assertTrue(CheckVowels.hasVowels("bar")); 14 | assertFalse(CheckVowels.hasVowels("why")); 15 | assertFalse(CheckVowels.hasVowels("myths")); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/HammingDistanceTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class HammingDistanceTest { 9 | 10 | @Test 11 | void testHammingDistance() throws Exception { 12 | assertEquals(HammingDistance.calculateHammingDistance("", ""), 0); 13 | assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0); 14 | assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3); 15 | assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4); 16 | assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5); 17 | } 18 | 19 | @Test 20 | void testNotEqualStringLengths() { 21 | Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc")); 22 | assertEquals("String lengths must be equal", exception.getMessage()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/IsomorphicTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public final class IsomorphicTest { 9 | private IsomorphicTest() { 10 | } 11 | 12 | @Test 13 | public static void main(String[] args) { 14 | String str1 = "abbbbaac"; 15 | String str2 = "kffffkkd"; 16 | 17 | String str3 = "xyxyxy"; 18 | String str4 = "bnbnbn"; 19 | 20 | String str5 = "ghjknnmm"; 21 | String str6 = "wertpopo"; 22 | 23 | String str7 = "aaammmnnn"; 24 | String str8 = "ggghhhbbj"; 25 | 26 | assertTrue(Isomorphic.checkStrings(str1, str2)); 27 | assertTrue(Isomorphic.checkStrings(str3, str4)); 28 | assertFalse(Isomorphic.checkStrings(str5, str6)); 29 | assertFalse(Isomorphic.checkStrings(str7, str8)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/LongestNonRepeativeSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class LongestNonRepeativeSubstringTest { 7 | 8 | @Test 9 | public void palindrome() { 10 | String input1 = "HelloWorld"; 11 | String input2 = "javaIsAProgrammingLanguage"; 12 | Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5); 13 | Assertions.assertEquals(LongestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/LowerTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class LowerTest { 8 | @Test 9 | public void toLowerCase() { 10 | String input1 = "hello world"; 11 | String input2 = "HelLO WoRld"; 12 | String input3 = "HELLO WORLD"; 13 | 14 | assertEquals("hello world", Lower.toLowerCase(input1)); 15 | assertEquals("hello world", Lower.toLowerCase(input2)); 16 | assertEquals("hello world", Lower.toLowerCase(input3)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/MyAtoiTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MyAtoiTest { 8 | 9 | @Test 10 | void testOne() { 11 | assertEquals(42, MyAtoi.myAtoi("42")); 12 | } 13 | 14 | @Test 15 | void testTwo() { 16 | assertEquals(-42, MyAtoi.myAtoi(" -42")); 17 | } 18 | 19 | @Test 20 | void testThree() { 21 | assertEquals(4193, MyAtoi.myAtoi("4193 with words")); 22 | } 23 | 24 | @Test 25 | void testFour() { 26 | assertEquals(0, MyAtoi.myAtoi("0")); 27 | } 28 | 29 | @Test 30 | void testFive() { 31 | assertEquals(5678, MyAtoi.myAtoi("5678")); 32 | } 33 | 34 | @Test 35 | void testSix() { 36 | assertEquals(42, MyAtoi.myAtoi("+42")); 37 | } 38 | 39 | @Test 40 | void testSeven() { 41 | assertEquals(0, MyAtoi.myAtoi(" +0 ")); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/PalindromeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PalindromeTest { 7 | 8 | @Test 9 | public void palindrome() { 10 | 11 | String[] palindromes = {null, "", "aba", "123321", "kayak"}; 12 | for (String s : palindromes) { 13 | Assertions.assertTrue(Palindrome.isPalindrome(s) && Palindrome.isPalindromeRecursion(s) && Palindrome.isPalindromeTwoPointer(s)); 14 | } 15 | 16 | String[] notPalindromes = {"abb", "abc", "abc123", "kayaks"}; 17 | for (String s : notPalindromes) { 18 | Assertions.assertFalse(Palindrome.isPalindrome(s) || Palindrome.isPalindromeRecursion(s) || Palindrome.isPalindromeTwoPointer(s)); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class ReverseStringRecursiveTest { 8 | @Test 9 | void shouldAcceptWhenEmptyStringIsPassed() { 10 | String expected = ""; 11 | String reversed = ReverseStringRecursive.reverse(""); 12 | 13 | assertEquals(expected, reversed); 14 | } 15 | 16 | @Test 17 | void shouldAcceptNotWhenWhenSingleCharacterIsPassed() { 18 | String expected = "a"; 19 | String reversed = ReverseStringRecursive.reverse("a"); 20 | 21 | assertEquals(expected, reversed); 22 | } 23 | 24 | @Test 25 | void shouldAcceptWhenStringIsPassed() { 26 | String expected = "dlroWolleH"; 27 | String reversed = ReverseStringRecursive.reverse("HelloWorld"); 28 | 29 | assertEquals(expected, reversed); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.stream.Stream; 4 | import org.junit.jupiter.api.Assertions; 5 | import org.junit.jupiter.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.Arguments; 7 | import org.junit.jupiter.params.provider.MethodSource; 8 | 9 | public class ReverseWordsInStringTest { 10 | @ParameterizedTest 11 | @MethodSource("inputStream") 12 | void numberTests(String expected, String input) { 13 | Assertions.assertEquals(expected, ReverseWordsInString.reverseWordsInString(input)); 14 | } 15 | 16 | private static Stream inputStream() { 17 | return Stream.of(Arguments.of("blue is Sky", "Sky is blue"), Arguments.of("blue is Sky", "Sky \n is \t \n blue "), Arguments.of("", ""), Arguments.of("", " "), Arguments.of("", "\t")); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/RotationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class RotationTest { 8 | 9 | @Test 10 | public void testRotation() { 11 | assertEquals("eksge", Rotation.rotation("geeks", 2)); 12 | assertEquals("anasban", Rotation.rotation("bananas", 3)); 13 | assertEquals("abracadabra", Rotation.rotation("abracadabra", 0)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/StringCompressionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | import static org.junit.jupiter.api.Assertions.assertEquals; 3 | 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.CsvSource; 6 | 7 | public class StringCompressionTest { 8 | @ParameterizedTest 9 | @CsvSource({"a,a", "aabbb,a2b3", "abbbc,ab3c", "aabccd,a2bc2d"}) 10 | void stringCompressionTest(String input, String expectedOutput) { 11 | String output = StringCompression.compress(input); 12 | assertEquals(expectedOutput, output); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/UpperTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class UpperTest { 8 | 9 | @Test 10 | public void toUpperCase() { 11 | String input1 = "hello world"; 12 | String input2 = "hElLo WoRlD"; 13 | String input3 = "HELLO WORLD"; 14 | assertEquals("HELLO WORLD", Upper.toUpperCase(input1)); 15 | assertEquals("HELLO WORLD", Upper.toUpperCase(input2)); 16 | assertEquals("HELLO WORLD", Upper.toUpperCase(input3)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertFalse; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | public class ValidParenthesesTest { 9 | 10 | @Test 11 | void testOne() { 12 | assertTrue(ValidParentheses.isValid("()")); 13 | } 14 | 15 | @Test 16 | void testTwo() { 17 | assertTrue(ValidParentheses.isValid("()[]{}")); 18 | } 19 | 20 | @Test 21 | void testThree() { 22 | assertFalse(ValidParentheses.isValid("(]")); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings.zigZagPattern; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class ZigZagPatternTest { 7 | 8 | @Test 9 | public void palindrome() { 10 | String input1 = "HelloWorldFromJava"; 11 | String input2 = "javaIsAProgrammingLanguage"; 12 | Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda"); 13 | Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig"); 14 | } 15 | } 16 | --------------------------------------------------------------------------------