├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── config.yml │ └── other.yml ├── workflows │ ├── clang-format-lint.yml │ └── codeql.yml └── dependabot.yml ├── .gitpod.yml ├── src ├── test │ └── java │ │ └── com │ │ └── thealgorithms │ │ ├── sorts │ │ ├── TimSortTest.java │ │ ├── CircleSortTest.java │ │ ├── CombSortTest.java │ │ ├── CycleSortTest.java │ │ ├── HeapSortTest.java │ │ ├── MergeSortTest.java │ │ ├── ShellSortTest.java │ │ ├── StrandSortTest.java │ │ ├── SwapSortTest.java │ │ ├── BucketSortTest.java │ │ ├── SelectionSortTest.java │ │ ├── SimpleSortTest.java │ │ ├── BitonicSortTest.java │ │ ├── ExchangeSortTest.java │ │ ├── PancakeSortTest.java │ │ ├── PatienceSortTest.java │ │ ├── DualPivotQuickSortTest.java │ │ ├── IntrospectiveSortTest.java │ │ ├── BubbleSortRecursiveTest.java │ │ ├── CocktailShakerSortTest.java │ │ ├── StoogeSortTest.java │ │ ├── QuickSortTest.java │ │ ├── BinaryInsertionSortTest.java │ │ ├── SelectionSortRecursiveTest.java │ │ ├── OddEvenSortTest.java │ │ └── SortUtilsRandomGeneratorTest.java │ │ ├── maths │ │ ├── MaxValueTest.java │ │ ├── MinValueTest.java │ │ ├── JosephusProblemTest.java │ │ ├── TestArmstrong.java │ │ ├── BinaryPowTest.java │ │ ├── CeilTest.java │ │ ├── AbsoluteValueTest.java │ │ ├── BinomialCoefficientTest.java │ │ ├── DigitalRootTest.java │ │ ├── PowerUsingRecursionTest.java │ │ ├── SquareRootWithNewtonRaphsonTestMethod.java │ │ ├── StandardScoreTest.java │ │ ├── AliquotSumTest.java │ │ ├── SquareRootwithBabylonianMethodTest.java │ │ ├── PerfectNumberTest.java │ │ ├── StrobogrammaticNumberTest.java │ │ ├── ArmstrongTest.java │ │ ├── GaussianTest.java │ │ ├── PronicNumberTest.java │ │ ├── FloorTest.java │ │ ├── HarshadNumberTest.java │ │ ├── PowerOfTwoOrNotTest.java │ │ ├── ReverseNumberTest.java │ │ ├── LeonardoNumberTest.java │ │ ├── LucasSeriesTest.java │ │ ├── AbsoluteMinTest.java │ │ ├── LeastCommonMultipleTest.java │ │ ├── FactorialTest.java │ │ ├── PythagoreanTripleTest.java │ │ ├── MedianTest.java │ │ ├── PerfectSquareTest.java │ │ ├── ModeTest.java │ │ ├── prime │ │ │ └── PrimeCheckTest.java │ │ ├── CombinationsTest.java │ │ ├── DudeneyNumberTest.java │ │ ├── FrizzyNumberTest.java │ │ ├── AverageTest.java │ │ ├── FactorialRecursionTest.java │ │ ├── GenericRootTest.java │ │ ├── StandardDeviationTest.java │ │ └── AbsoluteMaxTest.java │ │ ├── bitmanipulation │ │ ├── BitSwapTest.java │ │ ├── IsEvenTest.java │ │ ├── FirstDifferentBitTest.java │ │ ├── OneBitDifferenceTest.java │ │ ├── ParityCheckTest.java │ │ ├── ClearLeftmostSetBitTest.java │ │ ├── IndexOfRightMostSetBitTest.java │ │ ├── CountLeadingZerosTest.java │ │ ├── NextHigherSameBitCountTest.java │ │ ├── HammingDistanceTest.java │ │ ├── BinaryPalindromeCheckTest.java │ │ └── CountSetBitsTest.java │ │ ├── dynamicprogramming │ │ ├── CatalanNumberTest.java │ │ ├── UniqueSubsequencesCountTest.java │ │ ├── ShortestCommonSupersequenceLengthTest.java │ │ ├── SumOfSubsetTest.java │ │ ├── EggDroppingTest.java │ │ ├── SubsetSumSpaceOptimizedTest.java │ │ ├── ClimbStairsTest.java │ │ ├── PartitionProblemTest.java │ │ ├── SubsetCountTest.java │ │ ├── PalindromicPartitioningTest.java │ │ ├── TribonacciTest.java │ │ ├── WildcardMatchingTest.java │ │ └── LongestPalindromicSubstringTest.java │ │ ├── divideandconquer │ │ ├── TilingProblemTest.java │ │ └── CountingInversionsTest.java │ │ ├── strings │ │ ├── RotationTest.java │ │ ├── LowerTest.java │ │ ├── UpperTest.java │ │ ├── CheckVowelsTest.java │ │ ├── CharacterSameTest.java │ │ ├── StringCompressionTest.java │ │ ├── ReverseStringRecursiveTest.java │ │ ├── ValidParenthesesTest.java │ │ ├── ReverseWordsInStringTest.java │ │ ├── zigZagPattern │ │ │ └── ZigZagPatternTest.java │ │ ├── IsomorphicTest.java │ │ ├── LongestPalindromicSubstringTest.java │ │ ├── CountCharTest.java │ │ ├── AlphabeticalTest.java │ │ ├── PalindromeTest.java │ │ ├── ReturnSubsequenceTest.java │ │ └── LongestNonRepetitiveSubstringTest.java │ │ ├── others │ │ ├── CRC16Test.java │ │ └── CRCAlgorithmTest.java │ │ ├── greedyalgorithms │ │ ├── KCentersTest.java │ │ ├── JobSequencingTest.java │ │ ├── MinimumWaitingTimeTest.java │ │ ├── StockProfitCalculatorTest.java │ │ ├── EgyptianFractionTest.java │ │ ├── FractionalKnapsackTest.java │ │ └── BandwidthAllocationTest.java │ │ ├── searches │ │ ├── HowManyTimesRotatedTest.java │ │ ├── SortOrderAgnosticBinarySearchTest.java │ │ ├── RabinKarpAlgorithmTest.java │ │ └── TestSearchInARowAndColWiseSortedMatrix.java │ │ ├── datastructures │ │ └── heaps │ │ │ ├── MedianFinderTest.java │ │ │ └── KthElementFinderTest.java │ │ ├── conversions │ │ ├── DecimalToHexadecimalTest.java │ │ ├── MorseCodeConverterTest.java │ │ ├── DecimalToOctalTest.java │ │ ├── BinaryToHexadecimalTest.java │ │ ├── DecimalToBinaryTest.java │ │ ├── AnyBaseToDecimalTest.java │ │ ├── DecimalToAnyBaseTest.java │ │ └── OctalToDecimalTest.java │ │ ├── geometry │ │ └── GrahamScanTest.java │ │ ├── misc │ │ └── MapReduceTest.java │ │ ├── backtracking │ │ ├── PowerSumTest.java │ │ ├── PermutationTest.java │ │ └── WordSearchTest.java │ │ ├── ciphers │ │ ├── AutokeyTest.java │ │ ├── BaconianCipherTest.java │ │ ├── BlowfishTest.java │ │ └── HillCipherTest.java │ │ ├── stacks │ │ ├── PrefixEvaluatorTest.java │ │ ├── PostfixEvaluatorTest.java │ │ └── DuplicateBracketsTest.java │ │ ├── matrix │ │ ├── MedianOfMatrixTest.java │ │ └── TestPrintMatrixInSpiralOrder.java │ │ └── slidingwindow │ │ ├── LongestSubarrayWithSumLessOrEqualToKTest.java │ │ └── LongestSubstringWithoutRepeatingCharactersTest.java └── main │ └── java │ └── com │ └── thealgorithms │ ├── misc │ ├── MedianOfRunningArrayLong.java │ ├── MedianOfRunningArrayByte.java │ ├── MedianOfRunningArrayFloat.java │ ├── MedianOfRunningArrayDouble.java │ └── MedianOfRunningArrayInteger.java │ ├── maths │ ├── StandardScore.java │ ├── AbsoluteValue.java │ ├── FactorialRecursion.java │ ├── MaxValue.java │ ├── MinValue.java │ ├── StandardDeviation.java │ ├── Factorial.java │ ├── Median.java │ ├── SquareRootWithBabylonianMethod.java │ ├── Ceil.java │ ├── PowerOfTwoOrNot.java │ ├── Floor.java │ ├── SumOfOddNumbers.java │ ├── PowerUsingRecursion.java │ ├── BinaryPow.java │ ├── LeonardoNumber.java │ ├── FindMin.java │ ├── FindMax.java │ ├── SumWithoutArithmeticOperators.java │ ├── ReverseNumber.java │ ├── PalindromeNumber.java │ ├── AbsoluteMin.java │ ├── GenericRoot.java │ ├── AbsoluteMax.java │ ├── Prime │ │ └── PrimeFactorization.java │ ├── FrizzyNumber.java │ ├── PerfectSquare.java │ ├── GCDRecursion.java │ ├── PerfectCube.java │ ├── CatalanNumbers.java │ └── LucasSeries.java │ ├── ciphers │ └── a5 │ │ ├── BaseLFSR.java │ │ └── Utils.java │ ├── bitmanipulation │ ├── IsEven.java │ ├── BitSwap.java │ ├── ModuloPowerOfTwo.java │ ├── OneBitDifference.java │ ├── HammingDistance.java │ ├── FirstDifferentBit.java │ ├── OnesComplement.java │ ├── NextHigherSameBitCount.java │ └── NumbersDifferentSigns.java │ ├── sorts │ ├── SimpleSort.java │ ├── GnomeSort.java │ ├── SlowSort.java │ ├── StalinSort.java │ ├── SortAlgorithm.java │ ├── SelectionSort.java │ ├── BubbleSort.java │ ├── StoogeSort.java │ └── BubbleSortRecursive.java │ ├── datastructures │ ├── heaps │ │ └── EmptyHeapException.java │ ├── hashmap │ │ └── hashing │ │ │ └── Map.java │ ├── disjointsetunion │ │ └── Node.java │ ├── Node.java │ ├── lists │ │ └── CountSinglyLinkedListRecursion.java │ └── trees │ │ └── FenwickTree.java │ ├── strings │ ├── ReverseStringRecursive.java │ ├── CountChar.java │ ├── ReverseWordsInString.java │ ├── LongestCommonPrefix.java │ ├── CharactersSame.java │ ├── Lower.java │ ├── CheckVowels.java │ └── ReverseString.java │ ├── devutils │ ├── searches │ │ ├── SearchAlgorithm.java │ │ └── MatrixSearchAlgorithm.java │ └── nodes │ │ └── Node.java │ ├── recursion │ ├── FibonacciSeries.java │ └── GenerateSubsets.java │ ├── others │ ├── FloydTriangle.java │ ├── CRC16.java │ ├── Krishnamurthy.java │ ├── cn │ │ └── HammingDistance.java │ ├── CRC32.java │ └── RemoveDuplicateFromString.java │ ├── lineclipping │ └── utils │ │ ├── Point.java │ │ └── Line.java │ ├── matrix │ └── MedianOfMatrix.java │ ├── searches │ ├── DepthFirstSearch.java │ └── SearchInARowAndColWiseSortedMatrix.java │ └── dynamicprogramming │ └── Tribonacci.java ├── .gitpod.dockerfile ├── .gitignore └── LICENSE /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @yanglbme @vil02 @BamaCharanChhandogi @alxkm @siriak 2 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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/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/CombSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class CombSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new CombSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/CycleSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class CycleSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new CycleSort(); 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/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/ShellSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class ShellSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new ShellSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /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/BucketSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class BucketSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new BucketSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /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/SimpleSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SimpleSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new SimpleSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /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/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/PancakeSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class PancakeSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new PancakeSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/PatienceSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class PatienceSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new PatienceSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | class DualPivotQuickSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new DualPivotQuickSort(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class IntrospectiveSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new IntrospectiveSort(); 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/CocktailShakerSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class CocktailShakerSortTest extends SortingAlgorithmTest { 4 | @Override 5 | SortAlgorithm getSortAlgorithm() { 6 | return new CocktailShakerSort(); 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/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/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/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/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/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/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/test/java/com/thealgorithms/sorts/StoogeSortTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class StoogeSortTest extends SortingAlgorithmTest { 4 | protected int getGeneratedArraySize() { 5 | return 1000; 6 | } 7 | 8 | @Override 9 | SortAlgorithm getSortAlgorithm() { 10 | return new StoogeSort(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /.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.18 13 | with: 14 | source: './src' 15 | extensions: 'java' 16 | clangFormatVersion: 16 17 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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/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/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/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/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/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/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/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/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/test/java/com/thealgorithms/divideandconquer/TilingProblemTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.divideandconquer; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class TilingProblemTest { 8 | 9 | @Test 10 | public void testTilingSize2() { 11 | int[][] expected = {{1, 1}, {1, 0}}; 12 | int[][] result = TilingProblem.solveTiling(2, 1, 1); 13 | assertArrayEquals(expected, result); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/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/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/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/main/java/com/thealgorithms/sorts/SimpleSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SimpleSort implements SortAlgorithm { 4 | @Override 5 | public > T[] sort(T[] array) { 6 | for (int i = 0; i < array.length; i++) { 7 | for (int j = i + 1; j < array.length; j++) { 8 | if (SortUtils.less(array[j], array[i])) { 9 | SortUtils.swap(array, i, j); 10 | } 11 | } 12 | } 13 | return array; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.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 KCentersTest { 8 | 9 | @Test 10 | public void testFindKCenters() { 11 | int[][] distances = {{0, 2, 3, 4}, {2, 0, 5, 1}, {3, 5, 0, 7}, {4, 1, 7, 0}}; 12 | assertEquals(4, KCenters.findKCenters(distances, 2)); 13 | assertEquals(2, KCenters.findKCenters(distances, 4)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/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/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/datastructures/heaps/MedianFinderTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class MedianFinderTest { 8 | @Test 9 | public void testMedianMaintenance() { 10 | MedianFinder mf = new MedianFinder(); 11 | mf.addNum(1); 12 | mf.addNum(2); 13 | assertEquals(1.5, mf.findMedian()); 14 | mf.addNum(3); 15 | assertEquals(2.0, mf.findMedian()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /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/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/strings/ReverseStringRecursive.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using Recursion 5 | */ 6 | public final class ReverseStringRecursive { 7 | private ReverseStringRecursive() { 8 | } 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/test/java/com/thealgorithms/bitmanipulation/FirstDifferentBitTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 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 | public class FirstDifferentBitTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"10, 8, 1", "7, 5, 1", "15, 14, 0", "1, 2, 0"}) 12 | void testFirstDifferentBit(int x, int y, int expected) { 13 | assertEquals(expected, FirstDifferentBit.firstDifferentBit(x, y)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/bitmanipulation/OneBitDifferenceTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 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 | public class OneBitDifferenceTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"7, 5, true", "3, 2, true", "10, 8, true", "15, 15, false", "4, 1, false"}) 12 | void testDifferByOneBit(int x, int y, boolean expected) { 13 | assertEquals(expected, OneBitDifference.differByOneBit(x, y)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.CsvSource; 7 | 8 | public class DecimalToHexadecimalTest { 9 | @ParameterizedTest 10 | @CsvSource({"0, 0", "1, 1", "10, a", "15, f", "16, 10", "255, ff", "190, be", "1800, 708"}) 11 | void testDecToHex(int decimal, String expectedHex) { 12 | assertEquals(expectedHex, DecimalToHexadecimal.decToHex(decimal)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /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/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/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/bitmanipulation/ParityCheckTest.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 | public class ParityCheckTest { 9 | @Test 10 | public void testIsOddParity() { 11 | assertTrue(ParityCheck.checkParity(5)); // 101 has 2 ones (even parity) 12 | assertFalse(ParityCheck.checkParity(7)); // 111 has 3 ones (odd parity) 13 | assertFalse(ParityCheck.checkParity(8)); // 1000 has 1 one (odd parity) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/strings/CheckVowelsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 CheckVowelsTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"'foo', true", "'bar', true", "'why', false", "'myths', false", "'', false", "'AEIOU', true", "'bcdfghjklmnpqrstvwxyz', false", "'AeIoU', true"}) 12 | void testHasVowels(String input, boolean expected) { 13 | assertEquals(CheckVowels.hasVowels(input), expected); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.gitpod.dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-java-21:2024-11-26-08-43-19 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 | -------------------------------------------------------------------------------- /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/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/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/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/datastructures/heaps/KthElementFinderTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class KthElementFinderTest { 8 | @Test 9 | public void testFindKthLargest() { 10 | int[] nums = {3, 2, 1, 5, 6, 4}; 11 | assertEquals(5, KthElementFinder.findKthLargest(nums, 2)); 12 | } 13 | 14 | @Test 15 | public void testFindKthSmallest() { 16 | int[] nums = {7, 10, 4, 3, 20, 15}; 17 | assertEquals(7, KthElementFinder.findKthSmallest(nums, 3)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /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/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/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/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 | Point[] points = {new Point(0, 3), new Point(1, 1), new Point(2, 2), new Point(4, 4), new Point(0, 0), new Point(1, 2), new Point(3, 1), new 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/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/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/test/java/com/thealgorithms/conversions/MorseCodeConverterTest.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 MorseCodeConverterTest { 8 | 9 | @Test 10 | public void testTextToMorse() { 11 | assertEquals(".- -...", MorseCodeConverter.textToMorse("AB")); 12 | assertEquals(".... . .-.. .-.. --- | .-- --- .-. .-.. -..", MorseCodeConverter.textToMorse("HELLO WORLD")); 13 | } 14 | 15 | @Test 16 | public void testMorseToText() { 17 | assertEquals("AB", MorseCodeConverter.morseToText(".- -...")); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCountTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 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 | public class UniqueSubsequencesCountTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"abc, 7", "abcdashgdhas, 3592", "a, 1", "'a b', 7", "a1b2, 15", "AaBb, 15", "abab, 11"}) 12 | void subseqCountParameterizedTest(String input, int expected) { 13 | assertEquals(expected, UniqueSubsequencesCount.countSubseq(input)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public final class CountChar { 4 | private CountChar() { 5 | } 6 | 7 | /** 8 | * Counts the number of non-whitespace characters in the given string. 9 | * 10 | * @param str the input string to count the characters in 11 | * @return the number of non-whitespace characters in the specified string; 12 | * returns 0 if the input string is null 13 | */ 14 | public static int countCharacters(String str) { 15 | if (str == null) { 16 | return 0; 17 | } 18 | return str.replaceAll("\\s", "").length(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /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/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/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/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 | public static String reverseWordsInString(final String s) { 17 | var words = s.trim().split("\\s+"); 18 | Collections.reverse(Arrays.asList(words)); 19 | return String.join(" ", words); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBitTest.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 | public class ClearLeftmostSetBitTest { 8 | 9 | @Test 10 | public void testClearLeftmostSetBit() { 11 | assertEquals(10, ClearLeftmostSetBit.clearLeftmostSetBit(26)); // 11010 -> 01010 12 | assertEquals(0, ClearLeftmostSetBit.clearLeftmostSetBit(1)); // 1 -> 0 13 | assertEquals(3, ClearLeftmostSetBit.clearLeftmostSetBit(7)); // 111 -> 011 14 | assertEquals(2, ClearLeftmostSetBit.clearLeftmostSetBit(6)); // 0110 -> 0010 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /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/main/java/com/thealgorithms/recursion/FibonacciSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.recursion; 2 | 3 | /* 4 | The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, 5 | starting with 0 and 1. 6 | NUMBER 0 1 2 3 4 5 6 7 8 9 10 ... 7 | FIBONACCI 0 1 1 2 3 5 8 13 21 34 55 ... 8 | */ 9 | 10 | public final class FibonacciSeries { 11 | private FibonacciSeries() { 12 | throw new UnsupportedOperationException("Utility class"); 13 | } 14 | public static int fibonacci(int n) { 15 | if (n <= 1) { 16 | return n; 17 | } else { 18 | return fibonacci(n - 1) + fibonacci(n - 2); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/LongestCommonPrefix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | 5 | public final class LongestCommonPrefix { 6 | public String longestCommonPrefix(String[] strs) { 7 | if (strs == null || strs.length == 0) { 8 | return ""; 9 | } 10 | 11 | Arrays.sort(strs); 12 | String shortest = strs[0]; 13 | String longest = strs[strs.length - 1]; 14 | 15 | int index = 0; 16 | while (index < shortest.length() && index < longest.length() && shortest.charAt(index) == longest.charAt(index)) { 17 | index++; 18 | } 19 | 20 | return shortest.substring(0, index); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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/dynamicprogramming/ShortestCommonSupersequenceLengthTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 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 | public class ShortestCommonSupersequenceLengthTest { 9 | @ParameterizedTest 10 | @CsvSource({"AGGTAB, GXTXAYB, 9", "ABC, ABC, 3", "ABC, DEF, 6", "'', ABC, 3", "ABCD, AB, 4", "ABC, BCD, 4", "A, B, 2"}) 11 | void testShortestSupersequence(String input1, String input2, int expected) { 12 | assertEquals(expected, ShortestCommonSupersequenceLength.shortestSuperSequence(input1, input2)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * This program calculates the sum of the first n odd numbers. 5 | * 6 | * https://www.cuemath.com/algebra/sum-of-odd-numbers/ 7 | */ 8 | 9 | public final class SumOfOddNumbers { 10 | private SumOfOddNumbers() { 11 | } 12 | 13 | /** 14 | * Calculate sum of the first n odd numbers 15 | * 16 | * @param n the number of odd numbers to sum 17 | * @return sum of the first n odd numbers 18 | */ 19 | public static int sumOfFirstNOddNumbers(final int n) { 20 | if (n < 0) { 21 | throw new IllegalArgumentException("n must be non-negative."); 22 | } 23 | return n * n; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /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/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/test/java/com/thealgorithms/strings/CharacterSameTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 CharactersSameTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"aaa, true", "abc, false", "'1 1 1 1', false", "111, true", "'', true", "' ', true", "'. ', false", "'a', true", "' ', true", "'ab', false", "'11111', true", "'ababab', false", "' ', true", "'+++', true"}) 12 | void testIsAllCharactersSame(String input, boolean expected) { 13 | assertEquals(CharactersSame.isAllCharactersSame(input), expected); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/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/test/java/com/thealgorithms/bitmanipulation/CountLeadingZerosTest.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 | public class CountLeadingZerosTest { 8 | 9 | @Test 10 | public void testCountLeadingZeros() { 11 | assertEquals(29, CountLeadingZeros.countLeadingZeros(5)); // 000...0101 has 29 leading zeros 12 | assertEquals(32, CountLeadingZeros.countLeadingZeros(0)); // 000...0000 has 32 leading zeros 13 | assertEquals(31, CountLeadingZeros.countLeadingZeros(1)); // 000...0001 has 31 leading zeros 14 | assertEquals(0, CountLeadingZeros.countLeadingZeros(-1)); // No leading zeros in negative number (-1) 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCountTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 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 NextHigherSameBitCountTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({ 12 | "5, 6", // 101 -> 110 13 | "7, 11", // 0111 -> 1011 14 | "3, 5", // 011 -> 101 15 | "12, 17", // 001100 -> 010001 16 | "15, 23" // 01111 -> 10111 17 | }) 18 | void 19 | testNextHigherSameBitCount(int input, int expected) { 20 | assertEquals(expected, NextHigherSameBitCount.nextHigherSameBitCount(input)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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/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/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/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/main/java/com/thealgorithms/sorts/GnomeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * Implementation of gnome sort 5 | * 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | * @since 2018-04-10 8 | */ 9 | public class GnomeSort implements SortAlgorithm { 10 | 11 | @Override 12 | public > T[] sort(final T[] array) { 13 | int i = 1; 14 | int j = 2; 15 | while (i < array.length) { 16 | if (SortUtils.less(array[i - 1], array[i])) { 17 | i = j++; 18 | } else { 19 | SortUtils.swap(array, i - 1, i); 20 | if (--i == 0) { 21 | i = j++; 22 | } 23 | } 24 | } 25 | 26 | return array; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/strings/StringCompressionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 | public class StringCompressionTest { 9 | @ParameterizedTest 10 | @CsvSource({"'a', 'a'", "'aabbb', 'a2b3'", "'abbbc', 'ab3c'", "'aabccd', 'a2bc2d'", "'aaaabbbcccc', 'a4b3c4'", "'abcd', 'abcd'", "'aabbccdd', 'a2b2c2d2'", "'aaabbaa', 'a3b2a2'", "'', ''", "'a', 'a'", "'aaaaa', 'a5'", "'aabb', 'a2b2'", "'aabbbaaa', 'a2b3a3'", "'qwerty', 'qwerty'"}) 11 | void stringCompressionTest(String input, String expectedOutput) { 12 | String output = StringCompression.compress(input); 13 | assertEquals(expectedOutput, output); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /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/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/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/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/test/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimizedTest.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 | public class SubsetSumSpaceOptimizedTest { 9 | 10 | @Test 11 | void basicCheck() { 12 | assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {7, 3, 2, 5, 8}, 14)); 13 | assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {4, 3, 2, 1}, 5)); 14 | assertTrue(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 7, 2, 9, 10}, 13)); 15 | assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {1, 2, 7, 10, 9}, 14)); 16 | assertFalse(SubsetSumSpaceOptimized.isSubsetSum(new int[] {2, 15, 1, 6, 7}, 4)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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.params.ParameterizedTest; 6 | import org.junit.jupiter.params.provider.CsvSource; 7 | 8 | public class ReverseStringRecursiveTest { 9 | @ParameterizedTest 10 | @CsvSource({"'Hello World', 'dlroW olleH'", "'helloworld', 'dlrowolleh'", "'123456789', '987654321'", "'', ''", "'A', 'A'", "'!123 ABC xyz!', '!zyx CBA 321!'", "'Abc 123 Xyz', 'zyX 321 cbA'", "'12.34,56;78:90', '09:87;65,43.21'", "'abcdEFGHiJKL', 'LKJiHGFEdcba'", 11 | "'MixOf123AndText!', '!txeTdnA321fOxiM'"}) 12 | public void 13 | testReverseString(String input, String expectedOutput) { 14 | assertEquals(expectedOutput, ReverseStringRecursive.reverse(input)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /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 | assertTrue(ValidParentheses.isValidParentheses("()")); 14 | } 15 | 16 | @Test 17 | void testTwo() { 18 | assertTrue(ValidParentheses.isValid("()[]{}")); 19 | assertTrue(ValidParentheses.isValidParentheses("()[]{}")); 20 | } 21 | 22 | @Test 23 | void testThree() { 24 | assertFalse(ValidParentheses.isValid("(]")); 25 | assertFalse(ValidParentheses.isValidParentheses("(]")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/bitmanipulation/HammingDistanceTest.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 | public class HammingDistanceTest { 8 | 9 | @Test 10 | public void testHammingDistance() { 11 | assertEquals(3, HammingDistance.hammingDistance(9, 14)); // 1001 vs 1110, Hamming distance is 3 12 | assertEquals(0, HammingDistance.hammingDistance(10, 10)); // Same number, Hamming distance is 0 13 | assertEquals(1, HammingDistance.hammingDistance(1, 0)); // 0001 vs 0000, Hamming distance is 1 14 | assertEquals(2, HammingDistance.hammingDistance(4, 1)); // 100 vs 001, Hamming distance is 2 15 | assertEquals(4, HammingDistance.hammingDistance(0, 15)); // 0000 vs 1111, Hamming distance is 4 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /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/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/main/java/com/thealgorithms/sorts/StalinSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class StalinSort implements SortAlgorithm { 4 | @SuppressWarnings("unchecked") 5 | public > T[] sort(T[] array) { 6 | if (array.length == 0) { 7 | return array; 8 | } 9 | int currentIndex = 0; 10 | for (int i = 1; i < array.length; i++) { 11 | if (array[i].compareTo(array[currentIndex]) >= 0) { 12 | currentIndex++; 13 | array[currentIndex] = array[i]; 14 | } 15 | } 16 | // Create a result array with sorted elements 17 | T[] result = (T[]) java.lang.reflect.Array.newInstance(array.getClass().getComponentType(), currentIndex + 1); 18 | System.arraycopy(array, 0, result, 0, currentIndex + 1); 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheckTest.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 | public class BinaryPalindromeCheckTest { 9 | 10 | @Test 11 | public void testIsBinaryPalindrome() { 12 | assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(9)); // 1001 is a palindrome 13 | assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(10)); // 1010 is not a palindrome 14 | assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(0)); // 0 is a palindrome 15 | assertTrue(BinaryPalindromeCheck.isBinaryPalindrome(1)); // 1 is a palindrome 16 | assertFalse(BinaryPalindromeCheck.isBinaryPalindrome(12)); // 1100 is not a palindrome 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/DecimalToOctalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 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 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | class DecimalToOctalTest { 11 | @ParameterizedTest 12 | @CsvSource({"0, 0", "7, 7", "8, 10", "10, 12", "64, 100", "83, 123", "7026, 15562"}) 13 | void testConvertToOctal(int decimal, int expectedOctal) { 14 | assertEquals(expectedOctal, DecimalToOctal.convertToOctal(decimal)); 15 | } 16 | 17 | @Test 18 | void testConvertToOctalNegativeNumber() { 19 | assertThrows(IllegalArgumentException.class, () -> DecimalToOctal.convertToOctal(-10)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/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/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/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/conversions/BinaryToHexadecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 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.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.CsvSource; 8 | 9 | public class BinaryToHexadecimalTest { 10 | 11 | @ParameterizedTest 12 | @CsvSource({"0, 0", "1, 1", "10, 2", "1111, F", "1101010, 6A", "1100, C"}) 13 | void testBinToHex(int binary, String expectedHex) { 14 | assertEquals(expectedHex, BinaryToHexadecimal.binToHex(binary)); 15 | } 16 | 17 | @ParameterizedTest 18 | @CsvSource({"2", "1234", "11112"}) 19 | void testInvalidBinaryInput(int binary) { 20 | assertThrows(IllegalArgumentException.class, () -> BinaryToHexadecimal.binToHex(binary)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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 answer = new ArrayList(); 16 | answer.add(0.0); 17 | answer.add(1.0); 18 | 19 | int matrixSize = 2; 20 | list.add(1.0); 21 | list.add(1.0); 22 | list.add(1.0); 23 | list.add(2.0); 24 | list.add(1.0); 25 | list.add(1.0); 26 | 27 | assertEquals(answer, gaussian(matrixSize, list)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PronicNumberTest.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 PronicNumberTest { 8 | 9 | @ParameterizedTest 10 | @ValueSource(ints = {0, 2, 6, 12, 20, 30, 42, 110, 272, 380, 420, 1260, 2550}) 11 | void testForPronicNumber(final int number) { 12 | Assertions.assertTrue(PronicNumber.isPronic(number)); 13 | Assertions.assertTrue(PronicNumber.isPronicNumber(number)); 14 | } 15 | 16 | @ParameterizedTest 17 | @ValueSource(ints = {1, 4, 21, 36, 150, 2500}) 18 | void testForNonPronicNumber(final int number) { 19 | Assertions.assertFalse(PronicNumber.isPronic(number)); 20 | Assertions.assertFalse(PronicNumber.isPronicNumber(number)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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/strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public final class CharactersSame { 4 | private CharactersSame() { 5 | } 6 | 7 | /** 8 | * Checks if all characters in the string are the same. 9 | * 10 | * @param s the string to check 11 | * @return {@code true} if all characters in the string are the same or if the string is empty, otherwise {@code false} 12 | */ 13 | public static boolean isAllCharactersSame(String s) { 14 | if (s.isEmpty()) { 15 | return true; // Empty strings can be considered as having "all the same characters" 16 | } 17 | 18 | char firstChar = s.charAt(0); 19 | for (int i = 1; i < s.length(); i++) { 20 | if (s.charAt(i) != firstChar) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwo.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * This class provides a method to compute the remainder 5 | * of a number when divided by a power of two (2^n) 6 | * without using division or modulo operations. 7 | * 8 | * @author Hardvan 9 | */ 10 | public final class ModuloPowerOfTwo { 11 | private ModuloPowerOfTwo() { 12 | } 13 | 14 | /** 15 | * Computes the remainder of a given integer when divided by 2^n. 16 | * 17 | * @param x the input number 18 | * @param n the exponent (power of two) 19 | * @return the remainder of x divided by 2^n 20 | */ 21 | public static int moduloPowerOfTwo(int x, int n) { 22 | if (n <= 0) { 23 | throw new IllegalArgumentException("The exponent must be positive"); 24 | } 25 | 26 | return x & ((1 << n) - 1); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /.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 | 46 | /infer-out/ 47 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/bitmanipulation/CountSetBitsTest.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 | 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 | @Test 19 | void testSetBitsLookupApproach() { 20 | CountSetBits csb = new CountSetBits(); 21 | assertEquals(1L, csb.lookupApproach(16)); 22 | assertEquals(4, csb.lookupApproach(15)); 23 | assertEquals(5, csb.lookupApproach(10000)); 24 | assertEquals(5, csb.lookupApproach(31)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /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 testZigZagPattern() { 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 | // Edge cases 15 | Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row 16 | Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string 17 | Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /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/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/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/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/others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | final class FloydTriangle { 7 | private FloydTriangle() { 8 | } 9 | 10 | /** 11 | * Generates a Floyd Triangle with the specified number of rows. 12 | * 13 | * @param rows The number of rows in the triangle. 14 | * @return A List representing the Floyd Triangle. 15 | */ 16 | public static List> generateFloydTriangle(int rows) { 17 | List> triangle = new ArrayList<>(); 18 | int number = 1; 19 | 20 | for (int i = 0; i < rows; i++) { 21 | List row = new ArrayList<>(); 22 | for (int j = 0; j <= i; j++) { 23 | row.add(number++); 24 | } 25 | triangle.add(row); 26 | } 27 | 28 | return triangle; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /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 = Math.min(absMinWrapper.value, number)); 23 | 24 | return absMinWrapper.value; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /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/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/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/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/dynamicprogramming/PalindromicPartitioningTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 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 PalindromicPartitioningTest { 11 | 12 | private static Stream provideTestCases() { 13 | return Stream.of(Arguments.of("a", 0), Arguments.of("aa", 0), Arguments.of("ab", 1), Arguments.of("ababbbabbababa", 3), Arguments.of("abcde", 4), Arguments.of("abacdcaba", 0)); 14 | } 15 | 16 | @ParameterizedTest 17 | @MethodSource("provideTestCases") 18 | public void testMinimalPartitions(String input, int expected) { 19 | assertEquals(expected, PalindromicPartitioning.minimalPartitions(input)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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 org.junit.jupiter.params.ParameterizedTest; 7 | import org.junit.jupiter.params.provider.CsvSource; 8 | import org.junit.jupiter.params.provider.ValueSource; 9 | 10 | public class ReverseNumberTest { 11 | 12 | @ParameterizedTest 13 | @CsvSource({"0, 0", "1, 1", "10, 1", "123, 321", "7890, 987"}) 14 | public void testReverseNumber(int input, int expected) { 15 | assertEquals(expected, ReverseNumber.reverseNumber(input)); 16 | } 17 | 18 | @ParameterizedTest 19 | @ValueSource(ints = {-1, -123, -7890}) 20 | public void testReverseNumberThrowsExceptionForNegativeInput(int input) { 21 | assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(input)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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/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/test/java/com/thealgorithms/conversions/DecimalToBinaryTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 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 | public class DecimalToBinaryTest { 9 | 10 | @ParameterizedTest 11 | @CsvSource({"0, 0", "1, 1", "2, 10", "5, 101", "10, 1010", "15, 1111", "100, 1100100"}) 12 | void testConvertUsingConventionalAlgorithm(int decimal, int expectedBinary) { 13 | assertEquals(expectedBinary, DecimalToBinary.convertUsingConventionalAlgorithm(decimal)); 14 | } 15 | 16 | @ParameterizedTest 17 | @CsvSource({"0, 0", "1, 1", "2, 10", "5, 101", "10, 1010", "15, 1111", "100, 1100100"}) 18 | void testConvertUsingBitwiseAlgorithm(int decimal, int expectedBinary) { 19 | assertEquals(expectedBinary, DecimalToBinary.convertUsingBitwiseAlgorithm(decimal)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * This class provides a method to detect if two integers 5 | * differ by exactly one bit flip. 6 | * 7 | * Example: 8 | * 1 (0001) and 2 (0010) differ by exactly one bit flip. 9 | * 7 (0111) and 3 (0011) differ by exactly one bit flip. 10 | * 11 | * @author Hardvan 12 | */ 13 | public final class OneBitDifference { 14 | private OneBitDifference() { 15 | } 16 | 17 | /** 18 | * Checks if two integers differ by exactly one bit. 19 | * 20 | * @param x the first integer 21 | * @param y the second integer 22 | * @return true if x and y differ by exactly one bit, false otherwise 23 | */ 24 | public static boolean differByOneBit(int x, int y) { 25 | if (x == y) { 26 | return false; 27 | } 28 | 29 | int xor = x ^ y; 30 | return (xor & (xor - 1)) == 0; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /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 | @Test 23 | void testGetMinValueWithSameAbsoluteValues() { 24 | assertEquals(-5, AbsoluteMin.getMinValue(-5, 5)); 25 | assertEquals(-5, AbsoluteMin.getMinValue(5, -5)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 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 MinimumWaitingTimeTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCases") 14 | public void testMinimumWaitingTime(int[] queries, int expected) { 15 | assertEquals(expected, MinimumWaitingTime.minimumWaitingTime(queries)); 16 | } 17 | 18 | private static Stream provideTestCases() { 19 | return Stream.of(Arguments.of(new int[] {3, 2, 1, 2, 6}, 17), Arguments.of(new int[] {3, 2, 1}, 4), Arguments.of(new int[] {1, 2, 3, 4}, 10), Arguments.of(new int[] {5, 5, 5, 5}, 30), Arguments.of(new int[] {}, 0)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.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 | class LeastCommonMultipleTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCases") 14 | void testLcm(int num1, int num2, int expected) { 15 | assertEquals(expected, LeastCommonMultiple.lcm(num1, num2)); 16 | } 17 | 18 | private static Stream provideTestCases() { 19 | return Stream.of(Arguments.of(12, 18, 36), Arguments.of(5, 10, 10), Arguments.of(7, 3, 21), Arguments.of(21, 6, 42), Arguments.of(1, 1, 1), Arguments.of(8, 12, 24), Arguments.of(14, 35, 70), Arguments.of(15, 25, 75), Arguments.of(100, 25, 100), Arguments.of(0, 10, 0)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/ciphers/AutokeyTest.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 AutokeyCipherTest { 8 | 9 | Autokey autokeyCipher = new Autokey(); 10 | 11 | @Test 12 | void autokeyEncryptTest() { 13 | // given 14 | String plaintext = "MEET AT DAWN"; 15 | String keyword = "QUEEN"; 16 | 17 | // when 18 | String cipherText = autokeyCipher.encrypt(plaintext, keyword); 19 | 20 | // then 21 | assertEquals("CYIXNFHEPN", cipherText); 22 | } 23 | 24 | @Test 25 | void autokeyDecryptTest() { 26 | // given 27 | String ciphertext = "CYIX NF HEPN"; 28 | String keyword = "QUEEN"; 29 | 30 | // when 31 | String plainText = autokeyCipher.decrypt(ciphertext, keyword); 32 | 33 | // then 34 | assertEquals("MEETATDAWN", plainText); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /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/main/java/com/thealgorithms/lineclipping/utils/Point.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.lineclipping.utils; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * @author moksedursohan 7 | * @since 10/4/24 8 | */ 9 | public class Point { 10 | 11 | public double x; 12 | public double y; 13 | 14 | public Point() { 15 | } 16 | 17 | public Point(double x, double y) { 18 | this.x = x; 19 | this.y = y; 20 | } 21 | 22 | @Override 23 | public boolean equals(Object o) { 24 | if (this == o) { 25 | return true; 26 | } 27 | if (!(o instanceof Point point)) { 28 | return false; 29 | } 30 | 31 | return Double.compare(x, point.x) == 0 && Double.compare(y, point.y) == 0; 32 | } 33 | 34 | @Override 35 | public int hashCode() { 36 | return Objects.hash(x, y); 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "(" + x + ", " + y + ")"; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/divideandconquer/CountingInversionsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.divideandconquer; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class CountingInversionsTest { 8 | 9 | @Test 10 | public void testCountInversions() { 11 | int[] arr = {2, 3, 8, 6, 1}; 12 | assertEquals(5, CountingInversions.countInversions(arr)); 13 | } 14 | 15 | @Test 16 | public void testNoInversions() { 17 | int[] arr = {1, 2, 3, 4, 5}; 18 | assertEquals(0, CountingInversions.countInversions(arr)); 19 | } 20 | 21 | @Test 22 | public void testSingleElement() { 23 | int[] arr = {1}; 24 | assertEquals(0, CountingInversions.countInversions(arr)); 25 | } 26 | 27 | @Test 28 | public void testAllInversions() { 29 | int[] arr = {5, 4, 3, 2, 1}; 30 | assertEquals(10, CountingInversions.countInversions(arr)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /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/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/LongestPalindromicSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 | class LongestPalindromicSubstringTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCasesForLongestPalindrome") 14 | void testLongestPalindrome(String input, String expected) { 15 | assertEquals(expected, LongestPalindromicSubstring.longestPalindrome(input)); 16 | } 17 | 18 | private static Stream provideTestCasesForLongestPalindrome() { 19 | return Stream.of(Arguments.of("babad", "bab"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("", ""), Arguments.of("abc", "a"), Arguments.of(null, ""), Arguments.of("aaaaa", "aaaaa")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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) || (Math.abs(numbers[i]) == Math.abs(absMax) && numbers[i] > absMax)) { 21 | absMax = numbers[i]; 22 | } 23 | } 24 | return absMax; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /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/ciphers/BaconianCipherTest.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 BaconianCipherTest { 8 | 9 | BaconianCipher baconianCipher = new BaconianCipher(); 10 | 11 | @Test 12 | void baconianCipherEncryptTest() { 13 | // given 14 | String plaintext = "MEET AT DAWN"; 15 | 16 | // when 17 | String cipherText = baconianCipher.encrypt(plaintext); 18 | 19 | // then 20 | assertEquals("ABBAAAABAAAABAABAABBAAAAABAABBAAABBAAAAABABBAABBAB", cipherText); 21 | } 22 | 23 | @Test 24 | void baconianCipherDecryptTest() { 25 | // given 26 | String ciphertext = "ABBAAAABAAAABAABAABBAAAAABAABBAAABBAAAAABABBAABBAB"; 27 | 28 | // when 29 | String plainText = baconianCipher.decrypt(ciphertext); 30 | 31 | // then 32 | assertEquals("MEETATDAWN", plainText); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /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/main/java/com/thealgorithms/matrix/MedianOfMatrix.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.matrix; 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(Iterable> 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/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/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 | Assertions.assertTrue(PerfectSquare.isPerfectSquareUsingPow(number)); 13 | } 14 | 15 | @ParameterizedTest 16 | @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}) 17 | void negativeTest(final int number) { 18 | Assertions.assertFalse(PerfectSquare.isPerfectSquare(number)); 19 | Assertions.assertFalse(PerfectSquare.isPerfectSquareUsingPow(number)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/greedyalgorithms/StockProfitCalculatorTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 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 StockProfitCalculatorTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCases") 14 | public void testMaxProfit(int[] prices, int expected) { 15 | assertEquals(expected, StockProfitCalculator.maxProfit(prices)); 16 | } 17 | 18 | private static Stream provideTestCases() { 19 | return Stream.of(Arguments.of(new int[] {7, 1, 5, 3, 6, 4}, 5), Arguments.of(new int[] {7, 6, 4, 3, 1}, 0), Arguments.of(new int[] {5, 5, 5, 5, 5}, 0), Arguments.of(new int[] {10}, 0), Arguments.of(new int[] {1, 5}, 4), Arguments.of(new int[] {2, 4, 1, 3, 7, 5}, 6)); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/lineclipping/utils/Line.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.lineclipping.utils; 2 | 3 | import java.util.Objects; 4 | 5 | /** 6 | * @author moksedursohan 7 | * @since 10/4/24 8 | */ 9 | public class Line { 10 | 11 | public Point start; 12 | public Point end; 13 | 14 | public Line() { 15 | } 16 | 17 | public Line(Point start, Point end) { 18 | this.start = start; 19 | this.end = end; 20 | } 21 | 22 | @Override 23 | public boolean equals(Object o) { 24 | if (this == o) { 25 | return true; 26 | } 27 | if (!(o instanceof Line line)) { 28 | return false; 29 | } 30 | 31 | return Objects.equals(start, line.start) && Objects.equals(end, line.end); 32 | } 33 | 34 | @Override 35 | public int hashCode() { 36 | return Objects.hash(start, end); 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "Line from " + start + " to " + end; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/stacks/PrefixEvaluatorTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.stacks; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.util.EmptyStackException; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class PrefixEvaluatorTest { 10 | 11 | @Test 12 | public void testValidExpressions() { 13 | assertEquals(10, PrefixEvaluator.evaluatePrefix("+ * 2 3 4")); 14 | assertEquals(5, PrefixEvaluator.evaluatePrefix("- + 7 3 5")); 15 | assertEquals(6, PrefixEvaluator.evaluatePrefix("/ * 3 2 1")); 16 | } 17 | 18 | @Test 19 | public void testInvalidExpression() { 20 | assertThrows(EmptyStackException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3")); 21 | } 22 | 23 | @Test 24 | public void testMoreThanOneStackSizeAfterEvaluation() { 25 | assertThrows(IllegalArgumentException.class, () -> PrefixEvaluator.evaluatePrefix("+ 3 4 5")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /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/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/bitmanipulation/HammingDistance.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 5 | * Given two integers x and y, calculate the Hamming distance. 6 | * Example: 7 | * Input: x = 1, y = 4 8 | * Output: 2 9 | * Explanation: 1 (0001) and 4 (0100) have 2 differing bits. 10 | * 11 | * @author Hardvan 12 | */ 13 | public final class HammingDistance { 14 | private HammingDistance() { 15 | } 16 | 17 | /** 18 | * Calculates the Hamming distance between two integers. 19 | * The Hamming distance is the number of differing bits between the two integers. 20 | * 21 | * @param x The first integer. 22 | * @param y The second integer. 23 | * @return The Hamming distance (number of differing bits). 24 | */ 25 | public static int hammingDistance(int x, int y) { 26 | int xor = x ^ y; 27 | return Integer.bitCount(xor); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/stacks/PostfixEvaluatorTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.stacks; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | 6 | import java.util.EmptyStackException; 7 | import org.junit.jupiter.api.Test; 8 | 9 | public class PostfixEvaluatorTest { 10 | 11 | @Test 12 | public void testValidExpressions() { 13 | assertEquals(22, PostfixEvaluator.evaluatePostfix("5 6 + 2 *")); 14 | assertEquals(27, PostfixEvaluator.evaluatePostfix("7 2 + 3 *")); 15 | assertEquals(3, PostfixEvaluator.evaluatePostfix("10 5 / 1 +")); 16 | } 17 | 18 | @Test 19 | public void testInvalidExpression() { 20 | assertThrows(EmptyStackException.class, () -> PostfixEvaluator.evaluatePostfix("5 +")); 21 | } 22 | 23 | @Test 24 | public void testMoreThanOneStackSizeAfterEvaluation() { 25 | assertThrows(IllegalArgumentException.class, () -> PostfixEvaluator.evaluatePostfix("5 6 + 2 * 3")); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/conversions/AnyBaseToDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 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 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | public class AnyBaseToDecimalTest { 11 | @ParameterizedTest 12 | @CsvSource({"1010, 2, 10", "777, 8, 511", "999, 10, 999", "ABCDEF, 16, 11259375", "XYZ, 36, 44027", "0, 2, 0", "A, 16, 10", "Z, 36, 35"}) 13 | void testConvertToDecimal(String input, int radix, int expected) { 14 | assertEquals(expected, AnyBaseToDecimal.convertToDecimal(input, radix)); 15 | } 16 | 17 | @Test 18 | void testIncorrectInput() { 19 | assertThrows(NumberFormatException.class, () -> AnyBaseToDecimal.convertToDecimal("G", 16)); 20 | assertThrows(NumberFormatException.class, () -> AnyBaseToDecimal.convertToDecimal("XYZ", 10)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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/greedyalgorithms/EgyptianFractionTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import java.util.List; 6 | import java.util.stream.Stream; 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.Arguments; 9 | import org.junit.jupiter.params.provider.MethodSource; 10 | 11 | public class EgyptianFractionTest { 12 | 13 | @ParameterizedTest 14 | @MethodSource("fractionProvider") 15 | public void testGetEgyptianFraction(int numerator, int denominator, List expected) { 16 | assertEquals(expected, EgyptianFraction.getEgyptianFraction(numerator, denominator)); 17 | } 18 | 19 | private static Stream fractionProvider() { 20 | return Stream.of(Arguments.of(2, 3, List.of("1/2", "1/6")), Arguments.of(3, 10, List.of("1/4", "1/20")), Arguments.of(1, 3, List.of("1/3")), Arguments.of(1, 2, List.of("1/2")), Arguments.of(4, 13, List.of("1/4", "1/18", "1/468"))); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/CountCharTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.DisplayName; 6 | import org.junit.jupiter.api.Test; 7 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | class CountCharTest { 11 | 12 | @ParameterizedTest(name = "\"{0}\" should have {1} non-whitespace characters") 13 | @CsvSource({"'', 0", "' ', 0", "'a', 1", "'abc', 3", "'a b c', 3", "' a b c ', 3", "'\tabc\n', 3", "' a b\tc ', 3", "' 12345 ', 5", "'Hello, World!', 12"}) 14 | @DisplayName("Test countCharacters with various inputs") 15 | void testCountCharacters(String input, int expected) { 16 | assertEquals(expected, CountChar.countCharacters(input)); 17 | } 18 | 19 | @Test 20 | @DisplayName("Test countCharacters with null input") 21 | void testCountCharactersNullInput() { 22 | assertEquals(0, CountChar.countCharacters(null)); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/conversions/DecimalToAnyBaseTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 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 | import org.junit.jupiter.params.ParameterizedTest; 8 | import org.junit.jupiter.params.provider.CsvSource; 9 | 10 | public class DecimalToAnyBaseTest { 11 | 12 | @ParameterizedTest 13 | @CsvSource({"0, 2, 0", "0, 16, 0", "0, 36, 0", "10, 2, 1010", "255, 16, FF", "100, 8, 144", "42, 2, 101010", "1234, 16, 4D2", "1234, 36, YA"}) 14 | void testConvertToAnyBase(int decimal, int base, String expected) { 15 | assertEquals(expected, DecimalToAnyBase.convertToAnyBase(decimal, base)); 16 | } 17 | 18 | @Test 19 | void testBaseOutOfRange() { 20 | assertThrows(IllegalArgumentException.class, () -> DecimalToAnyBase.convertToAnyBase(10, 1)); 21 | assertThrows(IllegalArgumentException.class, () -> DecimalToAnyBase.convertToAnyBase(10, 37)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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/main/java/com/thealgorithms/maths/Prime/PrimeFactorization.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths.Prime; 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/test/java/com/thealgorithms/maths/prime/PrimeCheckTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths.prime; 2 | 3 | import com.thealgorithms.maths.Prime.PrimeCheck; 4 | import org.junit.jupiter.api.Assertions; 5 | import org.junit.jupiter.api.Test; 6 | 7 | public class PrimeCheckTest { 8 | 9 | @Test 10 | void test1() { 11 | Assertions.assertTrue(PrimeCheck.isPrime(2)); 12 | } 13 | 14 | @Test 15 | void test2() { 16 | Assertions.assertFalse(PrimeCheck.isPrime(-1)); 17 | } 18 | 19 | @Test 20 | void test3() { 21 | Assertions.assertFalse(PrimeCheck.isPrime(4)); 22 | } 23 | 24 | @Test 25 | void test4() { 26 | Assertions.assertTrue(PrimeCheck.isPrime(5)); 27 | } 28 | 29 | @Test 30 | void test5() { 31 | Assertions.assertFalse(PrimeCheck.isPrime(15)); 32 | } 33 | 34 | @Test 35 | void test6() { 36 | Assertions.assertTrue(PrimeCheck.isPrime(11)); 37 | } 38 | 39 | @Test 40 | void test7() { 41 | Assertions.assertFalse(PrimeCheck.isPrime(49)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | /** 4 | * CountSinglyLinkedListRecursion extends a singly linked list to include a 5 | * recursive count method, which calculates the number of nodes in the list. 6 | */ 7 | public class CountSinglyLinkedListRecursion extends SinglyLinkedList { 8 | 9 | /** 10 | * Recursively calculates the number of nodes in the list. 11 | * 12 | * @param head the head node of the list segment being counted. 13 | * @return the count of nodes from the given head node onward. 14 | */ 15 | private int countRecursion(Node head) { 16 | return head == null ? 0 : 1 + countRecursion(head.next); 17 | } 18 | 19 | /** 20 | * Returns the total number of nodes in the list by invoking the recursive 21 | * count helper method. 22 | * 23 | * @return the total node count in the list. 24 | */ 25 | @Override 26 | public int count() { 27 | return countRecursion(getHead()); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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/test/java/com/thealgorithms/matrix/MedianOfMatrixTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.matrix; 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/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 | /** 23 | * Check if a number is perfect square or not 24 | * 25 | * @param number number to be checked 26 | * @return {@code true} if {@code number} is perfect square, otherwise 27 | * {@code false} 28 | */ 29 | public static boolean isPerfectSquareUsingPow(long number) { 30 | long a = (long) Math.pow(number, 1.0 / 2); 31 | return a * a == number; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /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/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/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * This class provides a method to find the first differing bit 5 | * between two integers. 6 | * 7 | * Example: 8 | * x = 10 (1010 in binary) 9 | * y = 12 (1100 in binary) 10 | * The first differing bit is at index 1 (0-based) 11 | * So, the output will be 1 12 | * 13 | * @author Hardvan 14 | */ 15 | public final class FirstDifferentBit { 16 | private FirstDifferentBit() { 17 | } 18 | 19 | /** 20 | * Identifies the index of the first differing bit between two integers. 21 | * Steps: 22 | * 1. XOR the two integers to get the differing bits 23 | * 2. Find the index of the first set bit in XOR result 24 | * 25 | * @param x the first integer 26 | * @param y the second integer 27 | * @return the index of the first differing bit (0-based) 28 | */ 29 | public static int firstDifferentBit(int x, int y) { 30 | int diff = x ^ y; 31 | return Integer.numberOfTrailingZeros(diff); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * @author - https://github.com/Monk-AbhinayVerma 5 | * @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement 6 | * The class OnesComplement computes the complement of binary number 7 | * and returns 8 | * the complemented binary string. 9 | * @return the complimented binary string 10 | */ 11 | public final class OnesComplement { 12 | private OnesComplement() { 13 | } 14 | 15 | // Function to get the 1's complement of a binary number 16 | public static String onesComplement(String binary) { 17 | StringBuilder complement = new StringBuilder(); 18 | // Invert each bit to get the 1's complement 19 | for (int i = 0; i < binary.length(); i++) { 20 | if (binary.charAt(i) == '0') { 21 | complement.append('1'); 22 | } else { 23 | complement.append('0'); 24 | } 25 | } 26 | return complement.toString(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /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/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/dynamicprogramming/LongestPalindromicSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 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 LongestPalindromicSubstringTest { 11 | 12 | private static Stream provideTestCases() { 13 | return Stream.of( 14 | Arguments.of("babad", "aba"), Arguments.of("cbbd", "bb"), Arguments.of("a", "a"), Arguments.of("x", "x"), Arguments.of("", ""), Arguments.of("aaaa", "aaaa"), Arguments.of("mm", "mm"), Arguments.of("level", "level"), Arguments.of("bananas", "anana"), Arguments.of("abacabad", "abacaba")); 15 | } 16 | 17 | @ParameterizedTest 18 | @MethodSource("provideTestCases") 19 | public void testLps(String input, String expected) { 20 | assertEquals(expected, LongestPalindromicSubstring.lps(input)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/PalindromeTest.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.MethodSource; 7 | 8 | public class PalindromeTest { 9 | private static Stream provideTestCases() { 10 | return Stream.of(new TestData(null, true), new TestData("", true), new TestData("aba", true), new TestData("123321", true), new TestData("kayak", true), new TestData("abb", false), new TestData("abc", false), new TestData("abc123", false), new TestData("kayaks", false)); 11 | } 12 | 13 | @ParameterizedTest 14 | @MethodSource("provideTestCases") 15 | void testPalindrome(TestData testData) { 16 | Assertions.assertEquals(testData.expected, Palindrome.isPalindrome(testData.input) && Palindrome.isPalindromeRecursion(testData.input) && Palindrome.isPalindromeTwoPointer(testData.input)); 17 | } 18 | 19 | private record TestData(String input, boolean expected) { 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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/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/strings/ReturnSubsequenceTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 | class ReturnSubsequenceTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("provideTestCases") 14 | void testSubsequences(String input, String[] expected) { 15 | String[] actual = ReturnSubsequence.getSubsequences(input); 16 | assertArrayEquals(expected, actual); 17 | } 18 | 19 | static Stream provideTestCases() { 20 | return Stream.of(Arguments.of("", new String[] {""}), Arguments.of("a", new String[] {"", "a"}), Arguments.of("ab", new String[] {"", "b", "a", "ab"}), Arguments.of("abc", new String[] {"", "c", "b", "bc", "a", "ac", "ab", "abc"}), 21 | Arguments.of("aab", new String[] {"", "b", "a", "ab", "a", "ab", "aa", "aab"})); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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/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/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/stacks/DuplicateBracketsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.stacks; 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.api.Test; 8 | import org.junit.jupiter.params.ParameterizedTest; 9 | import org.junit.jupiter.params.provider.CsvSource; 10 | 11 | class DuplicateBracketsTest { 12 | 13 | @ParameterizedTest 14 | @CsvSource({"'((a + b) + (c + d))'", "'(a + b)'", "'a + b'", "'('", "''"}) 15 | void testInputReturnsFalse(String input) { 16 | assertFalse(DuplicateBrackets.check(input)); 17 | } 18 | 19 | @ParameterizedTest 20 | @CsvSource({"'(a + b) + ((c + d))'", "'((a + b))'", "'((((a + b)))))'"}) 21 | void testInputReturnsTrue(String input) { 22 | assertTrue(DuplicateBrackets.check(input)); 23 | } 24 | 25 | @Test 26 | void testInvalidInput() { 27 | assertThrows(IllegalArgumentException.class, () -> DuplicateBrackets.check(null)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /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/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 | 14 | for (int i = 0; i < array.length - 1; i++) { 15 | final int minIndex = findIndexOfMin(array, i); 16 | SortUtils.swap(array, i, minIndex); 17 | } 18 | return array; 19 | } 20 | 21 | private static > int findIndexOfMin(T[] array, final int startIndex) { 22 | int minIndex = startIndex; 23 | for (int i = startIndex + 1; i < array.length; i++) { 24 | if (array[i].compareTo(array[minIndex]) < 0) { 25 | minIndex = i; 26 | } 27 | } 28 | return minIndex; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /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/slidingwindow/LongestSubarrayWithSumLessOrEqualToKTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.slidingwindow; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Unit tests for the LongestSubarrayWithSumLessOrEqualToK algorithm. 9 | */ 10 | public class LongestSubarrayWithSumLessOrEqualToKTest { 11 | 12 | /** 13 | * Tests for the longest subarray with a sum less than or equal to k. 14 | */ 15 | @Test 16 | public void testLongestSubarrayWithSumLEK() { 17 | assertEquals(3, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 6)); // {1, 2, 3} 18 | assertEquals(4, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 10)); // {1, 2, 3, 4} 19 | assertEquals(2, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {5, 1, 2, 3}, 5)); // {5} 20 | assertEquals(0, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3}, 0)); // No valid subarray 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.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: 'temurin' 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 | -------------------------------------------------------------------------------- /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/StoogeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | /** 4 | * @author Amir Hassan (https://github.com/ahsNT) 5 | * @see SortAlgorithm 6 | */ 7 | public class StoogeSort implements SortAlgorithm { 8 | 9 | @Override 10 | public > T[] sort(T[] array) { 11 | if (array.length == 0) { 12 | return array; 13 | } 14 | sort(array, 0, array.length); 15 | return array; 16 | } 17 | 18 | public > T[] sort(final T[] array, final int start, final int end) { 19 | if (SortUtils.less(array[end - 1], array[start])) { 20 | final T temp = array[start]; 21 | array[start] = array[end - 1]; 22 | array[end - 1] = temp; 23 | } 24 | 25 | final int length = end - start; 26 | if (length > 2) { 27 | int third = length / 3; 28 | sort(array, start, end - third); 29 | sort(array, start + third, end); 30 | sort(array, start, end - third); 31 | } 32 | return array; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /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/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/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * @author Varun Upadhyay (https://github.com/varunu28) 5 | */ 6 | public final class RemoveDuplicateFromString { 7 | private RemoveDuplicateFromString() { 8 | } 9 | 10 | /** 11 | * Removes duplicate characters from the given string. 12 | * 13 | * @param input The input string from which duplicate characters need to be removed. 14 | * @return A string containing only unique characters from the input, in their original order. 15 | */ 16 | public static String removeDuplicate(String input) { 17 | if (input == null || input.isEmpty()) { 18 | return input; 19 | } 20 | 21 | StringBuilder uniqueChars = new StringBuilder(); 22 | for (char c : input.toCharArray()) { 23 | if (uniqueChars.indexOf(String.valueOf(c)) == -1) { 24 | uniqueChars.append(c); // Append character if it's not already in the StringBuilder 25 | } 26 | } 27 | 28 | return uniqueChars.toString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/recursion/GenerateSubsets.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.recursion; 2 | 3 | // program to find power set of a string 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public final class GenerateSubsets { 9 | 10 | private GenerateSubsets() { 11 | throw new UnsupportedOperationException("Utility class"); 12 | } 13 | 14 | public static List subsetRecursion(String str) { 15 | return doRecursion("", str); 16 | } 17 | 18 | private static List doRecursion(String p, String up) { 19 | if (up.isEmpty()) { 20 | List list = new ArrayList<>(); 21 | list.add(p); 22 | return list; 23 | } 24 | 25 | // Taking the character 26 | char ch = up.charAt(0); 27 | // Adding the character in the recursion 28 | List left = doRecursion(p + ch, up.substring(1)); 29 | // Not adding the character in the recursion 30 | List right = doRecursion(p, up.substring(1)); 31 | 32 | left.addAll(right); 33 | 34 | return left; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | public int[] search(int[][] matrix, int value) { 12 | int n = matrix.length; 13 | // This variable iterates over rows 14 | int i = 0; 15 | // This variable iterates over columns 16 | int j = n - 1; 17 | int[] result = {-1, -1}; 18 | 19 | while (i < n && j >= 0) { 20 | if (matrix[i][j] == value) { 21 | result[0] = i; 22 | result[1] = j; 23 | return result; 24 | } 25 | if (value > matrix[i][j]) { 26 | i++; 27 | } else { 28 | j--; 29 | } 30 | } 31 | return result; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.slidingwindow; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | /** 8 | * Unit tests for the LongestSubstringWithoutRepeatingCharacters class. 9 | * 10 | * @author (https://github.com/Chiefpatwal) 11 | */ 12 | public class LongestSubstringWithoutRepeatingCharactersTest { 13 | 14 | @Test 15 | public void testLengthOfLongestSubstring() { 16 | // Test cases for the lengthOfLongestSubstring method 17 | assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcabcbb")); 18 | assertEquals(1, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("bbbbb")); 19 | assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("pwwkew")); 20 | assertEquals(0, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("")); 21 | assertEquals(5, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcde")); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/HillCipherTest.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 HillCipherTest { 8 | 9 | HillCipher hillCipher = new HillCipher(); 10 | 11 | @Test 12 | void hillCipherEncryptTest() { 13 | // given 14 | String message = "ACT"; // Plaintext message 15 | int[][] keyMatrix = {{6, 24, 1}, {13, 16, 10}, {20, 17, 15}}; // Encryption key matrix 16 | 17 | // when 18 | String cipherText = hillCipher.encrypt(message, keyMatrix); 19 | 20 | // then 21 | assertEquals("POH", cipherText); 22 | } 23 | 24 | @Test 25 | void hillCipherDecryptTest() { 26 | // given 27 | String cipherText = "POH"; // Ciphertext message 28 | int[][] inverseKeyMatrix = {{8, 5, 10}, {21, 8, 21}, {21, 12, 8}}; // Decryption (inverse key) matrix 29 | 30 | // when 31 | String plainText = hillCipher.decrypt(cipherText, inverseKeyMatrix); 32 | 33 | // then 34 | assertEquals("ACT", plainText); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /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/strings/CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Set; 4 | 5 | /** 6 | * Vowel Count is a system whereby character strings are placed in order based 7 | * on the position of the characters in the conventional ordering of an 8 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 9 | */ 10 | public final class CheckVowels { 11 | private static final Set VOWELS = Set.of('a', 'e', 'i', 'o', 'u'); 12 | 13 | private CheckVowels() { 14 | } 15 | 16 | /** 17 | * Checks if a string contains any vowels. 18 | * 19 | * @param input a string to check 20 | * @return {@code true} if the given string contains at least one vowel, otherwise {@code false} 21 | */ 22 | public static boolean hasVowels(String input) { 23 | if (input == null || input.isEmpty()) { 24 | return false; 25 | } 26 | 27 | for (char c : input.toLowerCase().toCharArray()) { 28 | if (VOWELS.contains(c)) { 29 | return true; 30 | } 31 | } 32 | return false; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /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/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/strings/LongestNonRepetitiveSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 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 LongestNonRepetitiveSubstringTest { 11 | 12 | private static Stream provideTestCases() { 13 | return Stream.of(Arguments.of("", 0), Arguments.of("a", 1), Arguments.of("abcde", 5), Arguments.of("aaaaa", 1), Arguments.of("abca", 3), Arguments.of("abcdeabc", 5), Arguments.of("a1b2c3", 6), Arguments.of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 62), 14 | Arguments.of("aabb", 2), Arguments.of("abcdefghijabc", 10)); 15 | } 16 | 17 | @ParameterizedTest 18 | @MethodSource("provideTestCases") 19 | void testLengthOfLongestSubstring(String input, int expectedLength) { 20 | assertEquals(expectedLength, LongestNonRepetitiveSubstring.lengthOfLongestSubstring(input)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /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/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 | assertEquals(-1, AbsoluteMax.getMaxValue(-1, -1, -1, -1, -1)); 16 | } 17 | 18 | @Test 19 | void testGetMaxValueWithNoArguments() { 20 | assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue); 21 | } 22 | 23 | @Test 24 | void testGetMaxValueWithSameAbsoluteValues() { 25 | assertEquals(5, AbsoluteMax.getMaxValue(-5, 5)); 26 | assertEquals(5, AbsoluteMax.getMaxValue(5, -5)); 27 | assertEquals(12, AbsoluteMax.getMaxValue(-12, 9, 3, 12, 1)); 28 | assertEquals(12, AbsoluteMax.getMaxValue(12, 9, 3, -12, 1)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/greedyalgorithms/BandwidthAllocationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.greedyalgorithms; 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 BandwidthAllocationTest { 11 | 12 | @ParameterizedTest 13 | @MethodSource("bandwidthProvider") 14 | public void testMaxValue(int capacity, int[] bandwidths, int[] values, int expected) { 15 | assertEquals(expected, BandwidthAllocation.maxValue(capacity, bandwidths, values)); 16 | } 17 | 18 | private static Stream bandwidthProvider() { 19 | return Stream.of(Arguments.of(50, new int[] {20, 10, 30}, new int[] {40, 20, 30}, 80), Arguments.of(0, new int[] {5, 10}, new int[] {10, 20}, 0), Arguments.of(5, new int[] {5, 10}, new int[] {10, 20}, 10), Arguments.of(15, new int[] {10, 20}, new int[] {10, 25}, 18), 20 | Arguments.of(25, new int[] {10, 15, 20}, new int[] {10, 30, 50}, 60)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCount.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * This class provides a method to find the next higher number 5 | * with the same number of set bits as the given number. 6 | * 7 | * @author Hardvan 8 | */ 9 | public final class NextHigherSameBitCount { 10 | private NextHigherSameBitCount() { 11 | } 12 | 13 | /** 14 | * Finds the next higher integer with the same number of set bits. 15 | * Steps: 16 | * 1. Find {@code c}, the rightmost set bit of {@code n}. 17 | * 2. Find {@code r}, the rightmost set bit of {@code n + c}. 18 | * 3. Swap the bits of {@code r} and {@code n} to the right of {@code c}. 19 | * 4. Shift the bits of {@code r} and {@code n} to the right of {@code c} to the rightmost. 20 | * 5. Combine the results of steps 3 and 4. 21 | * 22 | * @param n the input number 23 | * @return the next higher integer with the same set bit count 24 | */ 25 | public static int nextHigherSameBitCount(int n) { 26 | int c = n & -n; 27 | int r = n + c; 28 | return (((r ^ n) >> 2) / c) | r; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.bitmanipulation; 2 | 3 | /** 4 | * This class provides a method to determine whether two integers have 5 | * different signs. It utilizes the XOR operation on the two numbers: 6 | * 7 | * - If two numbers have different signs, their most significant bits 8 | * (sign bits) will differ, resulting in a negative XOR result. 9 | * - If two numbers have the same sign, the XOR result will be non-negative. 10 | * 11 | * Time Complexity: O(1) - Constant time operation. 12 | * Space Complexity: O(1) - No extra space used. 13 | * 14 | * @author Bama Charan Chhandogi 15 | */ 16 | public final class NumbersDifferentSigns { 17 | private NumbersDifferentSigns() { 18 | } 19 | 20 | /** 21 | * Determines if two integers have different signs using bitwise XOR. 22 | * 23 | * @param num1 the first integer 24 | * @param num2 the second integer 25 | * @return true if the two numbers have different signs, false otherwise 26 | */ 27 | public static boolean differentSigns(int num1, int num2) { 28 | return (num1 ^ num2) < 0; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/CatalanNumbers.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Calculate Catalan Numbers 5 | */ 6 | public final class CatalanNumbers { 7 | private CatalanNumbers() { 8 | } 9 | 10 | /** 11 | * Calculate the nth Catalan number using a recursive formula. 12 | * 13 | * @param n the index of the Catalan number to compute 14 | * @return the nth Catalan number 15 | */ 16 | public static long catalan(final int n) { 17 | if (n < 0) { 18 | throw new IllegalArgumentException("Index must be non-negative"); 19 | } 20 | return factorial(2 * n) / (factorial(n + 1) * factorial(n)); 21 | } 22 | 23 | /** 24 | * Calculate the factorial of a number. 25 | * 26 | * @param n the number to compute the factorial for 27 | * @return the factorial of n 28 | */ 29 | private static long factorial(final int n) { 30 | if (n == 0 || n == 1) { 31 | return 1; 32 | } 33 | long result = 1; 34 | for (int i = 2; i <= n; i++) { 35 | result *= i; 36 | } 37 | return result; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /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/strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using different version 5 | */ 6 | public final class ReverseString { 7 | private ReverseString() { 8 | } 9 | 10 | /** 11 | * easiest way to reverses the string str and returns it 12 | * 13 | * @param str string to be reversed 14 | * @return reversed string 15 | */ 16 | public static String reverse(String str) { 17 | return new StringBuilder(str).reverse().toString(); 18 | } 19 | 20 | /** 21 | * second way to reverses the string str and returns it 22 | * 23 | * @param str string to be reversed 24 | * @return reversed string 25 | */ 26 | public static String reverse2(String str) { 27 | if (str == null || str.isEmpty()) { 28 | return str; 29 | } 30 | 31 | char[] value = str.toCharArray(); 32 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) { 33 | char temp = value[i]; 34 | value[i] = value[j]; 35 | value[j] = temp; 36 | } 37 | return new String(value); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/matrix/TestPrintMatrixInSpiralOrder.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.matrix; 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/conversions/OctalToDecimalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.CsvSource; 6 | 7 | public class OctalToDecimalTest { 8 | 9 | @ParameterizedTest 10 | @CsvSource({"10, 8", "7, 7", "77, 63", "123, 83", "0, 0", "777, 511", "2671, 1465", "275, 189"}) 11 | void testConvertOctalToDecimal(String inputOctal, int expectedDecimal) { 12 | Assertions.assertEquals(expectedDecimal, OctalToDecimal.convertOctalToDecimal(inputOctal)); 13 | } 14 | 15 | @ParameterizedTest 16 | @CsvSource({"'', Input cannot be null or empty", "'8', Incorrect input: Expecting an octal number (digits 0-7)", "'19', Incorrect input: Expecting an octal number (digits 0-7)"}) 17 | void testIncorrectInput(String inputOctal, String expectedMessage) { 18 | IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> OctalToDecimal.convertOctalToDecimal(inputOctal)); 19 | Assertions.assertEquals(expectedMessage, exception.getMessage()); 20 | } 21 | } 22 | --------------------------------------------------------------------------------