├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── build.yml │ ├── prettify.yml │ ├── stale.yml │ └── update_directory.yml ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── CONTRIBUTING.md ├── DIRECTORY.md ├── LICENSE ├── README-ko.md ├── README.md ├── pom.xml └── src ├── main └── java │ └── com │ └── thealgorithms │ ├── audiofilters │ └── IIRFilter.java │ ├── backtracking │ ├── Combination.java │ ├── FloodFill.java │ ├── KnightsTour.java │ ├── NQueens.java │ ├── Permutation.java │ └── PowerSum.java │ ├── ciphers │ ├── AES.java │ ├── AESEncryption.java │ ├── AffineCipher.java │ ├── Blowfish.java │ ├── Caesar.java │ ├── ColumnarTranspositionCipher.java │ ├── HillCipher.java │ ├── ProductCipher.java │ ├── RSA.java │ ├── SimpleSubCipher.java │ ├── SimpleSubstitutionCipher.java │ └── Vigenere.java │ ├── conversions │ ├── AnyBaseToAnyBase.java │ ├── AnyBaseToDecimal.java │ ├── AnytoAny.java │ ├── BinaryToDecimal.java │ ├── BinaryToHexadecimal.java │ ├── BinaryToOctal.java │ ├── DecimalToAnyBase.java │ ├── DecimalToBinary.java │ ├── DecimalToHexaDecimal.java │ ├── DecimalToOctal.java │ ├── HexToOct.java │ ├── HexaDecimalToBinary.java │ ├── HexaDecimalToDecimal.java │ ├── IntegerToRoman.java │ ├── OctalToDecimal.java │ ├── OctalToHexadecimal.java │ ├── RgbHsvConversion.java │ ├── RomanToInteger.java │ └── TurkishToLatinConversion.java │ ├── datastructures │ ├── bags │ │ └── Bag.java │ ├── bloomfilter │ │ └── BloomFilter.java │ ├── buffers │ │ └── CircularBuffer.java │ ├── caches │ │ ├── LRUCache.java │ │ └── MRUCache.java │ ├── disjointsets │ │ ├── DisjointSets.java │ │ └── Node.java │ ├── dynamicarray │ │ └── DynamicArray.java │ ├── graphs │ │ ├── A_Star.java │ │ ├── BellmanFord.java │ │ ├── BipartiteGrapfDFS.java │ │ ├── ConnectedComponent.java │ │ ├── Cycles.java │ │ ├── DIJSKSTRAS_ALGORITHM.java │ │ ├── FloydWarshall.java │ │ ├── Graphs.java │ │ ├── KahnsAlgorithm.java │ │ ├── Kruskal.java │ │ ├── MatrixGraphs.java │ │ ├── PrimMST.java │ │ └── README.md │ ├── hashmap │ │ ├── Readme.md │ │ └── hashing │ │ │ ├── HashMap.java │ │ │ ├── HashMapLinearProbing.java │ │ │ ├── Intersection │ │ │ ├── Main.java │ │ │ └── MainLinearProbing.java │ ├── heaps │ │ ├── EmptyHeapException.java │ │ ├── FibonacciHeap.java │ │ ├── GenericHeap │ │ ├── Heap.java │ │ ├── HeapElement.java │ │ ├── MaxHeap.java │ │ ├── MinHeap.java │ │ ├── MinPriorityQueue.java │ │ └── Readme.md │ ├── lists │ │ ├── CircleLinkedList.java │ │ ├── CountSinglyLinkedListRecursion.java │ │ ├── CreateAndDetectLoop.java │ │ ├── CursorLinkedList.java │ │ ├── DoublyLinkedList.java │ │ ├── MergeSortedArrayList.java │ │ ├── MergeSortedSinglyLinkedList.java │ │ ├── Merge_K_SortedLinkedlist.java │ │ ├── README.md │ │ ├── RandomNode.java │ │ ├── SearchSinglyLinkedListRecursion.java │ │ └── SinglyLinkedList.java │ ├── queues │ │ ├── CircularQueue.java │ │ ├── Deques.java │ │ ├── GenericArrayListQueue.java │ │ ├── LinkedQueue.java │ │ ├── PriorityQueues.java │ │ ├── Queues.java │ │ └── README.md │ ├── stacks │ │ ├── BalancedBrackets.java │ │ ├── CalculateMaxOfMin.java │ │ ├── DecimalToAnyUsingStack.java │ │ ├── DuplicateBrackets.java │ │ ├── InfixToPostfix.java │ │ ├── LargestRectangle.java │ │ ├── MaximumMinimumWindow.java │ │ ├── NextGraterElement.java │ │ ├── NextSmallerElement.java │ │ ├── NodeStack.java │ │ ├── PostfixToInfix.java │ │ ├── README.md │ │ ├── ReverseStack.java │ │ ├── StackArray.java │ │ ├── StackArrayList.java │ │ └── StackOfLinkedList.java │ └── trees │ │ ├── AVLSimple.java │ │ ├── AVLTree.java │ │ ├── BSTIterative.java │ │ ├── BSTRecursive.java │ │ ├── BSTRecursiveGeneric.java │ │ ├── BinaryTree.java │ │ ├── CeilInBinarySearchTree.java │ │ ├── CheckIfBinaryTreeBalanced.java │ │ ├── CreateBSTFromSortedArray.java │ │ ├── CreateBinaryTreeFromInorderPreorder.java │ │ ├── FenwickTree.java │ │ ├── GenericTree.java │ │ ├── LCA.java │ │ ├── LevelOrderTraversal.java │ │ ├── LevelOrderTraversalQueue.java │ │ ├── PrintTopViewofTree.java │ │ ├── README.md │ │ ├── RedBlackBST.java │ │ ├── SegmentTree.java │ │ ├── TreeRandomNode.java │ │ ├── TreeTraversal.java │ │ ├── TrieImp.java │ │ ├── ValidBSTOrNot.java │ │ ├── VerticalOrderTraversal.java │ │ └── nearestRightKey.java │ ├── devutils │ ├── nodes │ │ ├── LargeTreeNode.java │ │ ├── Node.java │ │ ├── SimpleNode.java │ │ ├── SimpleTreeNode.java │ │ └── TreeNode.java │ └── searches │ │ └── SearchAlgorithm.java │ ├── divideandconquer │ ├── BinaryExponentiation.java │ ├── ClosestPair.java │ ├── SkylineAlgorithm.java │ └── StrassenMatrixMultiplication.java │ ├── dynamicprogramming │ ├── BoardPath.java │ ├── BoundaryFill.java │ ├── BruteForceKnapsack.java │ ├── CatalanNumber.java │ ├── CoinChange.java │ ├── CountFriendsPairing.java │ ├── DiceThrow.java │ ├── DyanamicProgrammingKnapsack.java │ ├── EditDistance.java │ ├── EggDropping.java │ ├── Fibonacci.java │ ├── FordFulkerson.java │ ├── KadaneAlgorithm.java │ ├── Knapsack.java │ ├── KnapsackMemoization.java │ ├── LevenshteinDistance.java │ ├── LongestAlternatingSubsequence.java │ ├── LongestCommonSubsequence.java │ ├── LongestIncreasingSubsequence.java │ ├── LongestPalindromicSubsequence.java │ ├── LongestPalindromicSubstring.java │ ├── LongestValidParentheses.java │ ├── MatrixChainMultiplication.java │ ├── MatrixChainRecursiveTopDownMemoisation.java │ ├── MemoizationTechniqueKnapsack.java │ ├── MinimumPathSum.java │ ├── MinimumSumPartition.java │ ├── NewManShanksPrime.java │ ├── PalindromicPartitioning.java │ ├── RegexMatching.java │ ├── RodCutting.java │ ├── ShortestCommonSupersequenceLength.java │ ├── SubsetSum.java │ ├── Sum_Of_Subset.java │ ├── UniquePaths.java │ └── WineProblem.java │ ├── maths │ ├── ADTFraction.java │ ├── AbsoluteMax.java │ ├── AbsoluteMin.java │ ├── AbsoluteValue.java │ ├── AliquotSum.java │ ├── AmicableNumber.java │ ├── Area.java │ ├── Armstrong.java │ ├── AutomorphicNumber.java │ ├── Average.java │ ├── BinaryPow.java │ ├── BinomialCoefficient.java │ ├── Ceil.java │ ├── CircularConvolutionFFT.java │ ├── Combinations.java │ ├── Convolution.java │ ├── ConvolutionFFT.java │ ├── DeterminantOfMatrix.java │ ├── DigitalRoot.java │ ├── DistanceFormula.java │ ├── DudeneyNumber.java │ ├── EulerMethod.java │ ├── FFT.java │ ├── FFTBluestein.java │ ├── Factorial.java │ ├── FactorialRecursion.java │ ├── FibonacciJavaStreams.java │ ├── FibonacciNumber.java │ ├── FindKthNumber.java │ ├── FindMax.java │ ├── FindMaxRecursion.java │ ├── FindMin.java │ ├── FindMinRecursion.java │ ├── Floor.java │ ├── GCD.java │ ├── GCDRecursion.java │ ├── Gaussian.java │ ├── GenericRoot.java │ ├── HarshadNumber.java │ ├── HeronsFormula.java │ ├── JugglerSequence.java │ ├── KaprekarNumbers.java │ ├── KeithNumber.java │ ├── KrishnamurthyNumber.java │ ├── LeonardoNumber.java │ ├── LinearDiophantineEquationsSolver.java │ ├── LucasSeries.java │ ├── MagicSquare.java │ ├── MatrixUtil.java │ ├── MaxValue.java │ ├── Median.java │ ├── MinValue.java │ ├── Mode.java │ ├── NonRepeatingElement.java │ ├── NthUglyNumber.java │ ├── NumberOfDigits.java │ ├── PalindromeNumber.java │ ├── ParseInteger.java │ ├── PascalTriangle.java │ ├── PerfectCube.java │ ├── PerfectNumber.java │ ├── PerfectSquare.java │ ├── PiNilakantha.java │ ├── Pow.java │ ├── PowRecursion.java │ ├── PowerOfTwoOrNot.java │ ├── PrimeCheck.java │ ├── PrimeFactorization.java │ ├── PronicNumber.java │ ├── PythagoreanTriple.java │ ├── ReverseNumber.java │ ├── RomanNumeralUtil.java │ ├── SimpsonIntegration.java │ ├── SquareRootWithBabylonianMethod.java │ ├── StandardDeviation.java │ ├── StandardScore.java │ ├── SumOfArithmeticSeries.java │ ├── SumOfDigits.java │ ├── TrinomialTriangle.java │ ├── VampireNumber.java │ ├── VectorCrossProduct.java │ └── Volume.java │ ├── matrixexponentiation │ └── Fibonacci.java │ ├── minimizinglateness │ ├── MinimizingLateness.java │ └── lateness_data.txt │ ├── misc │ ├── ColorContrastRatio.java │ ├── InverseOfMatrix.java │ ├── MedianOfRunningArray.java │ ├── PalindromePrime.java │ ├── PalindromeSinglyLinkedList.java │ ├── RangeInSortedArray.java │ ├── Sort012D.java │ ├── Sparcity.java │ ├── ThreeSumProblem.java │ ├── TwoSumProblem.java │ ├── WordBoggle.java │ └── matrixTranspose.java │ ├── others │ ├── ArrayLeftRotation.java │ ├── BFPRT.java │ ├── BankersAlgorithm.java │ ├── BoyerMoore.java │ ├── BrianKernighanAlgorithm.java │ ├── CRC32.java │ ├── CRCAlgorithm.java │ ├── CountChar.java │ ├── CountWords.java │ ├── Damm.java │ ├── Dijkstra.java │ ├── EulersFunction.java │ ├── FibbonaciSeries.java │ ├── FloydTriangle.java │ ├── GuassLegendre.java │ ├── HappyNumbersSeq.java │ ├── Huffman.java │ ├── Implementing_auto_completing_features_using_trie.java │ ├── InsertDeleteInArray.java │ ├── KMP.java │ ├── KochSnowflake.java │ ├── Krishnamurthy.java │ ├── LinearCongruentialGenerator.java │ ├── LowestBasePalindrome.java │ ├── Luhn.java │ ├── Mandelbrot.java │ ├── MemoryManagementAlgorithms.java │ ├── MiniMaxAlgorithm.java │ ├── PageRank.java │ ├── PasswordGen.java │ ├── PerlinNoise.java │ ├── QueueUsingTwoStacks.java │ ├── RabinKarp.java │ ├── RemoveDuplicateFromString.java │ ├── ReturnSubsequence.java │ ├── ReverseStackUsingRecursion.java │ ├── RootPrecision.java │ ├── RotateMatriceBy90Degree.java │ ├── SJF.java │ ├── SieveOfEratosthenes.java │ ├── SkylineProblem.java │ ├── StackPostfixNotation.java │ ├── StringMatchFiniteAutomata.java │ ├── Sudoku.java │ ├── ThreeSum.java │ ├── TopKWords.java │ ├── TowerOfHanoi.java │ ├── TwoPointers.java │ └── Verhoeff.java │ ├── searches │ ├── BinarySearch.java │ ├── BreadthFirstSearch.java │ ├── DepthFirstSearch.java │ ├── ExponentalSearch.java │ ├── FibonacciSearch.java │ ├── HowManyTimesRotated.java │ ├── InterpolationSearch.java │ ├── IterativeBinarySearch.java │ ├── IterativeTernarySearch.java │ ├── JumpSearch.java │ ├── LinearSearch.java │ ├── LinearSearchThread.java │ ├── LowerBound.java │ ├── MonteCarloTreeSearch.java │ ├── PerfectBinarySearch.java │ ├── QuickSelect.java │ ├── SaddlebackSearch.java │ ├── SquareRootBinarySearch.java │ ├── TernarySearch.java │ ├── UnionFind.java │ └── UpperBound.java │ ├── sorts │ ├── BitonicSort.java │ ├── BogoSort.java │ ├── BubbleSort.java │ ├── BubbleSortRecursion.java │ ├── BucketSort.java │ ├── CircleSort.java │ ├── CocktailShakerSort.java │ ├── CombSort.java │ ├── CountingSort.java │ ├── CycleSort.java │ ├── DNFSort.java │ ├── DutchNationalFlagSort.java │ ├── GnomeSort.java │ ├── HeapSort.java │ ├── InsertionSort.java │ ├── LinkList_Sort.java │ ├── MergeSort.java │ ├── MergeSortNoExtraSpace.java │ ├── MergeSortRecursive.java │ ├── OddEvenSort.java │ ├── PancakeSort.java │ ├── PigeonholeSort.java │ ├── QuickSort.java │ ├── RadixSort.java │ ├── SelectionSort.java │ ├── ShellSort.java │ ├── SimpleSort.java │ ├── SlowSort.java │ ├── SortAlgorithm.java │ ├── SortUtils.java │ ├── StoogeSort.java │ ├── SwapSort.java │ ├── TimSort.java │ ├── TopologicalSort.java │ ├── TreeSort.java │ └── WiggleSort.java │ └── strings │ ├── Alphabetical.java │ ├── Anagrams.java │ ├── CharactersSame.java │ ├── CheckAnagrams.java │ ├── CheckVowels.java │ ├── HorspoolSearch.java │ ├── List_all_Possible_Words_From_Phone_Digits.java │ ├── LongestPalindromicSubstring.java │ ├── Lower.java │ ├── Palindrome.java │ ├── Pangram.java │ ├── PermuteString.java │ ├── ReverseString.java │ ├── Rotation.java │ ├── Upper.java │ ├── WordLadder.java │ ├── longestNonRepeativeSubstring.java │ └── zigZagPattern │ ├── README.md │ └── zigZagPattern.java └── test └── java └── com └── thealgorithms ├── backtracking ├── CombinationTest.java ├── FloodFillTest.java └── PermutationTest.java ├── ciphers └── BlowfishTest.java ├── datastructures ├── FibonacciHeapTest.java └── bloomfilter │ └── BloomFilterTest.java ├── maths ├── ADTFractionTest.java ├── AbsoluteMaxTest.java ├── AbsoluteMinTest.java ├── AbsoluteValueTest.java ├── AliquotSumTest.java ├── ArmstrongTest.java ├── AverageTest.java ├── DistanceFormulaTest.java ├── FFTTest.java ├── FactorialTest.java ├── FindMaxTest.java ├── FindMinTest.java ├── GCDTest.java ├── GaussianTest.java ├── HeronsFormulaTest.java ├── KaprekarNumbersTest.java ├── PascalTriangleTest.java ├── PrimeCheckTest.java ├── PronicNumberTest.java ├── PythagoreanTripleTest.java ├── SquareRootwithBabylonianMethodTest.java ├── StandardDeviationTest.java ├── StandardScoreTest.java ├── SumOfDigitsTest.java └── TestArmstrong.java ├── others ├── ArrayLeftRotationTest.java ├── BestFitCPUTest.java ├── CalculateMaxOfMinTest.java ├── CountFriendsPairingTest.java ├── FirstFitCPUTest.java ├── KadaneAlogrithmTest.java ├── LinkList_Sort_test.java ├── NewManShanksPrimeTest.java ├── NextFitTest.java ├── UniquePathsTests.java └── WorstFitCPUTest.java ├── searches └── QuickSelectTest.java ├── sorts ├── DutchNationalFlagSortTest.java ├── TopologicalSortTest.java └── WiggleSortTest.java └── strings ├── AlphabeticalTest.java ├── AnagramsTest.java ├── CharacterSameTest.java ├── CheckAnagramsTest.java ├── PalindromeTest.java ├── PangramTest.java ├── UpperTest.java ├── longestNonRepeativeSubstringTest.java └── zigZagPattern └── zigZagPatternTest.java /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @siriak @yanglbme 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Device Specification** 27 | 28 | **Additional context** 29 | Add any other context about the problem here. 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### **Describe your change:** 2 | 3 | - [ ] Add an algorithm? 4 | - [ ] Fix a bug or typo in an existing algorithm? 5 | - [ ] Documentation change? 6 | 7 | #### References 8 | 9 | 10 | 11 | ### **Checklist:** 12 | 13 | 14 | 15 | - [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md). 16 | - [ ] This pull request is all my own work -- I have not plagiarized. 17 | - [ ] I know that pull requests will not be merged if they fail the automated tests. 18 | - [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. 19 | - [ ] All new Java files are placed inside an existing directory. 20 | - [ ] All filenames are in all uppercase characters with no spaces or dashes. 21 | - [ ] All functions and variable names follow Java naming conventions. 22 | - [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. 23 | - [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. 24 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: 3 | push: 4 | paths: 5 | - 'src/**' 6 | - '**.yml' 7 | - '**.xml' 8 | - '**.Dockerfile' 9 | pull_request: 10 | paths: 11 | - 'src/**' 12 | - '**.yml' 13 | - '**.xml' 14 | - '**.Dockerfile' 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Set up JDK 17 21 | uses: actions/setup-java@v2 22 | with: 23 | java-version: 17 24 | distribution: 'adopt' 25 | - name: Build with Maven 26 | run: mvn --batch-mode --update-snapshots verify 27 | -------------------------------------------------------------------------------- /.github/workflows/prettify.yml: -------------------------------------------------------------------------------- 1 | name: Prettify 2 | on: 3 | push: 4 | paths: 5 | - 'src/**' 6 | - '**.yml' 7 | - '**.xml' 8 | - '**.Dockerfile' 9 | pull_request: 10 | paths: 11 | - 'src/**' 12 | - '**.yml' 13 | - '**.xml' 14 | - '**.Dockerfile' 15 | jobs: 16 | prettier: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v2 21 | with: 22 | ref: ${{ github.head_ref }} 23 | 24 | - name: Prettify code 25 | uses: creyD/prettier_action@v3.3 26 | with: 27 | prettier_options: --write **/*.java 28 | commit_message: 'Prettify code' 29 | env: 30 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 31 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: 'Close stale issues and PRs' 2 | on: 3 | schedule: 4 | - cron: '0 0 * * *' 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v4 10 | with: 11 | stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' 12 | close-issue-message: 'Please reopen this issue once you add more information and updates here. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' 13 | stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' 14 | close-pr-message: 'Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' 15 | exempt-issue-labels: 'dont-close' 16 | exempt-pr-labels: 'dont-close' 17 | days-before-stale: 30 18 | days-before-close: 7 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /gradle/wrapper/gradle-wrapper.properties 2 | ##----------Android---------- 3 | # build 4 | *.apk 5 | *.ap_ 6 | *.dex 7 | *.class 8 | bin/ 9 | gen/ 10 | build/ 11 | out/ 12 | # gradle 13 | .gradle/ 14 | gradle-app.setting 15 | !gradle-wrapper.jar 16 | build/ 17 | # maven 18 | *.classpath 19 | *.project 20 | *.settings 21 | /target/ 22 | local.properties 23 | ##----------idea---------- 24 | *.iml 25 | .idea/ 26 | *.ipr 27 | *.iws 28 | # Android Studio Navigation editor temp files 29 | .navigation/ 30 | ##----------Other---------- 31 | # osx 32 | *~ 33 | .DS_Store 34 | gradle.properties 35 | .vscode 36 | *.log 37 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full 2 | 3 | # Install custom tools, runtimes, etc. 4 | # For example "bastet", a command-line tetris clone: 5 | # RUN brew install bastet 6 | # 7 | # More information: https://www.gitpod.io/docs/config-docker/ 8 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | tasks: 5 | - init: 'echo "TODO: Replace with init/build command"' 6 | command: (e.g. 'npm start', 'yarn watch'...) 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The Algorithms - Java 2 | 3 | [![Build](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml) 4 | [![Discord chat](https://img.shields.io/discord/808045925556682782.svg?logo=discord&colorB=7289DA&style=flat-square)](https://discord.gg/c7MnfGFGa6) 5 | [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) 6 | 7 | 8 | You can run and edit the algorithms, or contribute to them using Gitpod.io (a free online development environment) with a single click. 9 | 10 | [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/TheAlgorithms/Java) 11 | 12 | ### All algorithms are implemented in Java (for educational purposes) 13 | These implementations are intended for learning purposes. As such, they may be less efficient than the Java standard library. 14 | 15 | ## Contribution Guidelines 16 | Please read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute to this project. 17 | 18 | ## Community Channel 19 | We're on [Gitter](https://gitter.im/TheAlgorithms)! Come join us. 20 | 21 | ## Algorithms 22 | Our [directory](DIRECTORY.md) has the full list of applications. 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/AnytoAny.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | // given a source number , source base, destination base, this code can give you the destination 5 | // number. 6 | // sn ,sb,db ---> ()dn . this is what we have to do . 7 | 8 | public class AnytoAny { 9 | 10 | public static void main(String[] args) { 11 | Scanner scn = new Scanner(System.in); 12 | int sn = scn.nextInt(); 13 | int sb = scn.nextInt(); 14 | int db = scn.nextInt(); 15 | int m = 1, dec = 0, dn = 0; 16 | while (sn != 0) { 17 | dec = dec + (sn % 10) * m; 18 | m *= sb; 19 | sn /= 10; 20 | } 21 | m = 1; 22 | while (dec != 0) { 23 | dn = dn + (dec % db) * m; 24 | m *= 10; 25 | dec /= db; 26 | } 27 | System.out.println(dn); 28 | scn.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts a Binary number to a Decimal number 7 | */ 8 | class BinaryToDecimal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line arguments 14 | */ 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int binNum, binCopy, d, s = 0, power = 0; 18 | System.out.print("Binary number: "); 19 | binNum = sc.nextInt(); 20 | binCopy = binNum; 21 | while (binCopy != 0) { 22 | d = binCopy % 10; 23 | s += d * (int) Math.pow(2, power++); 24 | binCopy /= 10; 25 | } 26 | System.out.println("Decimal equivalent:" + s); 27 | sc.close(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/BinaryToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Binary number to an Octal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class BinaryToOctal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the binary number: "); 20 | int b = sc.nextInt(); 21 | System.out.println("Octal equivalent: " + convertBinaryToOctal(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a binary number to an octal number. 27 | * 28 | * @param binary The binary number 29 | * @return The octal number 30 | */ 31 | public static String convertBinaryToOctal(int binary) { 32 | String octal = ""; 33 | int currBit = 0, j = 1; 34 | while (binary != 0) { 35 | int code3 = 0; 36 | for (int i = 0; i < 3; i++) { 37 | currBit = binary % 10; 38 | binary = binary / 10; 39 | code3 += currBit * j; 40 | j *= 2; 41 | } 42 | octal = code3 + octal; 43 | j = 1; 44 | } 45 | return octal; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // hex = [0 - 9] -> [A - F] 4 | class DecimalToHexaDecimal { 5 | 6 | private static final int sizeOfIntInHalfBytes = 8; 7 | private static final int numberOfBitsInAHalfByte = 4; 8 | private static final int halfByte = 0x0F; 9 | private static final char[] hexDigits = { 10 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 11 | }; 12 | 13 | // Returns the hex value of the dec entered in the parameter. 14 | public static String decToHex(int dec) { 15 | StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes); 16 | hexBuilder.setLength(sizeOfIntInHalfBytes); 17 | for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) { 18 | int j = dec & halfByte; 19 | hexBuilder.setCharAt(i, hexDigits[j]); 20 | dec >>= numberOfBitsInAHalfByte; 21 | } 22 | return hexBuilder.toString().toLowerCase(); 23 | } 24 | 25 | // Test above function. 26 | public static void main(String[] args) { 27 | System.out.println("Test..."); 28 | int dec = 305445566; 29 | String libraryDecToHex = Integer.toHexString(dec); 30 | String decToHex = decToHex(dec); 31 | System.out.println("Result from the library : " + libraryDecToHex); 32 | System.out.println("Result decToHex method : " + decToHex); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/DecimalToOctal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * This class converts Decimal numbers to Octal Numbers 7 | */ 8 | public class DecimalToOctal { 9 | 10 | /** 11 | * Main Method 12 | * 13 | * @param args Command line Arguments 14 | */ 15 | 16 | // enter in a decimal value to get Octal output 17 | public static void main(String[] args) { 18 | Scanner sc = new Scanner(System.in); 19 | int n, k, d, s = 0, c = 0; 20 | System.out.print("Decimal number: "); 21 | n = sc.nextInt(); 22 | k = n; 23 | while (k != 0) { 24 | d = k % 8; 25 | s += d * (int) Math.pow(10, c++); 26 | k /= 8; 27 | } 28 | 29 | System.out.println("Octal equivalent:" + s); 30 | sc.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | // Hex [0-9],[A-F] -> Binary [0,1] 4 | public class HexaDecimalToBinary { 5 | 6 | private final int LONG_BITS = 8; 7 | 8 | public void convert(String numHex) { 9 | // String a HexaDecimal: 10 | int conHex = Integer.parseInt(numHex, 16); 11 | // Hex a Binary: 12 | String binary = Integer.toBinaryString(conHex); 13 | // Output: 14 | System.out.println(numHex + " = " + completeDigits(binary)); 15 | } 16 | 17 | public String completeDigits(String binNum) { 18 | for (int i = binNum.length(); i < LONG_BITS; i++) { 19 | binNum = "0" + binNum; 20 | } 21 | return binNum; 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | // Testing Numbers: 27 | String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"}; 28 | HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); 29 | 30 | for (String num : hexNums) { 31 | objConvert.convert(num); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | public class HexaDecimalToDecimal { 6 | 7 | // convert hexadecimal to decimal 8 | public static int getHexaToDec(String hex) { 9 | String digits = "0123456789ABCDEF"; 10 | hex = hex.toUpperCase(); 11 | int val = 0; 12 | for (int i = 0; i < hex.length(); i++) { 13 | int d = digits.indexOf(hex.charAt(i)); 14 | val = 16 * val + d; 15 | } 16 | return val; 17 | } 18 | 19 | // Main method gets the hexadecimal input from user and converts it into Decimal output. 20 | public static void main(String args[]) { 21 | String hexa_Input; 22 | int dec_output; 23 | Scanner scan = new Scanner(System.in); 24 | 25 | System.out.print("Enter Hexadecimal Number : "); 26 | hexa_Input = scan.nextLine(); 27 | 28 | // convert hexadecimal to decimal 29 | dec_output = getHexaToDec(hexa_Input); 30 | /* 31 | Pass the string to the getHexaToDec function 32 | and it returns the decimal form in the variable dec_output. 33 | */ 34 | System.out.println("Number in Decimal: " + dec_output); 35 | scan.close(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/IntegerToRoman.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | /** 4 | * Converting Integers into Roman Numerals 5 | * 6 | *

7 | * ('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50); 8 | * ('XC',90); ('C', 100); ('D', 500); ('M', 1000); 9 | */ 10 | public class IntegerToRoman { 11 | 12 | private static int[] allArabianRomanNumbers 13 | = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 14 | private static String[] allRomanNumbers 15 | = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 16 | 17 | // Value must be > 0 18 | public static String integerToRoman(int num) { 19 | if (num <= 0) { 20 | return ""; 21 | } 22 | 23 | StringBuilder builder = new StringBuilder(); 24 | 25 | for (int a = 0; a < allArabianRomanNumbers.length; a++) { 26 | int times = num / allArabianRomanNumbers[a]; 27 | for (int b = 0; b < times; b++) { 28 | builder.append(allRomanNumbers[a]); 29 | } 30 | 31 | num -= times * allArabianRomanNumbers[a]; 32 | } 33 | 34 | return builder.toString(); 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println(IntegerToRoman.integerToRoman(2131)); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/OctalToDecimal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts any Octal Number to a Decimal Number 7 | * 8 | * @author Zachary Jones 9 | */ 10 | public class OctalToDecimal { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.print("Octal Input: "); 20 | String inputOctal = sc.nextLine(); 21 | int result = convertOctalToDecimal(inputOctal); 22 | if (result != -1) { 23 | System.out.println("Result convertOctalToDecimal : " + result); 24 | } 25 | sc.close(); 26 | } 27 | 28 | /** 29 | * This method converts an octal number to a decimal number. 30 | * 31 | * @param inputOctal The octal number 32 | * @return The decimal number 33 | */ 34 | public static int convertOctalToDecimal(String inputOctal) { 35 | 36 | try { 37 | // Actual conversion of Octal to Decimal: 38 | Integer outputDecimal = Integer.parseInt(inputOctal, 8); 39 | return outputDecimal; 40 | } catch (NumberFormatException ne) { 41 | // Printing a warning message if the input is not a valid octal 42 | // number: 43 | System.out.println("Invalid Input, Expecting octal number 0-7"); 44 | return -1; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.conversions; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Converts turkish character to latin character 7 | * 8 | * @author Özgün Gökşenli 9 | */ 10 | public class TurkishToLatinConversion { 11 | 12 | /** 13 | * Main method 14 | * 15 | * @param args Command line arguments 16 | */ 17 | public static void main(String args[]) { 18 | Scanner sc = new Scanner(System.in); 19 | System.out.println("Input the string: "); 20 | String b = sc.next(); 21 | System.out.println("Converted: " + convertTurkishToLatin(b)); 22 | sc.close(); 23 | } 24 | 25 | /** 26 | * This method converts a turkish character to latin character. 27 | * 28 | * @param param String paramter 29 | * @return String 30 | */ 31 | public static String convertTurkishToLatin(String param) { 32 | char[] turkishChars 33 | = new char[]{0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E}; 34 | char[] latinChars = new char[]{'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'}; 35 | for (int i = 0; i < turkishChars.length; i++) { 36 | param 37 | = param.replaceAll( 38 | new String(new char[]{turkishChars[i]}), new String(new char[]{latinChars[i]})); 39 | } 40 | return param; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/disjointsets/DisjointSets.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.disjointsets; 2 | 3 | public class DisjointSets { 4 | 5 | public Node MakeSet(T x) { 6 | return new Node(x); 7 | } 8 | 9 | ; 10 | 11 | public Node FindSet(Node node) { 12 | if (node != node.parent) { 13 | node.parent = FindSet(node.parent); 14 | } 15 | 16 | return node.parent; 17 | } 18 | 19 | public void UnionSet(Node x, Node y) { 20 | Node nx = FindSet(x); 21 | Node ny = FindSet(y); 22 | 23 | if (nx == ny) { 24 | return; 25 | } 26 | if (nx.rank > ny.rank) { 27 | ny.parent = nx; 28 | } else if (ny.rank > nx.rank) { 29 | nx.parent = ny; 30 | } else { 31 | nx.parent = ny; 32 | ny.rank++; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/disjointsets/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.disjointsets; 2 | 3 | public class Node { 4 | 5 | public int rank; 6 | public Node parent; 7 | public T data; 8 | 9 | public Node(T data) { 10 | this.data = data; 11 | parent = this; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | /* 3 | * this is algo which implies common mathematical set theory concept 4 | * called intersection in which result is common values of both the sets 5 | * here metaphor of sets is HashMap 6 | 7 | 8 | Test Case: 9 | Scanner scn=new Scanner(System.in); 10 | int len =scn.nextInt(); 11 | int arr[]=new int[len]; 12 | int arr2[]=new int[len]; 13 | 14 | for(int i=0;i<2*len;i++) { 15 | 16 | if(i=len) { 19 | arr2[i-len]=scn.nextInt(); 20 | } 21 | } 22 | System.out.println(Main(arr,arr2)); 23 | 24 | 25 | 26 | */ 27 | 28 | import java.util.ArrayList; 29 | import java.util.HashMap; 30 | import java.util.Map; 31 | import java.util.Scanner; 32 | import java.util.Set; 33 | 34 | public class Intersection { 35 | 36 | public static ArrayList Main(int arr[],int arr2[]) { 37 | HashMap hmap=new HashMap<>(); 38 | HashMap hmap2=new HashMap<>(); 39 | for(int i=0;i res=new ArrayList<>(); 48 | for(int i=0;i0) { 50 | int val=hmap.get(arr2[i]); 51 | hmap.put(arr2[i],val-1); 52 | res.add(arr2[i]); 53 | } 54 | 55 | } 56 | return res; 57 | } 58 | public Intersection() { 59 | 60 | } 61 | 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.hashmap.hashing; 2 | 3 | import java.util.Scanner; 4 | 5 | public class Main { 6 | 7 | public static void main(String[] args) { 8 | 9 | int choice, key; 10 | 11 | HashMap h = new HashMap(7); 12 | Scanner In = new Scanner(System.in); 13 | 14 | while (true) { 15 | System.out.println("Enter your Choice :"); 16 | System.out.println("1. Add Key"); 17 | System.out.println("2. Delete Key"); 18 | System.out.println("3. Print Table"); 19 | System.out.println("4. Exit"); 20 | 21 | choice = In.nextInt(); 22 | 23 | switch (choice) { 24 | case 1: { 25 | System.out.println("Enter the Key: "); 26 | key = In.nextInt(); 27 | h.insertHash(key); 28 | break; 29 | } 30 | case 2: { 31 | System.out.println("Enter the Key delete: "); 32 | key = In.nextInt(); 33 | h.deleteHash(key); 34 | break; 35 | } 36 | case 3: { 37 | System.out.println("Print table"); 38 | h.displayHashtable(); 39 | break; 40 | } 41 | case 4: { 42 | In.close(); 43 | return; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class CountSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 5; ++i) { 8 | list.insert(i); 9 | } 10 | assert list.count() == 5; 11 | } 12 | 13 | /** 14 | * Calculate the count of the list manually using recursion. 15 | * 16 | * @param head head of the list. 17 | * @return count of the list. 18 | */ 19 | private int countRecursion(Node head) { 20 | return head == null ? 0 : 1 + countRecursion(head.next); 21 | } 22 | 23 | /** 24 | * Returns the count of the list. 25 | */ 26 | @Override 27 | public int count() { 28 | return countRecursion(getHead()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.PriorityQueue; 6 | 7 | /** 8 | * @author Arun Pandey (https://github.com/pandeyarun709) 9 | */ 10 | public class Merge_K_SortedLinkedlist { 11 | 12 | /** 13 | * This function merge K sorted LinkedList 14 | * 15 | * @param a array of LinkedList 16 | * @param N size of array 17 | * @return node 18 | */ 19 | Node mergeKList(Node[] a, int N) { 20 | // Min Heap 21 | PriorityQueue min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); 22 | 23 | // adding head of all linkedList in min heap 24 | min.addAll(Arrays.asList(a).subList(0, N)); 25 | 26 | // Make new head among smallest heads in K linkedList 27 | Node head = min.poll(); 28 | min.add(head.next); 29 | Node curr = head; 30 | 31 | // merging LinkedList 32 | while (!min.isEmpty()) { 33 | 34 | Node temp = min.poll(); 35 | curr.next = temp; 36 | curr = temp; 37 | 38 | // Add Node in min Heap only if temp.next is not null 39 | if (temp.next != null) { 40 | min.add(temp.next); 41 | } 42 | } 43 | 44 | return head; 45 | } 46 | 47 | private class Node { 48 | 49 | private int data; 50 | private Node next; 51 | 52 | public Node(int d) { 53 | this.data = d; 54 | next = null; 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/README.md: -------------------------------------------------------------------------------- 1 | ## Linked List 2 | ### Description 3 | 4 | LinkedList is a data structure in which data is stored in a linear manner. It usually contains a data field and a link to the memory location of the next mode. 5 | 6 | ### Structure 7 | 8 | ``` 9 | class LinkedList{ 10 | E value; 11 | LinkedList next; 12 | } 13 | ``` 14 | 15 | The `next` variable points to the next node in the data structure and value stores the data. Any number of nodes can be linked in this manner. The structure will be: 16 | 17 | 18 | ### Properties 19 | 1. Linked list does not provide indexing like an array. For accessing a node at position `p` , θ(p) nodes need to be accessed. 20 | 2. Main advantage of linked list is addition and removal of nodes near the end and beginning of lists. It can be done just by updating the link (O(1) time) 21 | 3. Unlike an array, its size is not predefined. So any number of nodes can be appended. 22 | 23 | ### File descriptions: 24 | 25 | 1. `CircleLinkedList.java` : A circular linked list where next pointer of last node points to first nide of linked list. 26 | 2. `SinglyLinkedList.java` : The classic case of single links. 27 | 3. `CountSinglyLinkedListRecursion.java`: Recursively counts the size of a list. 28 | 4. `CreateAndDetectLoop.java` : Create and detect a loop in a linked list. 29 | 5. `DoublyLinkedList.java` : A modification of singly linked list which has a `prev` pointer to point to the previous node. 30 | 6. `Merge_K_SortedLinkedlist.java` : Merges K sorted linked list with mergesort (mergesort is also the most efficient sorting algorithm for linked list). 31 | 7. `RandomNode.java` : Selects a random node from given linked list and diplays it. -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.lists; 2 | 3 | public class SearchSinglyLinkedListRecursion extends SinglyLinkedList { 4 | 5 | public static void main(String[] args) { 6 | SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion(); 7 | for (int i = 1; i <= 10; ++i) { 8 | list.insert(i); 9 | } 10 | 11 | for (int i = 1; i <= 10; ++i) { 12 | assert list.search(i); 13 | } 14 | assert !list.search(-1) && !list.search(100); 15 | } 16 | 17 | /** 18 | * Test if the value key is present in the list using recursion. 19 | * 20 | * @param node the head node. 21 | * @param key the value to be searched. 22 | * @return {@code true} if key is present in the list, otherwise 23 | * {@code false}. 24 | */ 25 | private boolean searchRecursion(Node node, int key) { 26 | return node != null && (node.value == key || searchRecursion(node.next, key)); 27 | } 28 | 29 | @Override 30 | public boolean search(int key) { 31 | return searchRecursion(getHead(), key); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/queues/README.md: -------------------------------------------------------------------------------- 1 | # Queue 2 | - The Queue interface is present in the `java.util` package. 3 | - It is an ordered list of objects that follows the **FIFO** (First-In-First-Out) principle. 4 | 5 | ## Characteristics of a Queue 6 | - The Queue is used to insert elements at the end of the queue and removes elements from the beginning of the queue. 7 | - It supports all methods of Collection interface including insertion, deletion etc. 8 | - LinkedList, ArrayBlockingQueue and PriorityQueue are the most commonly used implementations. 9 | 10 | ## Declaration 11 | 12 | `Queue queue = new PriorityQueue ();` 13 | 14 | ## Important operations 15 | 16 | | Operations | Description | 17 | | ----------- | ----------- | 18 | |Enqueue|Adds an item to the queue| 19 | |Dequeue|Removes an item from the queue| 20 | |Front|Gets the front item from the queue| 21 | |Rear|Gets the last item from the queue| 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java: -------------------------------------------------------------------------------- 1 | /** Author : Siddhant Swarup Mallick 2 | * Github : https://github.com/siddhant2002 3 | */ 4 | 5 | /** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */ 6 | package com.thealgorithms.datastructures.stacks; 7 | 8 | import java.util.*; 9 | 10 | public class CalculateMaxOfMin { 11 | public static int calculateMaxOfMin(int[] a) { 12 | int n = a.length; 13 | int[] ans = new int[n]; 14 | int[] arr2 = Arrays.copyOf(a, n); 15 | Arrays.sort(arr2); 16 | int maxNum = arr2[arr2.length - 1]; 17 | ans[0] = maxNum; 18 | int index = 1; 19 | while (index != ans.length) { 20 | int[] minimums = new int[n - index]; 21 | for (int i = 0; i < n - index; i++) { 22 | int[] windowArray = Arrays.copyOfRange(a, i, i + index + 1); 23 | Arrays.sort(windowArray); 24 | int minNum = windowArray[0]; 25 | minimums[i] = minNum; 26 | } 27 | Arrays.sort(minimums); 28 | ans[index] = minimums[minimums.length - 1]; 29 | index += 1; 30 | } 31 | return ans[0]; 32 | } 33 | } 34 | /** 35 | * Given an integer array. The task is to find the maximum of the minimum of the 36 | * given array 37 | */ -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.stacks; 2 | 3 | import java.util.Stack; 4 | 5 | public class DecimalToAnyUsingStack { 6 | 7 | public static void main(String[] args) { 8 | assert convert(0, 2).equals("0"); 9 | assert convert(30, 2).equals("11110"); 10 | assert convert(30, 8).equals("36"); 11 | assert convert(30, 10).equals("30"); 12 | assert convert(30, 16).equals("1E"); 13 | } 14 | 15 | /** 16 | * Convert decimal number to another radix 17 | * 18 | * @param number the number to be converted 19 | * @param radix the radix 20 | * @return another radix 21 | * @throws ArithmeticException if number or radius is 22 | * invalid 23 | */ 24 | private static String convert(int number, int radix) { 25 | if (radix < 2 || radix > 16) { 26 | throw new ArithmeticException( 27 | String.format("Invalid input -> number:%d,radius:%d", number, radix)); 28 | } 29 | char[] tables = { 30 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 31 | }; 32 | Stack bits = new Stack<>(); 33 | do { 34 | bits.push(tables[number % radix]); 35 | number = number / radix; 36 | } while (number != 0); 37 | 38 | StringBuilder result = new StringBuilder(); 39 | while (!bits.isEmpty()) { 40 | result.append(bits.pop()); 41 | } 42 | return result.toString(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.stacks; 2 | 3 | // 1. You are given a string exp representing an expression. 4 | // 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other. 5 | // 3. But, some of the pair of brackets maybe extra/needless. 6 | // 4. You are required to print true if you detect extra brackets and false otherwise. 7 | // e.g.' 8 | // ((a + b) + (c + d)) -> false 9 | // (a + b) + ((c + d)) -> true 10 | import java.util.*; 11 | 12 | public class DuplicateBrackets { 13 | 14 | public static boolean check(String str) { 15 | Stack st = new Stack<>(); 16 | 17 | for (int i = 0; i < str.length(); i++) { 18 | char ch = str.charAt(i); 19 | if (ch == ')') { 20 | if (st.peek() == '(') { 21 | return true; 22 | } else { 23 | while (st.size() > 0 && st.peek() != '(') { 24 | st.pop(); 25 | } 26 | st.pop(); 27 | } 28 | 29 | } else { 30 | st.push(ch); 31 | } 32 | // System.out.println(st); 33 | } 34 | return false; 35 | } 36 | 37 | public static void main(String[] args) throws Exception { 38 | Scanner sc = new Scanner(System.in); 39 | String str = sc.nextLine(); 40 | System.out.println(check(str)); 41 | sc.close(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.stacks; 2 | 3 | import java.util.Stack; 4 | 5 | /** 6 | * 7 | * @author mohd rameez github.com/rameez471 8 | */ 9 | 10 | public class LargestRectangle { 11 | public static String largestRectanglehistogram(int[] heights) { 12 | int n = heights.length, maxArea = 0; 13 | Stack st = new Stack<>(); 14 | for(int i=0;i heights[i]) { 17 | int[] tmp = st.pop(); 18 | maxArea = Math.max(maxArea, tmp[1]*(i - tmp[0])); 19 | start = tmp[0]; 20 | } 21 | st.push(new int[]{start, heights[i]}); 22 | } 23 | while(!st.isEmpty()) { 24 | int[] tmp = st.pop(); 25 | maxArea = Math.max(maxArea, tmp[1]*(n-tmp[0])); 26 | } 27 | return Integer.toString(maxArea); 28 | } 29 | public static void main(String[] args) { 30 | assert largestRectanglehistogram(new int[]{2, 1, 5, 6, 2, 3}).equals("10"); 31 | assert largestRectanglehistogram(new int[]{2, 4}).equals("4"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/stacks/README.md: -------------------------------------------------------------------------------- 1 | # STACK 2 | 3 | Stack is an ADT (abstract data type) that acts like a list of objects but there is a difference. 4 | 5 | Stack works on the principle of _LIFO_ (Last In First Out), it means that the last item added to the stack will be the first item to be removed. 6 | 7 | Stack is based on two methods (functions)- 8 | 9 | ## push(element) 10 | 11 | It adds "element" to the top of the stack. 12 | 13 | For example: If we have `1, 3, 5` in stack, and we call push(9), 14 | 15 | `9` will be added to last index of stack -> `1, 3, 5 , 9`. 16 | 17 | ## peek() or top() 18 | 19 | It returns element at the top of the stack. 20 | 21 | For example: If we have `1, 3, 5` in stack, and we call peek(), 22 | 23 | `5` will be returned (without removing it from the stack). 24 | 25 | ## pop() 26 | 27 | It removes the last element (i.e. top of stack) from stack. 28 | 29 | For example: If we have `1, 3, 5 , 9` in stack, and we call pop(), 30 | 31 | the function will return `9` and the stack will change to `1, 3, 5`. 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | import com.thealgorithms.datastructures.trees.BinaryTree.Node; 4 | 5 | /** 6 | * Given a sorted array. Create a balanced binary search tree from it. 7 | * 8 | * Steps: 1. Find the middle element of array. This will act as root 2. Use the 9 | * left half recursively to create left subtree 3. Use the right half 10 | * recursively to create right subtree 11 | */ 12 | public class CreateBSTFromSortedArray { 13 | 14 | public static void main(String[] args) { 15 | test(new int[]{}); 16 | test(new int[]{1, 2, 3}); 17 | test(new int[]{1, 2, 3, 4, 5}); 18 | test(new int[]{1, 2, 3, 4, 5, 6, 7}); 19 | } 20 | 21 | private static void test(int[] array) { 22 | BinaryTree root = new BinaryTree(createBst(array, 0, array.length - 1)); 23 | System.out.println("\n\nPreorder Traversal: "); 24 | root.preOrder(root.getRoot()); 25 | System.out.println("\nInorder Traversal: "); 26 | root.inOrder(root.getRoot()); 27 | System.out.println("\nPostOrder Traversal: "); 28 | root.postOrder(root.getRoot()); 29 | } 30 | 31 | private static Node createBst(int[] array, int start, int end) { 32 | // No element left. 33 | if (start > end) { 34 | return null; 35 | } 36 | int mid = start + (end - start) / 2; 37 | 38 | // middle element will be the root 39 | Node root = new Node(array[mid]); 40 | root.left = createBst(array, start, mid - 1); 41 | root.right = createBst(array, mid + 1, end); 42 | return root; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /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 fen_t[]; 7 | 8 | /* Constructor which takes the size of the array as a parameter */ 9 | public FenwickTree(int n) { 10 | this.n = n; 11 | this.fen_t = 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 | fen_t[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 += fen_t[i]; 31 | i -= i & (-i); 32 | } 33 | return cumSum; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class LevelOrderTraversal { 4 | 5 | class Node { 6 | 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) { 11 | data = item; 12 | left = right = null; 13 | } 14 | } 15 | 16 | // Root of the Binary Tree 17 | Node root; 18 | 19 | public LevelOrderTraversal(Node root) { 20 | this.root = root; 21 | } 22 | 23 | /* function to print level order traversal of tree*/ 24 | void printLevelOrder() { 25 | int h = height(root); 26 | int i; 27 | for (i = 1; i <= h; i++) { 28 | printGivenLevel(root, i); 29 | } 30 | } 31 | 32 | /* Compute the "height" of a tree -- the number of 33 | nodes along the longest path from the root node 34 | down to the farthest leaf node.*/ 35 | int height(Node root) { 36 | if (root == null) { 37 | return 0; 38 | } else { 39 | /** 40 | * Return the height of larger subtree 41 | */ 42 | return Math.max(height(root.left), height(root.right)) + 1; 43 | } 44 | } 45 | 46 | /* Print nodes at the given level */ 47 | void printGivenLevel(Node root, int level) { 48 | if (root == null) { 49 | return; 50 | } 51 | if (level == 1) { 52 | System.out.print(root.data + " "); 53 | } else if (level > 1) { 54 | printGivenLevel(root.left, level - 1); 55 | printGivenLevel(root.right, level - 1); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | /* Class to print Level Order Traversal */ 7 | public class LevelOrderTraversalQueue { 8 | 9 | /* Class to represent Tree node */ 10 | class Node { 11 | 12 | int data; 13 | Node left, right; 14 | 15 | public Node(int item) { 16 | data = item; 17 | left = null; 18 | right = null; 19 | } 20 | } 21 | 22 | /* Given a binary tree. Print its nodes in level order 23 | using array for implementing queue */ 24 | void printLevelOrder(Node root) { 25 | Queue queue = new LinkedList(); 26 | queue.add(root); 27 | while (!queue.isEmpty()) { 28 | 29 | /* poll() removes the present head. 30 | For more information on poll() visit 31 | http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ 32 | Node tempNode = queue.poll(); 33 | System.out.print(tempNode.data + " "); 34 | 35 | /*Enqueue left child */ 36 | if (tempNode.left != null) { 37 | queue.add(tempNode.left); 38 | } 39 | 40 | /*Enqueue right child */ 41 | if (tempNode.right != null) { 42 | queue.add(tempNode.right); 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.trees; 2 | 3 | public class ValidBSTOrNot { 4 | 5 | class Node { 6 | 7 | int data; 8 | Node left, right; 9 | 10 | public Node(int item) { 11 | data = item; 12 | left = right = null; 13 | } 14 | } 15 | 16 | // Root of the Binary Tree 17 | 18 | /* can give min and max value according to your code or 19 | can write a function to find min and max value of tree. */ 20 | 21 | /* returns true if given search tree is binary 22 | search tree (efficient version) */ 23 | boolean isBST(Node root) { 24 | return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); 25 | } 26 | 27 | /* Returns true if the given tree is a BST and its 28 | values are >= min and <= max. */ 29 | boolean isBSTUtil(Node node, int min, int max) { 30 | /* an empty tree is BST */ 31 | if (node == null) { 32 | return true; 33 | } 34 | 35 | /* false if this node violates the min/max constraints */ 36 | if (node.data < min || node.data > max) { 37 | return false; 38 | } 39 | 40 | /* otherwise check the subtrees recursively 41 | tightening the min/max constraints */ 42 | // Allow only distinct values 43 | return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/nodes/Node.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.nodes; 2 | 3 | /** 4 | * Base class for any node implementation which contains a generic type 5 | * variable. 6 | * 7 | * All known subclasses: {@link TreeNode}, {@link SimpleNode}. 8 | * 9 | * @param The type of the data held in the Node. 10 | * 11 | * @author aitorfi 12 | */ 13 | public abstract class Node { 14 | 15 | /** 16 | * Generic type data stored in the Node. 17 | */ 18 | private E data; 19 | 20 | /** 21 | * Empty constructor. 22 | */ 23 | public Node() { 24 | } 25 | 26 | /** 27 | * Initializes the Nodes' data. 28 | * 29 | * @param data Value to which data will be initialized. 30 | */ 31 | public Node(E data) { 32 | this.data = data; 33 | } 34 | 35 | public E getData() { 36 | return data; 37 | } 38 | 39 | public void setData(E data) { 40 | this.data = data; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.devutils.nodes; 2 | 3 | /** 4 | * Simple Node implementation that holds a reference to the next Node. 5 | * 6 | * @param The type of the data held in the Node. 7 | * 8 | * @author aitorfi 9 | */ 10 | public class SimpleNode extends Node { 11 | 12 | /** 13 | * Reference to the next Node. 14 | */ 15 | private SimpleNode nextNode; 16 | 17 | /** 18 | * Empty contructor. 19 | */ 20 | public SimpleNode() { 21 | super(); 22 | } 23 | 24 | /** 25 | * Initializes the Nodes' data. 26 | * 27 | * @param data Value to which data will be initialized. 28 | * @see Node#Node(Object) 29 | */ 30 | public SimpleNode(E data) { 31 | super(data); 32 | } 33 | 34 | /** 35 | * Initializes the Nodes' data and next node reference. 36 | * 37 | * @param data Value to which data will be initialized. 38 | * @param nextNode Value to which the next node reference will be set. 39 | */ 40 | public SimpleNode(E data, SimpleNode nextNode) { 41 | super(data); 42 | this.nextNode = nextNode; 43 | } 44 | 45 | /** 46 | * @return True if there is a next node, otherwise false. 47 | */ 48 | public boolean hasNext() { 49 | return (nextNode != null); 50 | } 51 | 52 | public SimpleNode getNextNode() { 53 | return nextNode; 54 | } 55 | 56 | public void setNextNode(SimpleNode nextNode) { 57 | this.nextNode = nextNode; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /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 | /** 11 | * @param key is an element which should be found 12 | * @param array is an array where the element should be found 13 | * @param Comparable type 14 | * @return first found index of the element 15 | */ 16 | > int find(T array[], T key); 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.divideandconquer; 2 | 3 | public class BinaryExponentiation { 4 | 5 | public static void main(String args[]) { 6 | System.out.println(calculatePower(2, 30)); 7 | } 8 | 9 | // Function to calculate x^y 10 | // Time Complexity: O(logn) 11 | public static long calculatePower(long x, long y) { 12 | if (y == 0) { 13 | return 1; 14 | } 15 | long val = calculatePower(x, y / 2); 16 | val *= val; 17 | if (y % 2 == 1) { 18 | val *= x; 19 | } 20 | return val; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /* A Naive recursive implementation 4 | of 0-1 Knapsack problem */ 5 | public class BruteForceKnapsack { 6 | 7 | // A utility function that returns 8 | // maximum of two integers 9 | static int max(int a, int b) { 10 | return (a > b) ? a : b; 11 | } 12 | 13 | // Returns the maximum value that 14 | // can be put in a knapsack of 15 | // capacity W 16 | static int knapSack(int W, int wt[], int val[], int n) { 17 | // Base Case 18 | if (n == 0 || W == 0) { 19 | return 0; 20 | } 21 | 22 | // If weight of the nth item is 23 | // more than Knapsack capacity W, 24 | // then this item cannot be included 25 | // in the optimal solution 26 | if (wt[n - 1] > W) { 27 | return knapSack(W, wt, val, n - 1); 28 | } // Return the maximum of two cases: 29 | // (1) nth item included 30 | // (2) not included 31 | else { 32 | return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1)); 33 | } 34 | } 35 | 36 | // Driver code 37 | public static void main(String args[]) { 38 | int val[] = new int[]{60, 100, 120}; 39 | int wt[] = new int[]{10, 20, 30}; 40 | int W = 50; 41 | int n = val.length; 42 | System.out.println(knapSack(W, wt, val, n)); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java: -------------------------------------------------------------------------------- 1 | /** Author : Siddhant Swarup Mallick 2 | * Github : https://github.com/siddhant2002 3 | */ 4 | /** 5 | * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence. 6 | */ 7 | 8 | /** 9 | * Wikipedia Link - https://en.wikipedia.org/wiki/Golomb_sequence 10 | */ 11 | 12 | /** Program description - To find the Golomb sequence upto n */ 13 | 14 | package com.thealgorithms.dynamicprogramming; 15 | 16 | public class CountFriendsPairing { 17 | public static boolean countFriendsPairing(int n, int a[]) { 18 | int dp[] = new int[n + 1]; 19 | // array of n+1 size is created 20 | dp[0] = 1; 21 | // since 1st index position value is fixed so it's marked as 1 22 | for (int i = 1; i < n; i++) { 23 | dp[i] = 1 + dp[i - dp[dp[i - 1]]]; 24 | // formula for ith golomb sequence is dp(i) = 1 + dp(i – dp(dp(i - 1))) 25 | } 26 | for (int i = 1; i < n; i++) { 27 | if (a[i - 1] != dp[i]) { 28 | return false; 29 | // checks whether the calculated answer matches with the expected answer 30 | } 31 | } 32 | return true; 33 | // returns true if calculated answer matches with the expected answer 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | // A Dynamic Programming based solution 4 | // for 0-1 Knapsack problem 5 | public class DyanamicProgrammingKnapsack { 6 | 7 | static int max(int a, int b) { 8 | return (a > b) ? a : b; 9 | } 10 | 11 | // Returns the maximum value that can 12 | // be put in a knapsack of capacity W 13 | static int knapSack(int W, int wt[], int val[], int n) { 14 | int i, w; 15 | int K[][] = new int[n + 1][W + 1]; 16 | 17 | // Build table K[][] in bottom up manner 18 | for (i = 0; i <= n; i++) { 19 | for (w = 0; w <= W; w++) { 20 | if (i == 0 || w == 0) { 21 | K[i][w] = 0; 22 | } else if (wt[i - 1] <= w) { 23 | K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); 24 | } else { 25 | K[i][w] = K[i - 1][w]; 26 | } 27 | } 28 | } 29 | 30 | return K[n][W]; 31 | } 32 | 33 | // Driver code 34 | public static void main(String args[]) { 35 | int val[] = new int[]{60, 100, 120}; 36 | int wt[] = new int[]{10, 20, 30}; 37 | int W = 50; 38 | int n = val.length; 39 | System.out.println(knapSack(W, wt, val, n)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * DynamicProgramming solution for the Egg Dropping Puzzle 5 | */ 6 | public class EggDropping { 7 | 8 | // min trials with n eggs and m floors 9 | private static int minTrials(int n, int m) { 10 | 11 | int[][] eggFloor = new int[n + 1][m + 1]; 12 | int result, x; 13 | 14 | for (int i = 1; i <= n; i++) { 15 | eggFloor[i][0] = 0; // Zero trial for zero floor. 16 | eggFloor[i][1] = 1; // One trial for one floor 17 | } 18 | 19 | // j trials for only 1 egg 20 | for (int j = 1; j <= m; j++) { 21 | eggFloor[1][j] = j; 22 | } 23 | 24 | // Using bottom-up approach in DP 25 | for (int i = 2; i <= n; i++) { 26 | for (int j = 2; j <= m; j++) { 27 | eggFloor[i][j] = Integer.MAX_VALUE; 28 | for (x = 1; x <= j; x++) { 29 | result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); 30 | 31 | // choose min of all values for particular x 32 | if (result < eggFloor[i][j]) { 33 | eggFloor[i][j] = result; 34 | } 35 | } 36 | } 37 | } 38 | 39 | return eggFloor[n][m]; 40 | } 41 | 42 | public static void main(String args[]) { 43 | int n = 2, m = 4; 44 | // result outputs min no. of trials in worst case for n eggs and m floors 45 | int result = minTrials(n, m); 46 | System.out.println(result); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** Author : Siddhant Swarup Mallick 2 | * Github : https://github.com/siddhant2002 3 | */ 4 | 5 | /** Program description - To find the maximum subarray sum */ 6 | package com.thealgorithms.dynamicprogramming; 7 | 8 | public class KadaneAlgorithm { 9 | public static boolean max_Sum(int a[] , int predicted_answer) 10 | { 11 | int sum=a[0],running_sum=0; 12 | for(int k:a) 13 | { 14 | running_sum=running_sum+k; 15 | // running sum of all the indexs are stored 16 | sum=Math.max(sum,running_sum); 17 | // the max is stored inorder to the get the maximum sum 18 | if(running_sum<0) 19 | running_sum=0; 20 | // if running sum is negative then it is initialized to zero 21 | } 22 | // for-each loop is used to iterate over the array and find the maximum subarray sum 23 | return sum==predicted_answer; 24 | // It returns true if sum and predicted answer matches 25 | // The predicted answer is the answer itself. So it always return true 26 | } 27 | /** 28 | * OUTPUT : 29 | * Input - {89,56,98,123,26,75,12,40,39,68,91} 30 | * Output: it returns either true or false 31 | * 1st approach Time Complexity : O(n) 32 | * Auxiliary Space Complexity : O(1) 33 | */ 34 | } -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * A DynamicProgramming based solution for 0-1 Knapsack problem 5 | */ 6 | public class Knapsack { 7 | 8 | private static int knapSack(int W, int wt[], int val[], int n) throws IllegalArgumentException { 9 | if (wt == null || val == null) { 10 | throw new IllegalArgumentException(); 11 | } 12 | int i, w; 13 | int rv[][] = new int[n + 1][W + 1]; // rv means return value 14 | 15 | // Build table rv[][] in bottom up manner 16 | for (i = 0; i <= n; i++) { 17 | for (w = 0; w <= W; w++) { 18 | if (i == 0 || w == 0) { 19 | rv[i][w] = 0; 20 | } else if (wt[i - 1] <= w) { 21 | rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); 22 | } else { 23 | rv[i][w] = rv[i - 1][w]; 24 | } 25 | } 26 | } 27 | 28 | return rv[n][W]; 29 | } 30 | 31 | // Driver program to test above function 32 | public static void main(String args[]) { 33 | int val[] = new int[]{50, 100, 130}; 34 | int wt[] = new int[]{10, 20, 40}; 35 | int W = 50; 36 | System.out.println(knapSack(W, wt, val, val.length)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java: -------------------------------------------------------------------------------- 1 | /** Author : Siddhant Swarup Mallick 2 | * Github : https://github.com/siddhant2002 3 | */ 4 | 5 | 6 | /** Program description - To find the New Man Shanks Prime. */ 7 | /** Wikipedia Link - https://en.wikipedia.org/wiki/Newman%E2%80%93Shanks%E2%80%93Williams_prime */ 8 | 9 | package com.thealgorithms.dynamicprogramming; 10 | 11 | public class NewManShanksPrime { 12 | public static boolean nthManShanksPrime(int n , int expected_answer) 13 | { 14 | int a[] = new int[n+1]; 15 | // array of n+1 size is initialized 16 | a[0] = a[1] = 1; 17 | // The 0th and 1st index position values are fixed. They are initialized as 1 18 | for(int i=2;i<=n;i++) 19 | { 20 | a[i]=2*a[i-1]+a[i-2]; 21 | } 22 | // The loop is continued till n 23 | return a[n]==expected_answer; 24 | // returns true if calculated answer matches with expected answer 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | /** 4 | * A DynamicProgramming solution for Rod cutting problem Returns the best 5 | * obtainable price for a rod of length n and price[] as prices of different 6 | * pieces 7 | */ 8 | public class RodCutting { 9 | 10 | private static int cutRod(int[] price, int n) { 11 | int val[] = new int[n + 1]; 12 | val[0] = 0; 13 | 14 | for (int i = 1; i <= n; i++) { 15 | int max_val = Integer.MIN_VALUE; 16 | for (int j = 0; j < i; j++) { 17 | max_val = Math.max(max_val, price[j] + val[i - j - 1]); 18 | } 19 | 20 | val[i] = max_val; 21 | } 22 | 23 | return val[n]; 24 | } 25 | 26 | // main function to test 27 | public static void main(String args[]) { 28 | int[] arr = new int[]{2, 5, 13, 19, 20}; 29 | int result = cutRod(arr, arr.length); 30 | System.out.println("Maximum Obtainable Value is " + result); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | public class SubsetSum { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | int[] arr = new int[]{50, 4, 10, 15, 34}; 10 | assert subsetSum(arr, 64); 11 | /* 4 + 10 + 15 + 34 = 64 */ 12 | assert subsetSum(arr, 99); 13 | /* 50 + 15 + 34 = 99 */ 14 | assert !subsetSum(arr, 5); 15 | assert !subsetSum(arr, 66); 16 | } 17 | 18 | /** 19 | * Test if a set of integers contains a subset that sum to a given integer. 20 | * 21 | * @param arr the array contains integers. 22 | * @param sum target sum of subset. 23 | * @return {@code true} if subset exists, otherwise {@code false}. 24 | */ 25 | private static boolean subsetSum(int[] arr, int sum) { 26 | int n = arr.length; 27 | boolean[][] isSum = new boolean[n + 2][sum + 1]; 28 | 29 | isSum[n + 1][0] = true; 30 | for (int i = 1; i <= sum; i++) { 31 | isSum[n + 1][i] = false; 32 | } 33 | 34 | for (int i = n; i > 0; i--) { 35 | isSum[i][0] = true; 36 | for (int j = 1; j <= arr[i - 1] - 1; j++) { 37 | if (j <= sum) { 38 | isSum[i][j] = isSum[i + 1][j]; 39 | } 40 | } 41 | for (int j = arr[i - 1]; j <= sum; j++) { 42 | isSum[i][j] = (isSum[i + 1][j] || isSum[i + 1][j - arr[i - 1]]); 43 | } 44 | } 45 | 46 | return isSum[1][sum]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.dynamicprogramming; 2 | 3 | public class Sum_Of_Subset { 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] arr = {7, 3, 2, 5, 8}; 8 | int Key = 14; 9 | 10 | if (subsetSum(arr, arr.length - 1, Key)) { 11 | System.out.print("Yes, that sum exists"); 12 | } else { 13 | System.out.print("Nope, that number does not exist"); 14 | } 15 | } 16 | 17 | public static boolean subsetSum(int[] arr, int num, int Key) { 18 | if (Key == 0) { 19 | return true; 20 | } 21 | if (num < 0 || Key < 0) { 22 | return false; 23 | } 24 | 25 | boolean include = subsetSum(arr, num - 1, Key - arr[num]); 26 | boolean exclude = subsetSum(arr, num - 1, Key); 27 | 28 | return include || exclude; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AbsoluteMax { 6 | 7 | /** 8 | * Compares the numbers given as arguments to get the absolute max value. 9 | * 10 | * @param numbers The numbers to compare 11 | * @return The absolute max value 12 | */ 13 | public static int getMaxValue(int... numbers) { 14 | if (numbers.length == 0) { 15 | throw new IllegalArgumentException("Numbers array cannot be empty"); 16 | } 17 | 18 | var absMaxWrapper = new Object() { 19 | int value = numbers[0]; 20 | }; 21 | 22 | Arrays.stream(numbers) 23 | .skip(1) 24 | .filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value)) 25 | .forEach(number -> absMaxWrapper.value = number); 26 | 27 | return absMaxWrapper.value; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | 5 | public class AbsoluteMin { 6 | 7 | /** 8 | * Compares the numbers given as arguments to get the absolute min value. 9 | * 10 | * @param numbers The numbers to compare 11 | * @return The absolute min value 12 | */ 13 | public static int getMinValue(int... numbers) { 14 | if (numbers.length == 0) { 15 | throw new IllegalArgumentException("Numbers array cannot be empty"); 16 | } 17 | 18 | var absMinWrapper = new Object() { 19 | int value = numbers[0]; 20 | }; 21 | 22 | Arrays.stream(numbers) 23 | .skip(1) 24 | .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)) 25 | .forEach(number -> absMinWrapper.value = number); 26 | 27 | return absMinWrapper.value; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AbsoluteValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class AbsoluteValue { 4 | 5 | /** 6 | * Returns the absolute value of a number. 7 | * 8 | * @param number The number to be transformed 9 | * @return The absolute value of the {@code number} 10 | */ 11 | public static int getAbsValue(int number) { 12 | return number < 0 ? -number : number; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/AliquotSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.stream.IntStream; 4 | 5 | /** 6 | * In number theory, the aliquot sum s(n) of a positive integer n is the sum of 7 | * all proper divisors of n, that is, all divisors of n other than n itself. For 8 | * example, the proper divisors of 15 (that is, the positive divisors of 15 that 9 | * are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 10 | * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum 11 | */ 12 | public class AliquotSum { 13 | 14 | /** 15 | * Finds the aliquot sum of an integer number. 16 | * 17 | * @param number a positive integer 18 | * @return aliquot sum of given {@code number} 19 | */ 20 | public static int getAliquotValue(int number) { 21 | var sumWrapper = new Object() { 22 | int value = 0; 23 | }; 24 | 25 | IntStream.iterate(1, i -> ++i) 26 | .limit(number / 2) 27 | .filter(i -> number % i == 0) 28 | .forEach(i -> sumWrapper.value += i); 29 | 30 | return sumWrapper.value; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Armstrong.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * An Armstrong number is equal to the sum of the cubes of its digits. For 5 | * example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An 6 | * Armstrong number is often called Narcissistic number. 7 | * 8 | * @author Vivek 9 | */ 10 | public class Armstrong { 11 | 12 | /** 13 | * Checks whether a given number is an armstrong number or not. 14 | * 15 | * @param number number to check 16 | * @return {@code true} if given number is armstrong number, {@code false} 17 | * otherwise 18 | */ 19 | public boolean isArmstrong(int number) { 20 | long sum = 0; 21 | long number2 = number; 22 | while (number2 > 0) { 23 | long mod = number2 % 10; 24 | sum += Math.pow(mod, 3); 25 | number2 /= 10; 26 | } 27 | return sum == number; 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Average.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Calculate average of a list of numbers 5 | */ 6 | public class Average { 7 | 8 | private static final double SMALL_VALUE = 0.00001f; 9 | 10 | public static void main(String[] args) { 11 | assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE; 12 | assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE; 13 | assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE; 14 | int[] array = {2, 4, 10}; 15 | assert average(array) == 5; 16 | } 17 | 18 | /** 19 | * Calculate average of a list of numbers 20 | * 21 | * @param numbers array to store numbers 22 | * @return mean of given numbers 23 | */ 24 | public static double average(double[] numbers) { 25 | double sum = 0; 26 | for (double number : numbers) { 27 | sum += number; 28 | } 29 | return sum / numbers.length; 30 | } 31 | 32 | /** 33 | * find average value of int array 34 | * 35 | * @param array the array contains element and the sum does not excess long 36 | * value limit 37 | * @return average value 38 | */ 39 | public static int average(int[] array) { 40 | long sum = 0; 41 | for (int i = 0; i < array.length; ++i) { 42 | sum += array[i]; 43 | } 44 | return (int) (sum / array.length); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/BinaryPow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class BinaryPow { 4 | 5 | /** 6 | * Calculate a^p using binary exponentiation 7 | * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) 8 | * 9 | * @param a the base for exponentiation 10 | * @param p the exponent - must be greater than 0 11 | * @return a^p 12 | */ 13 | public static int binPow(int a, int p) { 14 | int res = 1; 15 | while (p > 0) { 16 | if ((p & 1) == 1) { 17 | res = res * a; 18 | } 19 | a = a * a; 20 | p >>>= 1; 21 | } 22 | return res; 23 | } 24 | 25 | /** 26 | * Function for testing binary exponentiation 27 | * 28 | * @param a the base 29 | * @param p the exponent 30 | */ 31 | public static void test(int a, int p) { 32 | int res = binPow(a, p); 33 | assert res == (int) Math.pow(a, p) : "Incorrect Implementation"; 34 | System.out.println(a + "^" + p + ": " + res); 35 | } 36 | 37 | /** 38 | * Main Function to call tests 39 | * 40 | * @param args System Line Arguments 41 | */ 42 | public static void main(String[] args) { 43 | // prints 2^15: 32768 44 | test(2, 15); 45 | 46 | // prints 3^9: 19683 47 | test(3, 9); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/BinomialCoefficient.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Java program for Binomial Cofficients 5 | * Binomial Cofficients: A binomial cofficient C(n,k) gives number ways 6 | * in which k objects can be chosen from n objects. 7 | * Wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient 8 | * 9 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey) 10 | * 11 | * */ 12 | 13 | public class BinomialCoefficient { 14 | 15 | /** 16 | * This method returns the number of ways in which k objects can be chosen from n objects 17 | * 18 | * @param total_objects Total number of objects 19 | * @param no_of_objects Number of objects to be chosen from total_objects 20 | * @return number of ways in which no_of_objects objects can be chosen from total_objects objects 21 | */ 22 | 23 | static int binomialCoefficient(int total_objects, int no_of_objects) { 24 | 25 | //Base Case 26 | if(no_of_objects > total_objects) { 27 | return 0; 28 | } 29 | 30 | //Base Case 31 | if(no_of_objects == 0 || no_of_objects == total_objects) { 32 | return 1; 33 | } 34 | 35 | //Recursive Call 36 | return binomialCoefficient(total_objects - 1, no_of_objects - 1) 37 | + binomialCoefficient(total_objects - 1, no_of_objects); 38 | } 39 | 40 | public static void main(String[] args) { 41 | System.out.println(binomialCoefficient(20,2)); 42 | 43 | //Output: 190 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Ceil.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class Ceil { 6 | 7 | public static void main(String[] args) { 8 | Random random = new Random(); 9 | for (int i = 1; i <= 1000; ++i) { 10 | double randomNumber = random.nextDouble(); 11 | assert ceil(randomNumber) == Math.ceil(randomNumber); 12 | } 13 | } 14 | 15 | /** 16 | * Returns the smallest (closest to negative infinity) 17 | * 18 | * @param number the number 19 | * @return the smallest (closest to negative infinity) of given 20 | * {@code number} 21 | */ 22 | public static double ceil(double number) { 23 | if (number - (int) number == 0) { 24 | return number; 25 | } else if (number - (int) number > 0) { 26 | return (int) (number + 1); 27 | } else { 28 | return (int) number; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Convolution.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Class for linear convolution of two discrete signals 5 | * 6 | * @author Ioannis Karavitsis 7 | * @version 1.0 8 | */ 9 | public class Convolution { 10 | 11 | /** 12 | * Discrete linear convolution function. Both input signals and the output 13 | * signal must start from 0. If you have a signal that has values before 0 14 | * then shift it to start from 0. 15 | * 16 | * @param A The first discrete signal 17 | * @param B The second discrete signal 18 | * @return The convolved signal 19 | */ 20 | public static double[] convolution(double[] A, double[] B) { 21 | double[] convolved = new double[A.length + B.length - 1]; 22 | 23 | /* 24 | The discrete convolution of two signals A and B is defined as: 25 | 26 | A.length 27 | C[i] = Σ (A[k]*B[i-k]) 28 | k=0 29 | 30 | It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1 31 | From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below. 32 | */ 33 | for (int i = 0; i < convolved.length; i++) { 34 | convolved[i] = 0; 35 | int k = Math.max(i - B.length + 1, 0); 36 | 37 | while (k < i + 1 && k < A.length) { 38 | convolved[i] += A[k] * B[i - k]; 39 | k++; 40 | } 41 | } 42 | 43 | return convolved; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/DistanceFormula.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class DistanceFormula { 4 | public static double distance(double x1, double y1, double x2, double y2) 5 | { 6 | double dX = Math.pow(x2-x1, 2); 7 | double dY = Math.pow(y2-x1, 2); 8 | double d = Math.sqrt(dX+dY); 9 | return d; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Factorial.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class Factorial { 4 | 5 | /* Driver Code */ 6 | public static void main(String[] args) { 7 | assert factorial(0) == 1; 8 | assert factorial(1) == 1; 9 | assert factorial(5) == 120; 10 | assert factorial(10) == 3628800; 11 | } 12 | 13 | /** 14 | * Calculate factorial N using iteration 15 | * 16 | * @param n the number 17 | * @return the factorial of {@code n} 18 | */ 19 | public static long factorial(int n) { 20 | if (n < 0) { 21 | throw new IllegalArgumentException("number is negative"); 22 | } 23 | long factorial = 1; 24 | for (int i = 1; i <= n; factorial *= i, ++i) 25 | ; 26 | return factorial; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FactorialRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class FactorialRecursion { 4 | 5 | /* Driver Code */ 6 | public static void main(String[] args) { 7 | assert factorial(0) == 1; 8 | assert factorial(1) == 1; 9 | assert factorial(2) == 2; 10 | assert factorial(3) == 6; 11 | assert factorial(5) == 120; 12 | } 13 | 14 | /** 15 | * Recursive FactorialRecursion Method 16 | * 17 | * @param n The number to factorial 18 | * @return The factorial of the number 19 | */ 20 | public static long factorial(int n) { 21 | if (n < 0) { 22 | throw new IllegalArgumentException("number is negative"); 23 | } 24 | return n == 0 || n == 1 ? 1 : n * factorial(n - 1); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FibonacciNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Fibonacci: 0 1 1 2 3 5 8 13 21 ... 5 | */ 6 | public class FibonacciNumber { 7 | 8 | public static void main(String[] args) { 9 | assert isFibonacciNumber(1); 10 | assert isFibonacciNumber(2); 11 | assert isFibonacciNumber(21); 12 | assert !isFibonacciNumber(9); 13 | assert !isFibonacciNumber(10); 14 | } 15 | 16 | /** 17 | * Check if a number is perfect square number 18 | * 19 | * @param number the number to be checked 20 | * @return true if {@code number} is perfect square, otherwise 21 | * false 22 | */ 23 | public static boolean isPerfectSquare(int number) { 24 | int sqrt = (int) Math.sqrt(number); 25 | return sqrt * sqrt == number; 26 | } 27 | 28 | /** 29 | * Check if a number is fibonacci number This is true if and only if at 30 | * least one of 5x^2+4 or 5x^2-4 is a perfect square 31 | * 32 | * @param number the number 33 | * @return true if {@code number} is fibonacci number, otherwise 34 | * false 35 | * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification 36 | */ 37 | public static boolean isFibonacciNumber(int number) { 38 | return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMax.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMax { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | Random random = new Random(); 13 | 14 | /* random size */ 15 | int size = random.nextInt(100) + 1; 16 | int[] array = new int[size]; 17 | 18 | /* init array with random numbers */ 19 | for (int i = 0; i < size; i++) { 20 | array[i] = random.nextInt() % 100; 21 | } 22 | 23 | assert Arrays.stream(array).max().getAsInt() == findMax(array); 24 | } 25 | 26 | /** 27 | * find max of array 28 | * 29 | * @param array the array contains element 30 | * @return max value of given array 31 | */ 32 | public static int findMax(int[] array) { 33 | int max = array[0]; 34 | for (int i = 1; i < array.length; ++i) { 35 | if (array[i] > max) { 36 | max = array[i]; 37 | } 38 | } 39 | return max; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/FindMin.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Arrays; 4 | import java.util.Random; 5 | 6 | public class FindMin { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | Random random = new Random(); 13 | 14 | /* random size */ 15 | int size = random.nextInt(100) + 1; 16 | int[] array = new int[size]; 17 | 18 | /* init array with random numbers */ 19 | for (int i = 0; i < size; i++) { 20 | array[i] = random.nextInt() % 100; 21 | } 22 | 23 | assert Arrays.stream(array).min().getAsInt() == findMin(array); 24 | } 25 | 26 | /** 27 | * Find the minimum number of an array of numbers. 28 | * 29 | * @param array the array contains element 30 | * @return min value 31 | */ 32 | public static int findMin(int[] array) { 33 | int min = array[0]; 34 | for (int i = 1; i < array.length; ++i) { 35 | if (array[i] < min) { 36 | min = array[i]; 37 | } 38 | } 39 | return min; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Floor.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class Floor { 6 | 7 | public static void main(String[] args) { 8 | Random random = new Random(); 9 | for (int i = 1; i <= 1000; ++i) { 10 | double randomNumber = random.nextDouble(); 11 | assert floor(randomNumber) == Math.floor(randomNumber); 12 | } 13 | } 14 | 15 | /** 16 | * Returns the largest (closest to positive infinity) 17 | * 18 | * @param number the number 19 | * @return the largest (closest to positive infinity) of given 20 | * {@code number} 21 | */ 22 | public static double floor(double number) { 23 | if (number - (int) number == 0) { 24 | return number; 25 | } else if (number - (int) number > 0) { 26 | return (int) number; 27 | } else { 28 | return (int) number - 1; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GCD.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * This is Euclid's algorithm which is used to find the greatest common 5 | * denominator Overide function name gcd 6 | * 7 | * @author Oskar Enmalm 3/10/17 8 | */ 9 | public class GCD { 10 | 11 | /** 12 | * get greatest common divisor 13 | * 14 | * @param num1 the first number 15 | * @param num2 the second number 16 | * @return gcd 17 | */ 18 | public static int gcd(int num1, int num2) { 19 | if (num1 < 0 || num2 < 0) { 20 | throw new ArithmeticException(); 21 | } 22 | 23 | if (num1 == 0 || num2 == 0) { 24 | return Math.abs(num1 - num2); 25 | } 26 | 27 | while (num1 % num2 != 0) { 28 | int remainder = num1 % num2; 29 | num1 = num2; 30 | num2 = remainder; 31 | } 32 | return num2; 33 | } 34 | 35 | /** 36 | * get greatest common divisor in array 37 | * 38 | * @param number contains number 39 | * @return gcd 40 | */ 41 | public static int gcd(int[] number) { 42 | int result = number[0]; 43 | for (int i = 1; i < number.length; i++) // call gcd function (input two value) 44 | { 45 | result = gcd(result, number[i]); 46 | } 47 | 48 | return result; 49 | } 50 | 51 | public static void main(String[] args) { 52 | int[] myIntArray = {4, 16, 32}; 53 | 54 | // call gcd function (input array) 55 | System.out.println(gcd(myIntArray)); // => 4 56 | System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GCDRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * @author https://github.com/shellhub/ 5 | */ 6 | public class GCDRecursion { 7 | 8 | public static void main(String[] args) { 9 | System.out.println(gcd(20, 15)); 10 | /* output: 5 */ 11 | System.out.println(gcd(10, 8)); 12 | /* output: 2 */ 13 | System.out.println(gcd(gcd(10, 5), gcd(5, 10))); 14 | /* output: 5 */ 15 | } 16 | 17 | /** 18 | * get greatest common divisor 19 | * 20 | * @param a the first number 21 | * @param b the second number 22 | * @return gcd 23 | */ 24 | public static int gcd(int a, int b) { 25 | 26 | if (a < 0 || b < 0) { 27 | throw new ArithmeticException(); 28 | } 29 | 30 | if (a == 0 || b == 0) { 31 | return Math.abs(a - b); 32 | } 33 | 34 | if (a % b == 0) { 35 | return b; 36 | } else { 37 | return gcd(b, a % b); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/GenericRoot.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Algorithm explanation: 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. 5 | */ 6 | public class GenericRoot { 7 | 8 | public static void main(String[] args) { 9 | int number1 = 1234; 10 | int number2 = 12345; 11 | int result1 = genericRoot(number1); 12 | int result2 = genericRoot(number2); 13 | System.out.println("Generic root of " + number1 + " is: " + result1); 14 | System.out.println("Generic root of " + number2 + " is: " + result2); 15 | } 16 | 17 | private static int genericRoot(int n) { 18 | int root = 0; 19 | while (n > 0 || root > 9) { 20 | if (n == 0) { 21 | n = root; 22 | root = 0; 23 | } 24 | root += n % 10; 25 | n /= 10; 26 | } 27 | return root; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/HeronsFormula.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Find the area of a triangle using only side lengths 5 | */ 6 | 7 | public class HeronsFormula { 8 | 9 | public static double Herons(int s1, int s2, int s3) 10 | { 11 | double a = s1; 12 | double b = s2; 13 | double c = s3; 14 | double s = (a + b + c)/2.0; 15 | double area = 0; 16 | area = Math.sqrt((s)*(s-a)*(s-b)*(s-c)); 17 | return area; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/LeonardoNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class LeonardoNumber { 4 | 5 | public static int leonardoNumber(int n) { 6 | if (n < 0) { 7 | return 0; 8 | } 9 | if (n == 0 || n == 1) { 10 | return 1; 11 | } 12 | return (leonardoNumber(n - 1) + leonardoNumber(n - 2) + 1); 13 | } 14 | 15 | public static void main(String args[]) { 16 | for (int i = 0; i < 20; i++) { 17 | System.out.print(leonardoNumber(i) + " "); 18 | } 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /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 class LucasSeries { 7 | 8 | public static void main(String[] args) { 9 | assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2; 10 | assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1; 11 | assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3; 12 | assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4; 13 | assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7; 14 | assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11; 15 | assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123; 16 | } 17 | 18 | /** 19 | * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 20 | * 123, ....) using recursion 21 | * 22 | * @param n nth 23 | * @return nth number of lucas series 24 | */ 25 | public static int lucasSeries(int n) { 26 | return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); 27 | } 28 | 29 | /** 30 | * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 31 | * 123, ....) using iteration 32 | * 33 | * @param n nth 34 | * @return nth number of lucas series 35 | */ 36 | public static int lucasSeriesIteration(int n) { 37 | int previous = 2; 38 | int current = 1; 39 | for (int i = 1; i < n; i++) { 40 | int next = previous + current; 41 | previous = current; 42 | current = next; 43 | } 44 | return previous; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MaxValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class MaxValue { 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | Random rand = new Random(); 12 | 13 | /* test 100 times using rand numbers */ 14 | for (int i = 1; i <= 100; ++i) { 15 | /* generate number from -50 to 49 */ 16 | int a = rand.nextInt(100) - 50; 17 | int b = rand.nextInt(100) - 50; 18 | assert max(a, b) == Math.max(a, b); 19 | } 20 | } 21 | 22 | /** 23 | * Returns the greater of two {@code int} values. That is, the result is the 24 | * argument closer to the value of {@link Integer#MAX_VALUE}. If the 25 | * arguments have the same value, the result is that same value. 26 | * 27 | * @param a an argument. 28 | * @param b another argument. 29 | * @return the larger of {@code a} and {@code b}. 30 | */ 31 | public static int max(int a, int b) { 32 | return a >= b ? a : b; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /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 class Median { 9 | 10 | public static void main(String[] args) { 11 | assert median(new int[]{0}) == 0; 12 | assert median(new int[]{1, 2}) == 1.5; 13 | assert median(new int[]{4, 1, 3, 2}) == 2.5; 14 | assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6; 15 | assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5; 16 | } 17 | 18 | /** 19 | * Calculate average median 20 | * 21 | * @param values number series 22 | * @return median of given {@code values} 23 | */ 24 | public static double median(int[] values) { 25 | Arrays.sort(values); 26 | int length = values.length; 27 | return length % 2 == 0 28 | ? (values[length / 2] + values[length / 2 - 1]) / 2.0 29 | : values[length / 2]; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/MinValue.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Random; 4 | 5 | public class MinValue { 6 | 7 | /** 8 | * Driver Code 9 | */ 10 | public static void main(String[] args) { 11 | Random rand = new Random(); 12 | 13 | /* test 100 times using rand numbers */ 14 | for (int i = 1; i <= 100; ++i) { 15 | /* generate number from -50 to 49 */ 16 | int a = rand.nextInt(100) - 50; 17 | int b = rand.nextInt(100) - 50; 18 | assert min(a, b) == Math.min(a, b); 19 | } 20 | } 21 | 22 | /** 23 | * Returns the smaller of two {@code int} values. That is, the result the 24 | * argument closer to the value of {@link Integer#MIN_VALUE}. If the 25 | * arguments have the same value, the result is that same value. 26 | * 27 | * @param a an argument. 28 | * @param b another argument. 29 | * @return the smaller of {@code a} and {@code b}. 30 | */ 31 | public static int min(int a, int b) { 32 | return a <= b ? a : b; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PalindromeNumber { 4 | 5 | public static void main(String[] args) { 6 | 7 | assert isPalindrome(12321); 8 | assert !isPalindrome(1234); 9 | assert isPalindrome(1); 10 | } 11 | 12 | /** 13 | * Check if {@code n} is palindrome number or not 14 | * 15 | * @param number the number 16 | * @return {@code true} if {@code n} is palindrome number, otherwise 17 | * {@code false} 18 | */ 19 | public static boolean isPalindrome(int number) { 20 | if (number < 0) { 21 | throw new IllegalArgumentException(number + ""); 22 | } 23 | int numberCopy = number; 24 | int reverseNumber = 0; 25 | while (numberCopy != 0) { 26 | int remainder = numberCopy % 10; 27 | reverseNumber = reverseNumber * 10 + remainder; 28 | numberCopy /= 10; 29 | } 30 | return number == reverseNumber; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/ParseInteger.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class ParseInteger { 4 | 5 | public static void main(String[] args) { 6 | assert parseInt("123") == Integer.parseInt("123"); 7 | assert parseInt("-123") == Integer.parseInt("-123"); 8 | assert parseInt("0123") == Integer.parseInt("0123"); 9 | assert parseInt("+123") == Integer.parseInt("+123"); 10 | } 11 | 12 | /** 13 | * Parse a string to integer 14 | * 15 | * @param s the string 16 | * @return the integer value represented by the argument in decimal. 17 | * @throws NumberFormatException if the {@code string} does not contain a 18 | * parsable integer. 19 | */ 20 | public static int parseInt(String s) { 21 | if (s == null || s.length() == 0) { 22 | throw new NumberFormatException("null"); 23 | } 24 | boolean isNegative = s.charAt(0) == '-'; 25 | boolean isPositive = s.charAt(0) == '+'; 26 | int number = 0; 27 | for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { 28 | if (!Character.isDigit(s.charAt(i))) { 29 | throw new NumberFormatException("s=" + s); 30 | } 31 | number = number * 10 + s.charAt(i) - '0'; 32 | } 33 | return isNegative ? -number : number; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /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 class PerfectCube { 7 | 8 | public static void main(String[] args) { 9 | assert !isPerfectCube(-1); 10 | assert isPerfectCube(0); 11 | assert isPerfectCube(1); 12 | assert !isPerfectCube(4); 13 | assert isPerfectCube(8); 14 | assert isPerfectCube(27); 15 | } 16 | 17 | /** 18 | * Check if a number is perfect cube or not 19 | * 20 | * @param number number to check 21 | * @return {@code true} if {@code number} is perfect cube, otherwise 22 | * {@code false} 23 | */ 24 | public static boolean isPerfectCube(int number) { 25 | int a = (int) Math.pow(number, 1.0 / 3); 26 | return a * a * a == number; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PerfectNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * In number theory, a perfect number is a positive integer that is equal to the 5 | * sum of its positive divisors, excluding the number itself. For instance, 6 6 | * has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a 7 | * perfect number. 8 | * 9 | *

10 | * link:https://en.wikipedia.org/wiki/Perfect_number 11 | */ 12 | public class PerfectNumber { 13 | 14 | public static void main(String[] args) { 15 | assert isPerfectNumber(6); 16 | /* 1 + 2 + 3 == 6 */ 17 | assert !isPerfectNumber(8); 18 | /* 1 + 2 + 4 != 8 */ 19 | assert isPerfectNumber(28); 20 | /* 1 + 2 + 4 + 7 + 14 == 28 */ 21 | } 22 | 23 | /** 24 | * Check if {@code number} is perfect number or not 25 | * 26 | * @param number the number 27 | * @return {@code true} if {@code number} is perfect number, otherwise false 28 | */ 29 | public static boolean isPerfectNumber(int number) { 30 | int sum = 0; 31 | /* sum of its positive divisors */ 32 | for (int i = 1; i < number; ++i) { 33 | if (number % i == 0) { 34 | sum += i; 35 | } 36 | } 37 | return sum == number; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /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 class PerfectSquare { 7 | 8 | public static void main(String[] args) { 9 | assert !isPerfectSquare(-1); 10 | assert !isPerfectSquare(3); 11 | assert !isPerfectSquare(5); 12 | assert isPerfectSquare(9); 13 | assert isPerfectSquare(100); 14 | } 15 | 16 | /** 17 | * Check if a number is perfect square number 18 | * 19 | * @param number the number to be checked 20 | * @return true if {@code number} is perfect square, otherwise 21 | * false 22 | */ 23 | public static boolean isPerfectSquare(int number) { 24 | int sqrt = (int) Math.sqrt(number); 25 | return sqrt * sqrt == number; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PiNilakantha.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PiNilakantha { 4 | 5 | // Calculates Pi using Nilakantha's infinite series 6 | // Method 2 in the following link explains the algorithm 7 | // https://en.scratch-wiki.info/wiki/Calculating_Pi 8 | public static void main(String[] args) { 9 | assert calculatePi(0) == 3.0; 10 | assert calculatePi(10) > 3.0; 11 | assert calculatePi(100) < 4.0; 12 | 13 | System.out.println(calculatePi(500)); 14 | } 15 | 16 | /** 17 | * @param iterations number of times the infinite series gets repeated Pi 18 | * get more accurate the higher the value of iterations is Values from 0 up 19 | * to 500 are allowed since double precision is not sufficient for more than 20 | * about 500 repetitions of this algorithm 21 | * @return the pi value of the calculation with a precision of x iteration 22 | */ 23 | public static double calculatePi(int iterations) { 24 | if (iterations < 0 || iterations > 500) { 25 | throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); 26 | } 27 | 28 | double pi = 3; 29 | int divCounter = 2; 30 | 31 | for (int i = 0; i < iterations; i++) { 32 | 33 | if (i % 2 == 0) { 34 | pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); 35 | } else { 36 | pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); 37 | } 38 | 39 | divCounter += 2; 40 | } 41 | return pi; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/Pow.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | // POWER (exponentials) Examples (a^b) 4 | public class Pow { 5 | 6 | public static void main(String[] args) { 7 | assert pow(2, 0) == Math.pow(2, 0); // == 1 8 | assert pow(0, 2) == Math.pow(0, 2); // == 0 9 | assert pow(2, 10) == Math.pow(2, 10); // == 1024 10 | assert pow(10, 2) == Math.pow(10, 2); // == 100 11 | } 12 | 13 | /** 14 | * Returns the value of the first argument raised to the power of the second 15 | * argument 16 | * 17 | * @param a the base. 18 | * @param b the exponent. 19 | * @return the value {@code a}{@code b}. 20 | */ 21 | public static long pow(int a, int b) { 22 | long result = 1; 23 | for (int i = 1; i <= b; i++) { 24 | result *= a; 25 | } 26 | return result; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PowRecursion.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class PowRecursion { 4 | 5 | public static void main(String[] args) { 6 | assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0; 7 | assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0; 8 | assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0; 9 | assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0; 10 | } 11 | 12 | /** 13 | * Returns the value of the first argument raised to the power of the second 14 | * argument 15 | * 16 | * @param a the base. 17 | * @param b the exponent. 18 | * @return the value {@code a}{@code b}. 19 | */ 20 | public static long pow(int a, int b) { 21 | return b == 0 ? 1 : a * pow(a, b - 1); 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 class PowerOfTwoOrNot { 8 | 9 | public static void main(String[] args) { 10 | assert !checkIfPowerOfTwoOrNot(0); 11 | assert checkIfPowerOfTwoOrNot(1); 12 | assert checkIfPowerOfTwoOrNot(8); 13 | assert checkIfPowerOfTwoOrNot(16); 14 | assert checkIfPowerOfTwoOrNot(1024); 15 | } 16 | 17 | /** 18 | * Checks whether given number is power of two or not. 19 | * 20 | * @param number the number to check 21 | * @return {@code true} if given number is power of two, otherwise 22 | * {@code false} 23 | */ 24 | public static boolean checkIfPowerOfTwoOrNot(int number) { 25 | return number != 0 && ((number & (number - 1)) == 0); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PrimeFactorization.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | 5 | public class PrimeFactorization { 6 | 7 | public static void main(String[] args) { 8 | System.out.println("## all prime factors ##"); 9 | Scanner scanner = new Scanner(System.in); 10 | System.out.print("Enter a number: "); 11 | int n = scanner.nextInt(); 12 | System.out.print(("printing factors of " + n + " : ")); 13 | pfactors(n); 14 | scanner.close(); 15 | } 16 | 17 | public static void pfactors(int n) { 18 | 19 | while (n % 2 == 0) { 20 | System.out.print(2 + " "); 21 | n /= 2; 22 | } 23 | 24 | for (int i = 3; i <= Math.sqrt(n); i += 2) { 25 | while (n % i == 0) { 26 | System.out.print(i + " "); 27 | n /= i; 28 | } 29 | } 30 | 31 | if (n > 2) { 32 | System.out.print(n); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PronicNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /* 4 | * Java program for Pronic Number 5 | * Pronic Number: A number n is a pronic number if 6 | * it is equal to product of two consecutive numbers m and m+1. 7 | * Wikipedia: https://en.wikipedia.org/wiki/Pronic_number 8 | * 9 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey) 10 | * 11 | * */ 12 | 13 | public class PronicNumber { 14 | 15 | /** 16 | * This method checks if the given number is pronic number or non-pronic number 17 | * 18 | * @param input_number Integer value which is to be checked if is a pronic number or not 19 | * @return true if input number is a pronic number, false otherwise 20 | */ 21 | static boolean isPronic(int input_number) { 22 | 23 | //Iterating from 0 to input_number 24 | for(int i = 0; i <= input_number; i++) { 25 | 26 | //Checking if product of i and (i+1) is equals input_number 27 | if(i * (i+1) == input_number && i != input_number) { 28 | 29 | //return true if product of i and (i+1) is equals input_number 30 | return true; 31 | } 32 | 33 | } 34 | 35 | //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number 36 | return false; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/PythagoreanTriple.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * https://en.wikipedia.org/wiki/Pythagorean_triple 5 | */ 6 | public class PythagoreanTriple { 7 | 8 | public static void main(String[] args) { 9 | assert isPythagTriple(3, 4, 5); 10 | assert isPythagTriple(5, 12, 13); 11 | assert isPythagTriple(6, 8, 10); 12 | assert !isPythagTriple(10, 20, 30); 13 | assert !isPythagTriple(6, 8, 100); 14 | assert !isPythagTriple(-1, -1, 1); 15 | } 16 | 17 | /** 18 | * Check if a,b,c are a Pythagorean Triple 19 | * 20 | * @param a x/y component length of a right triangle 21 | * @param b y/x component length of a right triangle 22 | * @param c hypotenuse length of a right triangle 23 | * @return boolean true if a, b, c satisfy the Pythagorean theorem, 24 | * otherwise 25 | * false 26 | */ 27 | public static boolean isPythagTriple(int a, int b, int c) { 28 | if (a <= 0 || b <= 0 || c <= 0) { 29 | return false; 30 | } else { 31 | return (a * a) + (b * b) == (c * c); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/ReverseNumber.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | import java.util.NoSuchElementException; 5 | import java.lang.IllegalStateException; 6 | 7 | public class ReverseNumber { 8 | 9 | public static void main(String[] args) { 10 | int number; 11 | int reverse = 0; 12 | 13 | try (Scanner sc = new Scanner(System.in)) { 14 | System.out.println("Enter a number:"); 15 | number = sc.nextInt(); 16 | } catch (NoSuchElementException | IllegalStateException e) { 17 | System.out.println("ERROR: Invalid input"); 18 | return; 19 | } 20 | 21 | while (number != 0) { 22 | int remainder = number % 10; 23 | 24 | reverse = reverse * 10 + remainder; 25 | number = number / 10; 26 | } 27 | 28 | System.out.println("The reverse of the given number is: " + reverse); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * Translates numbers into the Roman Numeral System. 5 | * 6 | * @see Roman 7 | * numerals 8 | * @author Sokratis Fotkatzikis 9 | * @version 1.0 10 | */ 11 | public class RomanNumeralUtil { 12 | 13 | private static final int MIN_VALUE = 1; 14 | private static final int MAX_VALUE = 5999; 15 | //1000-5999 16 | private static final String[] RN_M = {"", "M", "MM", "MMM", "MMMM", "MMMMM"}; 17 | //100-900 18 | private static final String[] RN_C = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; 19 | //10-90 20 | private static final String[] RN_X = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; 21 | //1-9 22 | private static final String[] RN_I = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; 23 | 24 | public static String generate(int number) { 25 | if (number < MIN_VALUE || number > MAX_VALUE) { 26 | throw new IllegalArgumentException( 27 | String.format( 28 | "The number must be in the range [%d, %d]", 29 | MIN_VALUE, 30 | MAX_VALUE 31 | ) 32 | ); 33 | } 34 | 35 | return RN_M[number / 1000] 36 | + RN_C[number % 1000 / 100] 37 | + RN_X[number % 100 / 10] 38 | + RN_I[number % 10]; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import java.util.Scanner; 4 | 5 | 6 | public class SquareRootWithBabylonianMethod { 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 square_Root(float num) 14 | { 15 | float a = num; 16 | float b = 1; 17 | double e = 0.000001; 18 | while (a - b > e) { 19 | a = (a + b) / 2; 20 | b = num / a; 21 | } 22 | return a; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/StandardDeviation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class StandardDeviation { 4 | 5 | public static double stdDev(double[] data) 6 | { 7 | double var = 0; 8 | double avg = 0; 9 | for (int i = 0; i < data.length; i++) 10 | { 11 | avg += data[i]; 12 | } 13 | avg /= data.length; 14 | for (int j = 0; j < data.length; j++) 15 | { 16 | var += Math.pow((data[j] - avg), 2); 17 | } 18 | var /= data.length; 19 | return Math.sqrt(var); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/StandardScore.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | public class StandardScore { 4 | public static double zScore(double num, double mean, double stdDev) 5 | { 6 | double z = (num - mean)/stdDev; 7 | return z; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/maths/TrinomialTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | /** 4 | * The trinomial triangle is a variation of Pascal’s triangle. The difference 5 | * between the two is that an entry in the trinomial triangle is the sum of the 6 | * three (rather than the two in Pasacal’s triangle) entries above it 7 | * 8 | * Example Input: n = 4 Output 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 9 | */ 10 | public class TrinomialTriangle { 11 | 12 | public static int TrinomialValue(int n, int k) { 13 | if (n == 0 && k == 0) { 14 | return 1; 15 | } 16 | 17 | if (k < -n || k > n) { 18 | return 0; 19 | } 20 | 21 | return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); 22 | } 23 | 24 | public static void printTrinomial(int n) { 25 | for (int i = 0; i < n; i++) { 26 | for (int j = -i; j <= 0; j++) { 27 | System.out.print(TrinomialValue(i, j) + " "); 28 | } 29 | 30 | for (int j = 1; j <= i; j++) { 31 | System.out.print(TrinomialValue(i, j) + " "); 32 | } 33 | 34 | System.out.println(); 35 | } 36 | } 37 | 38 | public static void main(String argc[]) { 39 | int n = 6; 40 | printTrinomial(n); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/minimizinglateness/lateness_data.txt: -------------------------------------------------------------------------------- 1 | 6 2 | 3 6 3 | 2 8 4 | 1 9 5 | 4 9 6 | 3 14 7 | 2 15 -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Collections; 4 | import java.util.PriorityQueue; 5 | 6 | /** 7 | * @author shrutisheoran 8 | */ 9 | public class MedianOfRunningArray { 10 | 11 | private PriorityQueue p1; 12 | private PriorityQueue p2; 13 | 14 | // Constructor 15 | public MedianOfRunningArray() { 16 | this.p1 = new PriorityQueue<>(Collections.reverseOrder()); // Max Heap 17 | this.p2 = new PriorityQueue<>(); // Min Heap 18 | } 19 | 20 | /* 21 | Inserting lower half of array to max Heap 22 | and upper half to min heap 23 | */ 24 | public void insert(Integer e) { 25 | p2.add(e); 26 | if (p2.size() - p1.size() > 1) { 27 | p1.add(p2.remove()); 28 | } 29 | } 30 | 31 | /* 32 | Returns median at any given point 33 | */ 34 | public Integer median() { 35 | if (p1.size() == p2.size()) { 36 | return (p1.peek() + p2.peek()) / 2; 37 | } 38 | return p1.size() > p2.size() ? p1.peek() : p2.peek(); 39 | } 40 | 41 | public static void main(String[] args) { 42 | /* 43 | Testing the median function 44 | */ 45 | 46 | MedianOfRunningArray p = new MedianOfRunningArray(); 47 | int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; 48 | for (int i = 0; i < 9; i++) { 49 | p.insert(arr[i]); 50 | System.out.print(p.median() + " "); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.misc; 2 | 3 | import java.util.Stack; 4 | import com.thealgorithms.datastructures.lists.SinglyLinkedList; 5 | 6 | /** 7 | * A simple way of knowing if a singly linked list is palindrome is to push all 8 | * the values into a Stack and then compare the list to popped vales from the 9 | * Stack. 10 | * 11 | * See more: 12 | * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ 13 | */ 14 | public class PalindromeSinglyLinkedList { 15 | 16 | public static void main(String[] args) { 17 | SinglyLinkedList linkedList = new SinglyLinkedList(); 18 | 19 | linkedList.insertHead(3); 20 | linkedList.insertNth(2, 1); 21 | linkedList.insertNth(1, 2); 22 | linkedList.insertNth(2, 3); 23 | linkedList.insertNth(3, 4); 24 | 25 | if (isPalindrome(linkedList)) { 26 | System.out.println("It's a palindrome list"); 27 | } else { 28 | System.out.println("It's NOT a palindrome list"); 29 | } 30 | } 31 | 32 | public static boolean isPalindrome(SinglyLinkedList linkedList) { 33 | boolean ret = true; 34 | Stack linkedListValues = new Stack<>(); 35 | 36 | for (int i = 0; i < linkedList.size(); i++) { 37 | linkedListValues.push(linkedList.getNth(i)); 38 | } 39 | 40 | for (int i = 0; i < linkedList.size(); i++) { 41 | if (linkedList.getNth(i) != linkedListValues.pop()) { 42 | ret = false; 43 | break; 44 | } 45 | } 46 | 47 | return ret; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/ArrayLeftRotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /* 4 | * A left rotation operation on an array 5 | * shifts each of the array's elements 6 | * given integer n unit to the left. 7 | * 8 | * @author sangin-lee 9 | */ 10 | 11 | public class ArrayLeftRotation { 12 | 13 | /* 14 | * Returns the result of left rotation of given array arr and integer n 15 | * 16 | * @param arr : int[] given array 17 | * 18 | * @param n : int given integer 19 | * 20 | * @return : int[] result of left rotation 21 | */ 22 | public static int[] rotateLeft(int[] arr, int n) { 23 | int size = arr.length; 24 | int[] dst = new int[size]; 25 | n = n % size; 26 | for(int i = 0; i < size; i++) { 27 | dst[i] = arr[n]; 28 | n = (n + 1) % size; 29 | } 30 | return dst; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/BoyerMoore.java: -------------------------------------------------------------------------------- 1 | /* this Code is the illustration of Boyer moore's voting algorithm to 2 | find the majority element is an array that appears more than n/2 times in an array 3 | where "n" is the length of the array. 4 | For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm 5 | */ 6 | package com.thealgorithms.others; 7 | 8 | import java.util.*; 9 | 10 | public class BoyerMoore { 11 | 12 | public static int findmajor(int[] a) { 13 | int count = 0; 14 | int cand = -1; 15 | for (int i = 0; i < a.length; i++) { 16 | if (count == 0) { 17 | cand = a[i]; 18 | count = 1; 19 | } else { 20 | if (a[i] == cand) { 21 | count++; 22 | } else { 23 | count--; 24 | } 25 | } 26 | } 27 | for (int i = 0; i < a.length; i++) { 28 | if (a[i] == cand) { 29 | count++; 30 | } 31 | } 32 | if (count > (a.length / 2)) { 33 | return cand; 34 | } 35 | return -1; 36 | } 37 | 38 | public static void main(String args[]) { 39 | Scanner input = new Scanner(System.in); 40 | int n = input.nextInt(); 41 | int a[] = new int[n]; 42 | for (int i = 0; i < n; i++) { 43 | a[i] = input.nextInt(); 44 | } 45 | System.out.println("the majority element is " + findmajor(a)); 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * @author Nishita Aggarwal 7 | *

8 | * Brian Kernighan’s Algorithm 9 | *

10 | * algorithm to count the number of set bits in a given number 11 | *

12 | * Subtraction of 1 from a number toggles all the bits (from right to left) till 13 | * the rightmost set bit(including the rightmost set bit). So if we subtract a 14 | * number by 1 and do bitwise & with itself i.e. (n & (n-1)), we unset the 15 | * rightmost set bit. 16 | *

17 | * If we do n & (n-1) in a loop and count the no of times loop executes we get 18 | * the set bit count. 19 | *

20 | *

21 | * Time Complexity: O(logn) 22 | */ 23 | public class BrianKernighanAlgorithm { 24 | 25 | /** 26 | * @param num: number in which we count the set bits 27 | * @return int: Number of set bits 28 | */ 29 | static int countSetBits(int num) { 30 | int cnt = 0; 31 | while (num != 0) { 32 | num = num & (num - 1); 33 | cnt++; 34 | } 35 | return cnt; 36 | } 37 | 38 | /** 39 | * @param args : command line arguments 40 | */ 41 | public static void main(String args[]) { 42 | Scanner sc = new Scanner(System.in); 43 | int num = sc.nextInt(); 44 | int setBitCount = countSetBits(num); 45 | System.out.println(setBitCount); 46 | sc.close(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /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 class CRC32 { 9 | 10 | public static void main(String[] args) { 11 | System.out.println(Integer.toHexString(crc32("Hello World"))); 12 | } 13 | 14 | public static int crc32(String str) { 15 | return crc32(str.getBytes()); 16 | } 17 | 18 | public static int crc32(byte[] data) { 19 | BitSet bitSet = BitSet.valueOf(data); 20 | int crc32 = 0xFFFFFFFF; // initial value 21 | for (int i = 0; i < data.length * 8; i++) { 22 | if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) { 23 | crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial 24 | } else { 25 | crc32 = (crc32 << 1); 26 | } 27 | } 28 | crc32 = Integer.reverse(crc32); // result reflect 29 | return crc32 ^ 0xFFFFFFFF; // final xor value 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/CountChar.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class CountChar { 6 | 7 | public static void main(String[] args) { 8 | Scanner input = new Scanner(System.in); 9 | System.out.print("Enter your text: "); 10 | String str = input.nextLine(); 11 | input.close(); 12 | System.out.println("There are " + CountCharacters(str) + " characters."); 13 | } 14 | 15 | /** 16 | * Count non space character in string 17 | * 18 | * @param str String to count the characters 19 | * @return number of character in the specified string 20 | */ 21 | private static int CountCharacters(String str) { 22 | return str.replaceAll("\\s", "").length(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/EulersFunction.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * You can read more about Euler's totient function 5 | * 6 | *

7 | * See https://en.wikipedia.org/wiki/Euler%27s_totient_function 8 | */ 9 | public class EulersFunction { 10 | // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time 11 | // complexity; 12 | 13 | public static int getEuler(int n) { 14 | int result = n; 15 | for (int i = 2; i * i <= n; i++) { 16 | if (n % i == 0) { 17 | while (n % i == 0) { 18 | n /= i; 19 | } 20 | result -= result / i; 21 | } 22 | } 23 | if (n > 1) { 24 | result -= result / n; 25 | } 26 | return result; 27 | } 28 | 29 | public static void main(String[] args) { 30 | for (int i = 1; i < 100; i++) { 31 | System.out.println(getEuler(i)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FibbonaciSeries.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | /** 6 | * Fibonacci sequence, and characterized by the fact that every number after the 7 | * first two is the sum of the two preceding ones. 8 | * 9 | *

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

13 | * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number 14 | * 15 | * Problem Statement: print all Fibonacci numbers that are smaller than your 16 | * given input N 17 | */ 18 | public class FibbonaciSeries { 19 | 20 | public static void main(String[] args) { 21 | // Get input from the user 22 | Scanner scan = new Scanner(System.in); 23 | int n = scan.nextInt(); 24 | int first = 0, second = 1; 25 | scan.close(); 26 | while (first <= n) { 27 | // print first fibo 0 then add second fibo into it while updating second as well 28 | System.out.println(first); 29 | int next = first + second; 30 | first = second; 31 | second = next; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/FloydTriangle.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class FloydTriangle { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); 10 | int r = sc.nextInt(), n = 0; 11 | sc.close(); 12 | for (int i = 0; i < r; i++) { 13 | for (int j = 0; j <= i; j++) { 14 | System.out.print(++n + " "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/GuassLegendre.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | /** 4 | * Guass Legendre Algorithm ref 5 | * https://en.wikipedia.org/wiki/Gauss–Legendre_algorithm 6 | * 7 | * @author AKS1996 8 | */ 9 | public class GuassLegendre { 10 | 11 | public static void main(String[] args) { 12 | for (int i = 1; i <= 3; ++i) { 13 | System.out.println(pi(i)); 14 | } 15 | } 16 | 17 | static double pi(int l) { 18 | /* 19 | * l: No of loops to run 20 | */ 21 | 22 | double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1; 23 | for (int i = 0; i < l; ++i) { 24 | double temp[] = update(a, b, t, p); 25 | a = temp[0]; 26 | b = temp[1]; 27 | t = temp[2]; 28 | p = temp[3]; 29 | } 30 | 31 | return Math.pow(a + b, 2) / (4 * t); 32 | } 33 | 34 | static double[] update(double a, double b, double t, double p) { 35 | double values[] = new double[4]; 36 | values[0] = (a + b) / 2; 37 | values[1] = Math.sqrt(a * b); 38 | values[2] = t - p * Math.pow(a - values[0], 2); 39 | values[3] = 2 * p; 40 | 41 | return values; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/HappyNumbersSeq.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Scanner; 6 | import java.util.Set; 7 | 8 | public class HappyNumbersSeq { 9 | private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); 10 | 11 | public static void main(String[] args) { 12 | Scanner in = new Scanner(System.in); 13 | System.out.print("Enter number: "); 14 | int n = in.nextInt(); 15 | while (n != 1 && !isSad(n)) { 16 | System.out.print(n + " "); 17 | n = sumSquares(n); 18 | } 19 | String res = n == 1 ? "1 Happy number" : "Sad number"; 20 | System.out.println(res); 21 | } 22 | 23 | private static int sumSquares(int n) { 24 | int s = 0; 25 | for (; n > 0; n /= 10) { 26 | int r = n % 10; 27 | s += r * r; 28 | } 29 | return s; 30 | } 31 | 32 | private static boolean isSad(int n) { 33 | return CYCLE_NUMS.contains(n); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/Krishnamurthy.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class Krishnamurthy { 6 | 7 | static int fact(int n) { 8 | int i, p = 1; 9 | for (i = n; i >= 1; i--) { 10 | p = p * i; 11 | } 12 | return p; 13 | } 14 | 15 | public static void main(String args[]) { 16 | Scanner sc = new Scanner(System.in); 17 | int a, b, s = 0; 18 | System.out.print("Enter the number : "); 19 | a = sc.nextInt(); 20 | int n = a; 21 | while (a > 0) { 22 | b = a % 10; 23 | s = s + fact(b); 24 | a = a / 10; 25 | } 26 | if (s == n) { 27 | System.out.print(n + " is a krishnamurthy number"); 28 | } else { 29 | System.out.print(n + " is not a krishnamurthy number"); 30 | } 31 | sc.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/PasswordGen.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collections; 5 | import java.util.List; 6 | import java.util.Random; 7 | 8 | /** 9 | * Creates a random password from ASCII letters Given password length bounds 10 | * 11 | * @author AKS1996 12 | * @date 2017.10.25 13 | */ 14 | class PasswordGen { 15 | 16 | public static void main(String args[]) { 17 | String password = generatePassword(8, 16); 18 | System.out.print("Password: " + password); 19 | } 20 | 21 | static String generatePassword(int min_length, int max_length) { 22 | Random random = new Random(); 23 | 24 | String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 25 | String lower = "abcdefghijklmnopqrstuvwxyz"; 26 | String numbers = "0123456789"; 27 | String specialChars = "!@#$%^&*(){}?"; 28 | 29 | String allChars = upper + lower + numbers + specialChars; 30 | 31 | List letters = new ArrayList(); 32 | for (char c : allChars.toCharArray()) { 33 | letters.add(c); 34 | } 35 | 36 | // Inbuilt method to randomly shuffle a elements of a list 37 | Collections.shuffle(letters); 38 | StringBuilder password = new StringBuilder(); 39 | 40 | // Note that size of the password is also random 41 | for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { 42 | password.append(letters.get(random.nextInt(letters.size()))); 43 | } 44 | 45 | return password.toString(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | 6 | /** 7 | * @author Varun Upadhyay (https://github.com/varunu28) 8 | */ 9 | public class RemoveDuplicateFromString { 10 | 11 | public static void main(String[] args) throws Exception { 12 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 13 | String inpStr = br.readLine(); 14 | 15 | System.out.println("Actual string is: " + inpStr); 16 | System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); 17 | 18 | br.close(); 19 | } 20 | 21 | /** 22 | * This method produces a string after removing all the duplicate characters 23 | * from input string and returns it Example: Input String - "aabbbccccddddd" 24 | * Output String - "abcd" 25 | * 26 | * @param s String from which duplicate characters have to be removed 27 | * @return string with only unique characters 28 | */ 29 | public static String removeDuplicate(String s) { 30 | if (s == null || s.isEmpty()) { 31 | return s; 32 | } 33 | 34 | StringBuilder sb = new StringBuilder(); 35 | int n = s.length(); 36 | 37 | for (int i = 0; i < n; i++) { 38 | if (sb.toString().indexOf(s.charAt(i)) == -1) { 39 | sb.append(String.valueOf(s.charAt(i))); 40 | } 41 | } 42 | 43 | return sb.toString(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/RootPrecision.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | public class RootPrecision { 6 | 7 | public static void main(String[] args) { 8 | // take input 9 | Scanner scn = new Scanner(System.in); 10 | 11 | // N is the input number 12 | int N = scn.nextInt(); 13 | 14 | // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. 15 | int P = scn.nextInt(); 16 | System.out.println(squareRoot(N, P)); 17 | 18 | scn.close(); 19 | } 20 | 21 | public static double squareRoot(int N, int P) { 22 | // rv means return value 23 | double rv; 24 | 25 | double root = Math.pow(N, 0.5); 26 | 27 | // calculate precision to power of 10 and then multiply it with root value. 28 | int precision = (int) Math.pow(10, P); 29 | root = root * precision; 30 | /*typecast it into integer then divide by precision and again typecast into double 31 | so as to have decimal points upto P precision */ 32 | 33 | rv = (int) root; 34 | return rv / precision; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/StackPostfixNotation.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.*; 4 | 5 | public class StackPostfixNotation { 6 | 7 | public static void main(String[] args) { 8 | Scanner scanner = new Scanner(System.in); 9 | String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +" 10 | System.out.println(postfixEvaluate(post)); 11 | scanner.close(); 12 | } 13 | 14 | // Evaluates the given postfix expression string and returns the result. 15 | public static int postfixEvaluate(String exp) { 16 | Stack s = new Stack(); 17 | Scanner tokens = new Scanner(exp); 18 | 19 | while (tokens.hasNext()) { 20 | if (tokens.hasNextInt()) { 21 | s.push(tokens.nextInt()); // If int then push to stack 22 | } else { // else pop top two values and perform the operation 23 | int num2 = s.pop(); 24 | int num1 = s.pop(); 25 | String op = tokens.next(); 26 | 27 | if (op.equals("+")) { 28 | s.push(num1 + num2); 29 | } else if (op.equals("-")) { 30 | s.push(num1 - num2); 31 | } else if (op.equals("*")) { 32 | s.push(num1 * num2); 33 | } else { 34 | s.push(num1 / num2); 35 | } 36 | 37 | // "+", "-", "*", "/" 38 | } 39 | } 40 | tokens.close(); 41 | return s.pop(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/ThreeSum.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Arrays; 4 | import java.util.Scanner; 5 | 6 | /** 7 | * To find triplet equals to given sum in complexity O(n*log(n)) 8 | * 9 | *

10 | * Array must be sorted 11 | * 12 | * @author Ujjawal Joshi 13 | * @date 2020.05.18 14 | *

15 | * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12 16 | * Explanation: There is a triplet (12, 3 and 9) present in the array whose sum 17 | * is 24. 18 | */ 19 | class ThreeSum { 20 | 21 | public static void main(String args[]) { 22 | Scanner sc = new Scanner(System.in); 23 | int n = sc.nextInt(); // Length of an array 24 | 25 | int a[] = new int[n]; 26 | 27 | for (int i = 0; i < n; i++) { 28 | a[i] = sc.nextInt(); 29 | } 30 | System.out.println("Target"); 31 | int n_find = sc.nextInt(); 32 | 33 | Arrays.sort(a); // Sort the array if array is not sorted 34 | 35 | for (int i = 0; i < n; i++) { 36 | 37 | int l = i + 1, r = n - 1; 38 | 39 | while (l < r) { 40 | if (a[i] + a[l] + a[r] == n_find) { 41 | System.out.println(a[i] + " " + a[l] + " " + a[r]); 42 | break; 43 | } // if you want all the triplets write l++;r--; insted of break; 44 | else if (a[i] + a[l] + a[r] < n_find) { 45 | l++; 46 | } else { 47 | r--; 48 | } 49 | } 50 | } 51 | 52 | sc.close(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/others/TowerOfHanoi.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import java.util.Scanner; 4 | 5 | class TowerOfHanoi { 6 | 7 | public static void shift(int n, String startPole, String intermediatePole, String endPole) { 8 | // if n becomes zero the program returns thus ending the loop. 9 | if (n != 0) { 10 | // Shift function is called in recursion for swapping the n-1 disc from the startPole to the 11 | // intermediatePole 12 | shift(n - 1, startPole, endPole, intermediatePole); 13 | System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing 14 | // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole 15 | // to the endPole 16 | shift(n - 1, intermediatePole, startPole, endPole); 17 | } 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.print("Enter number of discs on Pole 1: "); 22 | Scanner scanner = new Scanner(System.in); 23 | int numberOfDiscs = scanner.nextInt(); // input of number of discs on pole 1 24 | shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); // Shift function called 25 | scanner.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/JumpSearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | import com.thealgorithms.devutils.searches.SearchAlgorithm; 4 | 5 | public class JumpSearch implements SearchAlgorithm { 6 | 7 | public static void main(String[] args) { 8 | JumpSearch jumpSearch = new JumpSearch(); 9 | Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 10 | for (int i = 0; i < array.length; i++) { 11 | assert jumpSearch.find(array, i) == i; 12 | } 13 | assert jumpSearch.find(array, -1) == -1; 14 | assert jumpSearch.find(array, 11) == -1; 15 | } 16 | 17 | /** 18 | * Jump Search algorithm implements 19 | * 20 | * @param array the array contains elements 21 | * @param key to be searched 22 | * @return index of {@code key} if found, otherwise -1 23 | */ 24 | @Override 25 | public > int find(T[] array, T key) { 26 | int length = array.length; 27 | /* length of array */ 28 | int blockSize = (int) Math.sqrt(length); 29 | /* block size to be jumped */ 30 | 31 | int limit = blockSize; 32 | while (key.compareTo(array[limit]) > 0 && limit < array.length - 1) { 33 | limit = Math.min(limit + blockSize, array.length - 1); 34 | } 35 | 36 | for (int i = limit - blockSize; i <= limit; i++) { 37 | if (array[i] == key) { 38 | /* execute linear search */ 39 | return i; 40 | } 41 | } 42 | return -1; 43 | /* not found */ 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.searches; 2 | 3 | class PerfectBinarySearch { 4 | 5 | static int binarySearch(int[] arr, int target) { 6 | int low = 0; 7 | int high = arr.length - 1; 8 | 9 | while (low <= high) { 10 | int mid = (low + high) / 2; 11 | 12 | if (arr[mid] == target) { 13 | return mid; 14 | } else if (arr[mid] > target) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | public static void main(String[] args) { 24 | PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); 25 | int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 26 | assert BinarySearch.binarySearch(array, -1) == -1; 27 | assert BinarySearch.binarySearch(array, 11) == -1; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/BogoSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * @author Podshivalov Nikita (https://github.com/nikitap492) 7 | * @see SortAlgorithm 8 | */ 9 | public class BogoSort implements SortAlgorithm { 10 | 11 | private static final Random random = new Random(); 12 | 13 | private static > boolean isSorted(T[] array) { 14 | for (int i = 0; i < array.length - 1; i++) { 15 | if (SortUtils.less(array[i + 1], array[i])) { 16 | return false; 17 | } 18 | } 19 | return true; 20 | } 21 | 22 | // Randomly shuffles the array 23 | private static void nextPermutation(T[] array) { 24 | int length = array.length; 25 | 26 | for (int i = 0; i < array.length; i++) { 27 | int randomIndex = i + random.nextInt(length - i); 28 | SortUtils.swap(array, randomIndex, i); 29 | } 30 | } 31 | 32 | public > T[] sort(T[] array) { 33 | while (!isSorted(array)) { 34 | nextPermutation(array); 35 | } 36 | return array; 37 | } 38 | 39 | // Driver Program 40 | public static void main(String[] args) { 41 | // Integer Input 42 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 43 | 44 | BogoSort bogoSort = new BogoSort(); 45 | 46 | // print a sorted array 47 | SortUtils.print(bogoSort.sort(integers)); 48 | 49 | // String Input 50 | String[] strings = {"c", "a", "e", "b", "d"}; 51 | 52 | SortUtils.print(bogoSort.sort(strings)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/DNFSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class DNFSort { 4 | 5 | // Sort the input array, the array is assumed to 6 | // have values in {0, 1, 2} 7 | static void sort012(int a[], int arr_size) { 8 | int low = 0; 9 | int high = arr_size - 1; 10 | int mid = 0, temp = 0; 11 | while (mid <= high) { 12 | switch (a[mid]) { 13 | case 0: { 14 | temp = a[low]; 15 | a[low] = a[mid]; 16 | a[mid] = temp; 17 | low++; 18 | mid++; 19 | break; 20 | } 21 | case 1: 22 | mid++; 23 | break; 24 | case 2: { 25 | temp = a[mid]; 26 | a[mid] = a[high]; 27 | a[high] = temp; 28 | high--; 29 | break; 30 | } 31 | } 32 | } 33 | } 34 | 35 | /* Utility function to print array arr[] */ 36 | static void printArray(int arr[], int arr_size) { 37 | for (int i = 0; i < arr_size; i++) { 38 | System.out.print(arr[i] + " "); 39 | } 40 | System.out.println(""); 41 | } 42 | 43 | /*Driver function to check for above functions*/ 44 | public static void main(String[] args) { 45 | int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; 46 | int arr_size = arr.length; 47 | sort012(arr, arr_size); 48 | System.out.println("Array after seggregation "); 49 | printArray(arr, arr_size); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/GnomeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of gnome sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | */ 11 | public class GnomeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] arr) { 15 | int i = 1; 16 | int j = 2; 17 | while (i < arr.length) { 18 | if (less(arr[i - 1], arr[i])) { 19 | i = j++; 20 | } else { 21 | swap(arr, i - 1, i); 22 | if (--i == 0) { 23 | i = j++; 24 | } 25 | } 26 | } 27 | 28 | return null; 29 | } 30 | 31 | public static void main(String[] args) { 32 | Integer[] integers = {4, 23, 6, 78, 1, 26, 11, 23, 0, -6, 3, 54, 231, 9, 12}; 33 | String[] strings = {"c", "a", "e", "b", "d", "dd", "da", "zz", "AA", "aa", "aB", "Hb", "Z"}; 34 | GnomeSort gnomeSort = new GnomeSort(); 35 | 36 | gnomeSort.sort(integers); 37 | gnomeSort.sort(strings); 38 | 39 | System.out.println("After sort : "); 40 | print(integers); 41 | print(strings); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/InsertionSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.less; 4 | import static com.thealgorithms.sorts.SortUtils.print; 5 | 6 | class InsertionSort implements SortAlgorithm { 7 | 8 | /** 9 | * Generic insertion sort algorithm in increasing order. 10 | * 11 | * @param array the array to be sorted. 12 | * @param the class of array. 13 | * @return sorted array. 14 | */ 15 | @Override 16 | public > T[] sort(T[] array) { 17 | for (int i = 1; i < array.length; i++) { 18 | T insertValue = array[i]; 19 | int j; 20 | for (j = i - 1; j >= 0 && less(insertValue, array[j]); j--) { 21 | array[j + 1] = array[j]; 22 | } 23 | if (j != i - 1) { 24 | array[j + 1] = insertValue; 25 | } 26 | } 27 | return array; 28 | } 29 | 30 | /** 31 | * Driver Code 32 | */ 33 | public static void main(String[] args) { 34 | Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 35 | InsertionSort sort = new InsertionSort(); 36 | sort.sort(integers); 37 | print(integers); 38 | /* [1, 4, 6, 9, 12, 23, 54, 78, 231] */ 39 | 40 | String[] strings = {"c", "a", "e", "b", "d"}; 41 | sort.sort(strings); 42 | print(strings); 43 | /* [a, b, c, d, e] */ 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/PancakeSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | /** 6 | * Implementation of pancake sort 7 | * 8 | * @author Podshivalov Nikita (https://github.com/nikitap492) 9 | * @since 2018-04-10 10 | */ 11 | public class PancakeSort implements SortAlgorithm { 12 | 13 | @Override 14 | public > T[] sort(T[] array) { 15 | int size = array.length; 16 | 17 | for (int i = 0; i < size; i++) { 18 | T max = array[0]; 19 | int index = 0; 20 | for (int j = 0; j < size - i; j++) { 21 | if (less(max, array[j])) { 22 | max = array[j]; 23 | index = j; 24 | } 25 | } 26 | flip(array, index, array.length - 1 - i); 27 | } 28 | return array; 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | Integer[] arr = { 34 | 10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1, 2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1 35 | }; 36 | PancakeSort pancakeSort = new PancakeSort(); 37 | System.out.println("After sorting:"); 38 | pancakeSort.sort(arr); 39 | print(arr); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SelectionSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | public class SelectionSort implements SortAlgorithm { 4 | 5 | /** 6 | * Generic selection sort algorithm in increasing order. 7 | * 8 | * @param arr the array to be sorted. 9 | * @param the class of array. 10 | * @return sorted array. 11 | */ 12 | @Override 13 | public > T[] sort(T[] arr) { 14 | int n = arr.length; 15 | for (int i = 0; i < n - 1; i++) { 16 | int minIndex = i; 17 | for (int j = i + 1; j < n; j++) { 18 | if (arr[minIndex].compareTo(arr[j]) > 0) { 19 | minIndex = j; 20 | } 21 | } 22 | if (minIndex != i) { 23 | T temp = arr[i]; 24 | arr[i] = arr[minIndex]; 25 | arr[minIndex] = temp; 26 | } 27 | } 28 | return arr; 29 | } 30 | 31 | /** 32 | * Driver Code 33 | */ 34 | public static void main(String[] args) { 35 | 36 | Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 37 | SelectionSort selectionSort = new SelectionSort(); 38 | Integer[] sorted = selectionSort.sort(arr); 39 | for (int i = 0; i < sorted.length - 1; ++i) { 40 | assert sorted[i] <= sorted[i + 1]; 41 | } 42 | 43 | String[] strings = {"c", "a", "e", "b", "d"}; 44 | String[] sortedStrings = selectionSort.sort(strings); 45 | for (int i = 0; i < sortedStrings.length - 1; ++i) { 46 | assert strings[i].compareTo(strings[i + 1]) <= 0; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/ShellSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | public class ShellSort implements SortAlgorithm { 6 | 7 | /** 8 | * Implements generic shell sort. 9 | * 10 | * @param array the array to be sorted. 11 | * @param the type of elements in the array. 12 | * @return the sorted array. 13 | */ 14 | @Override 15 | public > T[] sort(T[] array) { 16 | int length = array.length; 17 | int gap = 1; 18 | 19 | /* Calculate gap for optimization purpose */ 20 | while (gap < length / 3) { 21 | gap = 3 * gap + 1; 22 | } 23 | 24 | for (; gap > 0; gap /= 3) { 25 | for (int i = gap; i < length; i++) { 26 | int j; 27 | T temp = array[i]; 28 | for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) { 29 | array[j] = array[j - gap]; 30 | } 31 | array[j] = temp; 32 | } 33 | } 34 | return array; 35 | } 36 | 37 | /* Driver Code */ 38 | public static void main(String[] args) { 39 | Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; 40 | 41 | ShellSort sort = new ShellSort(); 42 | sort.sort(toSort); 43 | for (int i = 0; i < toSort.length - 1; ++i) { 44 | assert toSort[i] <= toSort[i + 1]; 45 | } 46 | print(toSort); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/sorts/SimpleSort.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.sorts; 2 | 3 | import static com.thealgorithms.sorts.SortUtils.*; 4 | 5 | public class SimpleSort implements SortAlgorithm { 6 | 7 | @Override 8 | public > T[] sort(T[] array) { 9 | final int LENGTH = array.length; 10 | 11 | for (int i = 0; i < LENGTH; i++) { 12 | for (int j = i + 1; j < LENGTH; j++) { 13 | if (less(array[j], array[i])) { 14 | T element = array[j]; 15 | array[j] = array[i]; 16 | array[i] = element; 17 | } 18 | } 19 | } 20 | 21 | return array; 22 | } 23 | 24 | public static void main(String[] args) { 25 | // ==== Int ======= 26 | Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; 27 | System.out.print("unsorted: "); 28 | print(a); 29 | System.out.println(); 30 | 31 | new SimpleSort().sort(a); 32 | System.out.print("sorted: "); 33 | print(a); 34 | System.out.println(); 35 | 36 | // ==== String ======= 37 | String[] b = {"banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"}; 38 | System.out.print("unsorted: "); 39 | print(b); 40 | System.out.println(); 41 | 42 | new SimpleSort().sort(b); 43 | System.out.print("sorted: "); 44 | print(b); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /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 | int m = (i + j) / 2; 20 | sort(array, i, m); 21 | sort(array, m + 1, j); 22 | if (SortUtils.less(array[j], array[m])) { 23 | T temp = array[j]; 24 | array[j] = array[m]; 25 | array[m] = temp; 26 | } 27 | sort(array, i, j - 1); 28 | } 29 | 30 | public static void main(String[] args) { 31 | SlowSort slowSort = new SlowSort(); 32 | 33 | Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202, 98}; 34 | // Print integerArray unsorted 35 | SortUtils.print(integerArray); 36 | 37 | slowSort.sort(integerArray); 38 | // Print integerArray sorted 39 | SortUtils.print(integerArray); 40 | 41 | String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; 42 | // Print stringArray unsorted 43 | SortUtils.print(stringArray); 44 | 45 | slowSort.sort(stringArray); 46 | // Print stringArray sorted 47 | SortUtils.print(stringArray); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /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 | /** 14 | * Main method arrays sorting algorithms 15 | * 16 | * @param unsorted - an array should be sorted 17 | * @return a sorted array 18 | */ 19 | > T[] sort(T[] unsorted); 20 | 21 | /** 22 | * Auxiliary method for algorithms what wanted to work with lists from JCF 23 | * 24 | * @param unsorted - a list should be sorted 25 | * @return a sorted list 26 | */ 27 | @SuppressWarnings("unchecked") 28 | default > List sort(List unsorted) { 29 | return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Alphabetical.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Alphabetical order is a system whereby character strings are placed in order 5 | * based on the position of the characters in the conventional ordering of an 6 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 7 | */ 8 | class Alphabetical { 9 | 10 | public static void main(String[] args) { 11 | assert !isAlphabetical("123abc"); 12 | assert isAlphabetical("aBC"); 13 | assert isAlphabetical("abc"); 14 | assert !isAlphabetical("xyzabc"); 15 | assert isAlphabetical("abcxyz"); 16 | } 17 | 18 | /** 19 | * Check if a string is alphabetical order or not 20 | * 21 | * @param s a string 22 | * @return {@code true} if given string is alphabetical order, otherwise 23 | * {@code false} 24 | */ 25 | public static boolean isAlphabetical(String s) { 26 | s = s.toLowerCase(); 27 | for (int i = 0; i < s.length() - 1; ++i) { 28 | if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { 29 | return false; 30 | } 31 | } 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CharactersSame.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class CharactersSame { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | assert isAllCharactersSame(""); 10 | assert !isAllCharactersSame("aab"); 11 | assert isAllCharactersSame("aaa"); 12 | assert isAllCharactersSame("11111"); 13 | } 14 | 15 | /** 16 | * check if all the characters of a string are same 17 | * 18 | * @param s the string to check 19 | * @return {@code true} if all characters of a string are same, otherwise 20 | * {@code false} 21 | */ 22 | public static boolean isAllCharactersSame(String s) { 23 | for (int i = 1, length = s.length(); i < length; ++i) { 24 | if (s.charAt(i) != s.charAt(0)) { 25 | return false; 26 | } 27 | } 28 | return true; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/CheckVowels.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | /** 8 | * Vowel Count is a system whereby character strings are placed in order based 9 | * on the position of the characters in the conventional ordering of an 10 | * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order 11 | */ 12 | public class CheckVowels { 13 | private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); 14 | 15 | /** 16 | * Check if a string is has vowels or not 17 | * 18 | * @param input a string 19 | * @return {@code true} if given string has vowels, otherwise {@code false} 20 | */ 21 | public static boolean hasVowels(String input) { 22 | return countVowels(input) > 0; 23 | } 24 | 25 | /** 26 | * count the number of vowels 27 | * 28 | * @param input a string prints the count of vowels 29 | */ 30 | public static int countVowels(String input) { 31 | if (input == null) { 32 | return 0; 33 | } 34 | int cnt = 0; 35 | for (char c : input.toLowerCase().toCharArray()) { 36 | if (VOWELS.contains(c)) { 37 | ++cnt; 38 | } 39 | } 40 | return cnt; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | // Longest Palindromic Substring 4 | import java.util.Scanner; 5 | 6 | class LongestPalindromicSubstring { 7 | 8 | public static void main(String[] args) { 9 | Solution s = new Solution(); 10 | String str = ""; 11 | Scanner sc = new Scanner(System.in); 12 | System.out.print("Enter the string: "); 13 | str = sc.nextLine(); 14 | System.out.println("Longest substring is : " + s.longestPalindrome(str)); 15 | } 16 | } 17 | 18 | class Solution { 19 | 20 | public String longestPalindrome(String s) { 21 | if (s == null || s.length() == 0) { 22 | return ""; 23 | } 24 | int n = s.length(); 25 | String maxStr = ""; 26 | for (int i = 0; i < n; ++i) { 27 | for (int j = i; j < n; ++j) { 28 | if (isValid(s, i, j) == true) { 29 | if (j - i + 1 > maxStr.length()) { // update maxStr 30 | maxStr = s.substring(i, j + 1); 31 | } 32 | } 33 | } 34 | } 35 | return maxStr; 36 | } 37 | 38 | private boolean isValid(String s, int lo, int hi) { 39 | int n = hi - lo + 1; 40 | for (int i = 0; i < n / 2; ++i) { 41 | if (s.charAt(lo + i) != s.charAt(hi - i)) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Lower.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Lower { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toLowerCase(s).equals(s.toLowerCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to lower case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to lowercase. 20 | */ 21 | public static String toLowerCase(String s) { 22 | char[] values = s.toCharArray(); 23 | for (int i = 0; i < values.length; ++i) { 24 | if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { 25 | values[i] = Character.toLowerCase(values[i]); 26 | } 27 | } 28 | return new String(values); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Pangram.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Wikipedia: https://en.wikipedia.org/wiki/Pangram 5 | */ 6 | public class Pangram { 7 | 8 | /** 9 | * Driver Code 10 | */ 11 | public static void main(String[] args) { 12 | assert isPangram("The quick brown fox jumps over the lazy dog"); 13 | assert !isPangram("The quick brown fox jumps over the azy dog"); 14 | /* not exists l character */ 15 | } 16 | 17 | /** 18 | * Check if a string is a pangram string or not 19 | * 20 | * @param s string to check 21 | * @return {@code true} if given string is pangram, otherwise {@code false} 22 | */ 23 | public static boolean isPangram(String s) { 24 | boolean[] marked = new boolean[26]; 25 | /* by default all letters don't exists */ 26 | char[] values = s.toCharArray(); 27 | for (char value : values) { 28 | if (Character.isLetter(value)) { 29 | int index = Character.isUpperCase(value) ? value - 'A' : value - 'a'; 30 | marked[index] = true; 31 | /* mark current character exists */ 32 | } 33 | } 34 | 35 | for (boolean b : marked) { 36 | if (!b) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | /** 4 | * Reverse String using different version 5 | */ 6 | public class ReverseString { 7 | 8 | public static void main(String[] args) { 9 | assert reverse("abc123").equals("321cba"); 10 | assert reverse2("abc123").equals("321cba"); 11 | } 12 | 13 | /** 14 | * easiest way to reverses the string str and returns it 15 | * 16 | * @param str string to be reversed 17 | * @return reversed string 18 | */ 19 | public static String reverse(String str) { 20 | return new StringBuilder(str).reverse().toString(); 21 | } 22 | 23 | /** 24 | * second way to reverses the string str and returns it 25 | * 26 | * @param str string to be reversed 27 | * @return reversed string 28 | */ 29 | public static String reverse2(String str) { 30 | 31 | if (str == null || str.isEmpty()) { 32 | return str; 33 | } 34 | 35 | char[] value = str.toCharArray(); 36 | for (int i = 0, j = str.length() - 1; i < j; i++, j--) { 37 | char temp = value[i]; 38 | value[i] = value[j]; 39 | value[j] = temp; 40 | } 41 | return new String(value); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/Upper.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | public class Upper { 4 | 5 | /** 6 | * Driver Code 7 | */ 8 | public static void main(String[] args) { 9 | String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; 10 | for (String s : strings) { 11 | assert toUpperCase(s).equals(s.toUpperCase()); 12 | } 13 | } 14 | 15 | /** 16 | * Converts all of the characters in this {@code String} to upper case 17 | * 18 | * @param s the string to convert 19 | * @return the {@code String}, converted to uppercase. 20 | */ 21 | public static String toUpperCase(String s) { 22 | if (s == null || "".equals(s)) { 23 | return s; 24 | } 25 | char[] values = s.toCharArray(); 26 | for (int i = 0; i < values.length; ++i) { 27 | if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { 28 | values[i] = Character.toUpperCase(values[i]); 29 | } 30 | } 31 | return new String(values); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings ; 2 | import java.util.HashMap ; 3 | class longestNonRepeativeSubstring { 4 | 5 | public static int lengthOfLongestSubstring(String s) { 6 | 7 | int max = 0 , start = 0 , i = 0 ; 8 | HashMap< Character , Integer > map = new HashMap<>() ; 9 | 10 | while ( i < s.length() ) { 11 | 12 | char temp = s.charAt( i ) ; 13 | 14 | // adding key to map if not present 15 | if ( ! map.containsKey( temp ) ) 16 | map.put( temp , 0 ) ; 17 | 18 | // checking if the first value is the dublicate value 19 | else if ( s.charAt( start ) == temp ) 20 | start++ ; 21 | 22 | // checking if the previous value is dublicate value 23 | else if ( s.charAt( i - 1 ) == temp ) { 24 | if ( max < map.size() ) max = map.size() ; 25 | map = new HashMap<>() ; 26 | start = i ; 27 | i-- ; 28 | } 29 | 30 | // last possible place where dublicate value can be is between start and i 31 | else { 32 | if ( max < map.size() ) max = map.size() ; 33 | while ( s.charAt( start ) != temp ) { 34 | map.remove( s.charAt( start ) ) ; 35 | start++ ; 36 | } 37 | start++ ; 38 | } 39 | 40 | i++ ; 41 | 42 | } 43 | if ( max < map.size() ) max = map.size() ; 44 | return max ; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/zigZagPattern/README.md: -------------------------------------------------------------------------------- 1 | # About 2 | 3 | convert string into a zig-zagged string 4 | 5 | for example : 6 | 7 | string = "123456789" , numRows = 3 8 | ans = "159246837" 9 | explanation 10 | 1 5 9 11 | 2 4 6 8 12 | 3 7 13 | 14 | string = "HelloWorldKotlin" , k = 4 15 | ans = "HoteWrollolKildn" 16 | explanation 17 | H o t 18 | e W r o l 19 | l o l K i 20 | l d n 21 | 22 | # working 23 | 24 | if string size is smaller than numRows or numRows is smaller than 2 25 | than we can return string because it will make no changes to string. 26 | If not than 27 | we initiate three variable depth which is equalvalent to numRows , 28 | height which starts with 1 and start with starting index of string. 29 | than we generate spaces to skip using formula 2 + (( n - 1 ) * 2 ) 30 | for both height and depth 31 | with each iteration we decrement depth and increate height and start 32 | by one also we keep contantating character on to new string with first 33 | depth spaces and later height spaces that we generated using formula 34 | if not zero 35 | 36 | # beats 80% of submission on leetcode -------------------------------------------------------------------------------- /src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings.zigZagPattern; 2 | class zigZagPattern { 3 | 4 | public static String encode(String s, int numRows) { 5 | if ( numRows < 2 || s.length() < numRows ) return s ; 6 | int start = 0 , index = 0 , height = 1 , depth = numRows ; 7 | char[] zigZagedArray = new char[ s.length() ] ; 8 | while ( depth != 0 ) { 9 | int pointer = start , height_space = 2 + ( ( height - 2 ) * 2 ) , depth_space = 2 + ( ( depth - 2 ) * 2 ) ; 10 | boolean bool = true ; 11 | while ( pointer < s.length() ) { 12 | zigZagedArray[index++] = s.charAt( pointer ) ; 13 | if ( height_space == 0 ) pointer += depth_space ; 14 | else if ( depth_space == 0 ) pointer += height_space ; 15 | else if ( bool ) { 16 | pointer += depth_space ; 17 | bool = false ; 18 | } else { 19 | pointer += height_space ; 20 | bool = true ; 21 | } 22 | } 23 | height++ ; 24 | depth-- ; 25 | start++ ; 26 | } 27 | return new String( zigZagedArray ) ; 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/CombinationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | import java.util.TreeSet; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | public class CombinationTest { 12 | @Test 13 | void testNoElement() 14 | { 15 | List> result = Combination.combination(new Integer[]{1, 2}, 0); 16 | assertTrue(result == null); 17 | } 18 | @Test 19 | void testLengthOne() 20 | { 21 | List> result = Combination.combination(new Integer[]{1, 2}, 1); 22 | assertTrue(result.get(0).iterator().next() == 1); 23 | assertTrue(result.get(1).iterator().next() == 2); 24 | } 25 | @Test 26 | void testLengthTwo() 27 | { 28 | List> result = Combination.combination(new Integer[]{1, 2}, 2); 29 | Integer[] arr = result.get(0).toArray(new Integer[2]); 30 | assertTrue(arr[0] == 1); 31 | assertTrue(arr[1] == 2); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/backtracking/PermutationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.backtracking; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | public class PermutationTest { 11 | @Test 12 | void testNoElement() 13 | { 14 | List result = Permutation.permutation(new Integer[]{}); 15 | assertEquals(result.get(0).length, 0); 16 | } 17 | @Test 18 | void testSingleElement() 19 | { 20 | List result = Permutation.permutation(new Integer[]{1}); 21 | assertEquals(result.get(0)[0], 1); 22 | } 23 | @Test 24 | void testMultipleElements() 25 | { 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 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/ciphers/BlowfishTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.ciphers; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 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 | 14 | //given 15 | String plainText = "123456abcd132536"; 16 | String key = "aabb09182736ccdd"; 17 | String expectedOutput = "d748ec383d3405f7"; 18 | 19 | //when 20 | String cipherText = blowfish.encrypt(plainText, key); 21 | 22 | //then 23 | assertEquals(expectedOutput, cipherText); 24 | 25 | } 26 | 27 | @Test 28 | void testDecrypt() { 29 | 30 | //given 31 | String cipherText = "d748ec383d3405f7"; 32 | String key = "aabb09182736ccdd"; 33 | String expectedOutput = "123456abcd132536"; 34 | 35 | //when 36 | String plainText = blowfish.decrypt(cipherText, key); 37 | 38 | //then 39 | assertEquals(expectedOutput, plainText); 40 | 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.heaps; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class FibonacciHeapTest{ 7 | 8 | @Test 9 | void testHeap(){ 10 | FibonacciHeap fibonacciHeap = new FibonacciHeap(); 11 | fibonacciHeap.insert(5); 12 | fibonacciHeap.insert(3); 13 | fibonacciHeap.insert(1); 14 | fibonacciHeap.insert(18); 15 | fibonacciHeap.insert(33); 16 | 17 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 1); 18 | fibonacciHeap.deleteMin(); 19 | Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 3); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.datastructures.bloomfilter; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | 7 | public class BloomFilterTest { 8 | 9 | @Test 10 | public void test1(){ 11 | BloomFilter bloomFilter = new BloomFilter<>(3,10); 12 | bloomFilter.insert(3); 13 | bloomFilter.insert(17); 14 | 15 | Assertions.assertTrue(bloomFilter.contains(3)); 16 | Assertions.assertTrue(bloomFilter.contains(17)); 17 | } 18 | 19 | @Test 20 | public void test2(){ 21 | BloomFilter bloomFilter = new BloomFilter<>(4,20); 22 | bloomFilter.insert("omar"); 23 | bloomFilter.insert("mahamid"); 24 | 25 | Assertions.assertTrue(bloomFilter.contains("omar")); 26 | Assertions.assertTrue(bloomFilter.contains("mahamid")); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | import static org.junit.jupiter.api.Assertions.assertThrows; 7 | 8 | public class AbsoluteMaxTest { 9 | 10 | @Test 11 | void testGetMaxValue() { 12 | assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16)); 13 | assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2)); 14 | } 15 | 16 | @Test 17 | void testGetMaxValueWithNoArguments() { 18 | Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMax.getMaxValue()); 19 | assertEquals("Numbers array cannot be empty", exception.getMessage()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | import static org.junit.jupiter.api.Assertions.assertThrows; 7 | 8 | public class AbsoluteMinTest { 9 | 10 | @Test 11 | void testGetMinValue() { 12 | assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16)); 13 | assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2)); 14 | } 15 | 16 | @Test 17 | void testGetMinValueWithNoArguments() { 18 | Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); 19 | assertEquals("Numbers array cannot be empty", exception.getMessage()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.util.concurrent.ThreadLocalRandom; 6 | import java.util.stream.Stream; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | 10 | public class AbsoluteValueTest { 11 | 12 | @Test 13 | void testGetAbsValue() { 14 | Stream.generate(() -> ThreadLocalRandom.current().nextInt()) 15 | .limit(1000) 16 | .forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/AliquotSumTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 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 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/ArmstrongTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | /** 8 | * @author Vivek 9 | * @since 15/03/22 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)).isFalse(); 21 | assertThat(armstrong.isArmstrong(200)).isFalse(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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 | 7 | public class AverageTest { 8 | double [] numbers = {3, 6, 9, 12, 15, 18, 21}; 9 | @Test 10 | public void testAverage() { 11 | 12 | Assertions.assertEquals(12, Average.average(numbers)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/DistanceFormulaTest.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 DistanceFormulaTest 7 | { 8 | @Test 9 | void test1() 10 | { 11 | Assertions.assertEquals(DistanceFormula.distance(1,1,2,2), 1.4142135623730951); 12 | } 13 | @Test 14 | void test2() 15 | { 16 | Assertions.assertEquals(DistanceFormula.distance(1,3,8,0), 7.0710678118654755); 17 | } 18 | @Test 19 | void test3() 20 | { 21 | Assertions.assertEquals(DistanceFormula.distance(2.4,9.1,55.1,100), 110.91911467371168); 22 | } 23 | @Test 24 | void test4() 25 | { 26 | Assertions.assertEquals(DistanceFormula.distance(1000,13,20000,84), 19022.067605809836); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FactorialTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.*; 5 | 6 | 7 | 8 | public class FactorialTest { 9 | 10 | @Test 11 | public void test() { 12 | Factorial fact = new Factorial(); 13 | assertEquals(120,fact.factorial(5)); 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FindMaxTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | public class FindMaxTest { 7 | 8 | @Test 9 | public void testFindMaxValue(){ 10 | assertEquals(10, FindMax.findMax(new int[] {1,2,3,4,5,6,7,8,9,10})); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/FindMinTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | public class FindMinTest { 7 | @Test 8 | public void testFindMinValue(){ 9 | assertEquals(1, FindMin.findMin(new int[] {1,2,3,4,5,6,7,8,9,10})); 10 | } 11 | 12 | @Test 13 | public void test1(){ 14 | assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9})); 15 | } 16 | 17 | @Test 18 | public void test2(){ 19 | assertEquals(0, FindMin.findMin(new int[] {0, 192, 384, 576})); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/GCDTest.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 GCDTest { 7 | @Test 8 | void test1() { 9 | Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1,0)); 10 | } 11 | 12 | @Test 13 | void test2() { 14 | Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2)); 15 | } 16 | 17 | @Test 18 | void test3() { 19 | Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3)); 20 | } 21 | 22 | @Test 23 | void test4() { 24 | Assertions.assertEquals(GCD.gcd(0, 2), 2); 25 | } 26 | 27 | @Test 28 | void test5() { 29 | Assertions.assertEquals(GCD.gcd(10, 0), 10); 30 | } 31 | 32 | @Test 33 | void test6() { 34 | Assertions.assertEquals(GCD.gcd(1, 0), 1); 35 | } 36 | 37 | @Test 38 | void test7() { 39 | Assertions.assertEquals(GCD.gcd(9, 6), 3); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/GaussianTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import java.util.ArrayList; 5 | 6 | import static com.thealgorithms.maths.Gaussian.gaussian; 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | 9 | public class GaussianTest { 10 | 11 | // easy pass test for the whole class. Matrix of 2*3. 12 | @Test 13 | void passTest1() 14 | { 15 | ArrayList list = new ArrayList(); 16 | ArrayList gaussian = new ArrayList(); 17 | ArrayList answer = new ArrayList(); 18 | answer.add(0.0); 19 | answer.add(1.0); 20 | 21 | int matrixSize = 2; 22 | list.add(1.0); 23 | list.add(1.0); 24 | list.add(1.0); 25 | list.add(2.0); 26 | list.add(1.0); 27 | list.add(1.0); 28 | gaussian=gaussian(matrixSize,list); 29 | 30 | assertEquals(answer,gaussian); 31 | } 32 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/HeronsFormulaTest.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 HeronsFormulaTest { 7 | @Test 8 | void test1() 9 | { 10 | Assertions.assertEquals(HeronsFormula.Herons(3,4,5), 6.0); 11 | } 12 | @Test 13 | void test2() 14 | { 15 | Assertions.assertEquals(HeronsFormula.Herons(24,30,18), 216.0); 16 | } 17 | @Test 18 | void test3() 19 | { 20 | Assertions.assertEquals(HeronsFormula.Herons(1,1,1), 0.4330127018922193); 21 | } 22 | @Test 23 | void test4() 24 | { 25 | Assertions.assertEquals(HeronsFormula.Herons(4,5,8), 8.181534085976786); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import java.util.ArrayList; 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class KaprekarNumbersTest { 8 | 9 | @Test 10 | void testFor1() 11 | { 12 | assertTrue(KaprekarNumbers.isKaprekarNumber(1)); 13 | } 14 | 15 | @Test 16 | void testFor45() 17 | { 18 | assertTrue(KaprekarNumbers.isKaprekarNumber(45)); 19 | } 20 | 21 | @Test 22 | void testFor297() 23 | { 24 | assertTrue(KaprekarNumbers.isKaprekarNumber(297)); 25 | } 26 | 27 | @Test 28 | void testFor2223() 29 | { 30 | assertTrue(KaprekarNumbers.isKaprekarNumber(2223)); 31 | } 32 | 33 | @Test 34 | void testFor857143() 35 | { 36 | assertTrue(KaprekarNumbers.isKaprekarNumber(857143)); 37 | } 38 | 39 | 40 | @Test 41 | void testFor3() 42 | { 43 | assertFalse(KaprekarNumbers.isKaprekarNumber(3)); 44 | } 45 | 46 | @Test 47 | void testFor26() 48 | { 49 | assertFalse(KaprekarNumbers.isKaprekarNumber(26)); 50 | } 51 | 52 | @Test 53 | void testFor98() 54 | { 55 | assertFalse(KaprekarNumbers.isKaprekarNumber(98)); 56 | } 57 | 58 | @Test 59 | void testForRangeOfNumber() { try { 60 | ArrayList rangedNumbers = KaprekarNumbers.kaprekarNumberInRange(1,100000); 61 | long[] allTheNumbers = {1, 9, 45, 55, 99, 297, 703, 999, 2223, 2728, 4950, 5050, 7272, 7777, 9999, 17344, 22222, 77778, 82656, 95121, 99999}; 62 | for (long i:allTheNumbers) { 63 | assert rangedNumbers.contains(i); 64 | } 65 | } catch (Exception e) { 66 | assert false; 67 | } 68 | } 69 | 70 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PascalTriangleTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class PascalTriangleTest { 8 | 9 | @Test 10 | void testForOne() { 11 | int[][] result = PascalTriangle.pascal(1); 12 | int[][] expected = {{1}}; 13 | assertArrayEquals(result, expected); 14 | } 15 | 16 | @Test 17 | void testForTwo() { 18 | int[][] result = PascalTriangle.pascal(2); 19 | int[][] expected = {{1, 0}, {1, 1}}; 20 | assertArrayEquals(result, expected); 21 | } 22 | 23 | @Test 24 | void testForFive() { 25 | int[][] result = PascalTriangle.pascal(5); 26 | int[][] expected = {{1, 0, 0, 0, 0}, 27 | {1, 1, 0, 0, 0}, 28 | {1, 2, 1, 0, 0}, 29 | {1, 3, 3, 1, 0}, 30 | {1, 4, 6, 4, 1} 31 | }; 32 | assertArrayEquals(result, expected); 33 | } 34 | 35 | @Test 36 | void testForEight() { 37 | int[][] result = PascalTriangle.pascal(8); 38 | int[][] expected = {{1, 0, 0, 0, 0, 0, 0, 0}, 39 | {1, 1, 0, 0, 0, 0, 0, 0}, 40 | {1, 2, 1, 0, 0, 0, 0, 0}, 41 | {1, 3, 3, 1, 0, 0, 0, 0}, 42 | {1, 4, 6, 4, 1, 0, 0, 0}, 43 | {1, 5, 10, 10, 5, 1, 0, 0}, 44 | {1, 6, 15, 20, 15, 6, 1, 0}, 45 | {1, 7, 21, 35, 35, 21, 7, 1} 46 | }; 47 | assertArrayEquals(expected, result); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PrimeCheckTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PrimeCheckTest { 7 | @Test 8 | void test1() { 9 | Assertions.assertTrue(PrimeCheck.isPrime(2)); 10 | } 11 | 12 | @Test 13 | void test2() { 14 | Assertions.assertFalse(PrimeCheck.isPrime(-1)); 15 | } 16 | 17 | @Test 18 | void test3() { 19 | Assertions.assertFalse(PrimeCheck.isPrime(4)); 20 | } 21 | 22 | @Test 23 | void test4() { 24 | Assertions.assertTrue(PrimeCheck.isPrime(5)); 25 | } 26 | 27 | @Test 28 | void test5() { 29 | Assertions.assertFalse(PrimeCheck.isPrime(15)); 30 | } 31 | 32 | @Test 33 | void test6() { 34 | Assertions.assertTrue(PrimeCheck.isPrime(11)); 35 | } 36 | 37 | @Test 38 | void test7() { 39 | Assertions.assertFalse(PrimeCheck.isPrime(49)); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PronicNumberTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class PronicNumberTest { 8 | 9 | @Test 10 | void testForPronicNumber() { 11 | 12 | //given 13 | int number = 30; 14 | 15 | //when 16 | boolean result = PronicNumber.isPronic(number); 17 | 18 | //then 19 | assertTrue(result); 20 | } 21 | 22 | @Test 23 | void testForNonPronicNumber() { 24 | 25 | //given 26 | int number = 21; 27 | 28 | //when 29 | boolean result = PronicNumber.isPronic(number); 30 | 31 | //then 32 | assertFalse(result); 33 | } 34 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | public class PythagoreanTripleTest { 7 | @Test 8 | public void Testpythagoreantriple(){ 9 | 10 | assertEquals(true, PythagoreanTriple.isPythagTriple(3,4,5)); 11 | assertEquals(true, PythagoreanTriple.isPythagTriple(6,8,10)); 12 | assertEquals(true, PythagoreanTriple.isPythagTriple(9,12,15)); 13 | assertEquals(true, PythagoreanTriple.isPythagTriple(12,16,20)); 14 | assertEquals(true, PythagoreanTriple.isPythagTriple(15,20,25)); 15 | assertEquals(true, PythagoreanTriple.isPythagTriple(18,24,30)); 16 | assertEquals(false, PythagoreanTriple.isPythagTriple(5,20,30)); 17 | assertEquals(false, PythagoreanTriple.isPythagTriple(6,8,100)); 18 | assertEquals(false, PythagoreanTriple.isPythagTriple(-2,-2,2)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /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 | @Test 8 | void testfor4(){ 9 | Assertions.assertEquals(2,SquareRootWithBabylonianMethod.square_Root(4)); 10 | } 11 | 12 | @Test 13 | void testfor1(){ 14 | Assertions.assertEquals(1,SquareRootWithBabylonianMethod.square_Root(1)); 15 | } 16 | 17 | @Test 18 | void testfor2(){ 19 | Assertions.assertEquals(1.4142135381698608,SquareRootWithBabylonianMethod.square_Root(2)); 20 | } 21 | 22 | @Test 23 | void testfor625(){ 24 | Assertions.assertEquals(25,SquareRootWithBabylonianMethod.square_Root(625)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /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 | @Test 8 | void test1() 9 | { 10 | double[] t1 = new double[]{1,1,1,1,1}; 11 | Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); 12 | } 13 | @Test 14 | void test2() 15 | { 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 | @Test 20 | void test3() 21 | { 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 | @Test 26 | void test4() 27 | { 28 | double[] t4 = new double[]{3.14, 2.22222, 9.89898989, 100.00045, 56.7}; 29 | Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775); 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /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 | @Test 8 | void test1() 9 | { 10 | Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4); 11 | } 12 | @Test 13 | void test2() 14 | { 15 | Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0); 16 | } 17 | @Test 18 | void test3() 19 | { 20 | Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0); 21 | } 22 | @Test 23 | void test4() 24 | { 25 | Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | 7 | /** 8 | * @author SirFixalot16 9 | * @since 01/06/22 10 | */ 11 | public class SumOfDigitsTest { 12 | @Test 13 | void isSumOf2Digits() { 14 | SumOfDigits sum = new SumOfDigits(); 15 | assertEquals(11, sum.sumOfDigits(56)); 16 | } 17 | void isSumOf3Digits() { 18 | SumOfDigits sum = new SumOfDigits(); 19 | assertEquals(12, sum.sumOfDigits(192)); 20 | } 21 | void isSumOf4Digits() { 22 | SumOfDigits sum = new SumOfDigits(); 23 | assertEquals(25, sum.sumOfDigits(8962)); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/maths/TestArmstrong.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.maths; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class TestArmstrong { 8 | 9 | @Test 10 | public void testArmstrong() { 11 | Armstrong armstrong = new Armstrong(); 12 | assertThat(armstrong.isArmstrong(371)).isTrue(); 13 | assertThat(armstrong.isArmstrong(200)).isFalse(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | class ArrayLeftRotationTest { 8 | 9 | @Test 10 | void testForOneElement() { 11 | int[] arr = {3}; 12 | int[] result = ArrayLeftRotation.rotateLeft(arr, 3); 13 | assertArrayEquals(arr, result); 14 | } 15 | 16 | @Test 17 | void testForZeroStep() { 18 | int[] arr = {3, 1, 5, 8, 6}; 19 | int[] result = ArrayLeftRotation.rotateLeft(arr, 0); 20 | assertArrayEquals(arr, result); 21 | } 22 | 23 | @Test 24 | void testForEqualSizeStep() { 25 | int[] arr = {3, 1, 5, 8, 6}; 26 | int[] result = ArrayLeftRotation.rotateLeft(arr, 5); 27 | assertArrayEquals(arr, result); 28 | } 29 | 30 | @Test 31 | void testForLowerSizeStep() { 32 | int[] arr = {3, 1, 5, 8, 6}; 33 | int n = 2; 34 | int[] expected = {5, 8, 6, 3, 1}; 35 | int[] result = ArrayLeftRotation.rotateLeft(arr, n); 36 | assertArrayEquals(expected, result); 37 | } 38 | 39 | @Test 40 | void testForHigherSizeStep() { 41 | int[] arr = {3, 1, 5, 8, 6}; 42 | int n = 7; 43 | int[] expected = {5, 8, 6, 3, 1}; 44 | int[] result = ArrayLeftRotation.rotateLeft(arr, n); 45 | assertArrayEquals(expected, result); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.*; 5 | import com.thealgorithms.datastructures.stacks.CalculateMaxOfMin; 6 | 7 | public class CalculateMaxOfMinTest { 8 | @Test 9 | void testForOneElement() { 10 | int a[] = { 10, 20, 30, 50, 10, 70, 30 }; 11 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 12 | assertTrue(k == 70); 13 | } 14 | 15 | @Test 16 | void testForTwoElements() { 17 | int a[] = { 5, 3, 2, 6, 3, 2, 6 }; 18 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 19 | assertTrue(k == 6); 20 | } 21 | 22 | @Test 23 | void testForThreeElements() { 24 | int a[] = { 10, 10, 10, 10, 10, 10, 10 }; 25 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 26 | assertTrue(k == 10); 27 | } 28 | 29 | @Test 30 | void testForFourElements() { 31 | int a[] = { 70, 60, 50, 40, 30, 20 }; 32 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 33 | assertTrue(k == 70); 34 | } 35 | 36 | @Test 37 | void testForFiveElements() { 38 | int a[] = { 50 }; 39 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 40 | assertTrue(k == 50); 41 | } 42 | 43 | @Test 44 | void testForSixElements() { 45 | int a[] = { 1, 4, 7, 9, 2, 4, 6 }; 46 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 47 | assertTrue(k == 9); 48 | } 49 | 50 | @Test 51 | void testForSevenElements() { 52 | int a[] = { -1, -5, -7, -9, -12, -14 }; 53 | int k = CalculateMaxOfMin.calculateMaxOfMin(a); 54 | assertTrue(k == -1); 55 | } 56 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import org.junit.jupiter.api.Test; 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import com.thealgorithms.dynamicprogramming.CountFriendsPairing; 6 | public class CountFriendsPairingTest { 7 | @Test 8 | void testForOneElement() 9 | { 10 | int a[] = {1,2,2}; 11 | assertTrue(CountFriendsPairing.countFriendsPairing(3,a)); 12 | } 13 | 14 | @Test 15 | void testForTwoElements() 16 | { 17 | int a[] = {1,2,2,3}; 18 | assertTrue(CountFriendsPairing.countFriendsPairing(4,a)); 19 | } 20 | 21 | @Test 22 | void testForThreeElements() 23 | { 24 | int a[] = {1,2,2,3,3}; 25 | assertTrue(CountFriendsPairing.countFriendsPairing(5,a)); 26 | } 27 | 28 | @Test 29 | void testForFourElements() 30 | { 31 | int a[] = {1,2,2,3,3,4}; 32 | assertTrue(CountFriendsPairing.countFriendsPairing(6,a)); 33 | } 34 | 35 | @Test 36 | void testForFiveElements() 37 | { 38 | int a[] = {1,2,2,3,3,4,4}; 39 | assertTrue(CountFriendsPairing.countFriendsPairing(7,a)); 40 | } 41 | 42 | @Test 43 | void testForSixElements() 44 | { 45 | int a[] = {1,2,2,3,3,4,4,4}; 46 | assertTrue(CountFriendsPairing.countFriendsPairing(8,a)); 47 | } 48 | 49 | @Test 50 | void testForSevenElements() 51 | { 52 | int a[] = {1,2,2,3,3,4,4,4,5}; 53 | assertTrue(CountFriendsPairing.countFriendsPairing(9,a)); 54 | } 55 | 56 | @Test 57 | void testForEightElements() 58 | { 59 | int a[] = {1,2,2,3,3,4,4,4,5,5}; 60 | assertTrue(CountFriendsPairing.countFriendsPairing(10,a)); 61 | } 62 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import org.junit.jupiter.api.Test; 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import com.thealgorithms.dynamicprogramming.KadaneAlgorithm; 6 | public class KadaneAlogrithmTest { 7 | @Test 8 | void testForOneElement() 9 | { 10 | int a[]={-1}; 11 | assertTrue(KadaneAlgorithm.max_Sum(a,-1)); 12 | } 13 | 14 | @Test 15 | void testForTwoElements() 16 | { 17 | int a[]={-2,1}; 18 | assertTrue(KadaneAlgorithm.max_Sum(a,1)); 19 | } 20 | 21 | @Test 22 | void testForThreeElements() 23 | { 24 | int a[]={5,3,12}; 25 | assertTrue(KadaneAlgorithm.max_Sum(a,20)); 26 | } 27 | 28 | @Test 29 | void testForFourElements() 30 | { 31 | int a[]={-1,-3,-7,-4}; 32 | assertTrue(KadaneAlgorithm.max_Sum(a,-1)); 33 | } 34 | 35 | @Test 36 | void testForFiveElements() 37 | { 38 | int a[]={4,5,3,0,2}; 39 | assertTrue(KadaneAlgorithm.max_Sum(a,14)); 40 | } 41 | 42 | 43 | @Test 44 | void testForSixElements() 45 | { 46 | int a[]={-43,-45,47,12,87,-13}; 47 | assertTrue(KadaneAlgorithm.max_Sum(a,146)); 48 | } 49 | 50 | @Test 51 | void testForSevenElements() 52 | { 53 | int a[]={9,8,2,23,13,6,7}; 54 | assertTrue(KadaneAlgorithm.max_Sum(a,68)); 55 | } 56 | 57 | @Test 58 | void testForEightElements() 59 | { 60 | int a[]={9,-5,-5,-2,4,5,0,1}; 61 | assertTrue(KadaneAlgorithm.max_Sum(a,10)); 62 | } 63 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/LinkList_Sort_test.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import org.junit.jupiter.api.Test; 3 | 4 | import com.thealgorithms.sorts.LinkList_Sort; 5 | 6 | import static org.junit.jupiter.api.Assertions.*; 7 | public class LinkList_Sort_test { 8 | @Test 9 | void testForOneElement() 10 | { 11 | int a[]={56}; 12 | assertTrue(LinkList_Sort.isSorted(a,2)); 13 | } 14 | 15 | @Test 16 | void testForTwoElements() 17 | { 18 | int a[]={6,4}; 19 | assertTrue(LinkList_Sort.isSorted(a,1)); 20 | } 21 | 22 | @Test 23 | void testForThreeElements() 24 | { 25 | int a[]={875,253,12}; 26 | assertTrue(LinkList_Sort.isSorted(a,3)); 27 | } 28 | 29 | @Test 30 | void testForFourElements() 31 | { 32 | int a[]={86,32,87,13}; 33 | assertFalse(LinkList_Sort.isSorted(a,2)); 34 | } 35 | 36 | @Test 37 | void testForFiveElements() 38 | { 39 | int a[]={6,5,3,0,9}; 40 | assertTrue(LinkList_Sort.isSorted(a,1)); 41 | } 42 | 43 | 44 | @Test 45 | void testForSixElements() 46 | { 47 | int a[]={9,65,432,32,47,327}; 48 | assertTrue(LinkList_Sort.isSorted(a,3)); 49 | } 50 | 51 | @Test 52 | void testForSevenElements() 53 | { 54 | int a[]={6,4,2,1,3,6,7}; 55 | assertTrue(LinkList_Sort.isSorted(a,1)); 56 | } 57 | 58 | @Test 59 | void testForEightElements() 60 | { 61 | int a[]={123,234,145,764,322,367,768,34}; 62 | assertFalse(LinkList_Sort.isSorted(a,2)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import org.junit.jupiter.api.Test; 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import com.thealgorithms.dynamicprogramming.NewManShanksPrime; 6 | public class NewManShanksPrimeTest { 7 | @Test 8 | void testOne() 9 | { 10 | assertTrue(NewManShanksPrime.nthManShanksPrime(1,1)); 11 | } 12 | 13 | @Test 14 | void testTwo() 15 | { 16 | assertTrue(NewManShanksPrime.nthManShanksPrime(2,3)); 17 | } 18 | 19 | @Test 20 | void testThree() 21 | { 22 | assertTrue(NewManShanksPrime.nthManShanksPrime(3,7)); 23 | } 24 | 25 | @Test 26 | void testFour() 27 | { 28 | assertTrue(NewManShanksPrime.nthManShanksPrime(4,17)); 29 | } 30 | 31 | @Test 32 | void testFive() 33 | { 34 | assertTrue(NewManShanksPrime.nthManShanksPrime(5,41)); 35 | } 36 | 37 | @Test 38 | void testSix() 39 | { 40 | assertTrue(NewManShanksPrime.nthManShanksPrime(6,99)); 41 | } 42 | 43 | @Test 44 | void testSeven() 45 | { 46 | assertTrue(NewManShanksPrime.nthManShanksPrime(7,239)); 47 | } 48 | 49 | @Test 50 | void testEight() 51 | { 52 | assertTrue(NewManShanksPrime.nthManShanksPrime(8,577)); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/others/UniquePathsTests.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.others; 2 | import org.junit.jupiter.api.Test; 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | import com.thealgorithms.dynamicprogramming.UniquePaths; 6 | 7 | 8 | public class UniquePathsTests { 9 | @Test 10 | void testForOneElement() 11 | { 12 | assertTrue(UniquePaths.uniquePaths(3,7,28)); 13 | } 14 | 15 | @Test 16 | void testForTwoElements() 17 | { 18 | assertTrue(UniquePaths.uniquePaths(3,2,3)); 19 | } 20 | 21 | @Test 22 | void testForThreeElements() 23 | { 24 | assertTrue(UniquePaths.uniquePaths(3,3,6)); 25 | } 26 | 27 | @Test 28 | void testForFourElements() 29 | { 30 | assertTrue(UniquePaths.uniquePaths(4,6,56)); 31 | } 32 | 33 | @Test 34 | void testForFiveElements() 35 | { 36 | assertTrue(UniquePaths.uniquePaths2(3,5,15)); 37 | } 38 | 39 | @Test 40 | void testForSixElements() 41 | { 42 | assertTrue(UniquePaths.uniquePaths2(6,2,6)); 43 | } 44 | 45 | @Test 46 | void testForSevenElements() 47 | { 48 | assertTrue(UniquePaths.uniquePaths2(5,9,495)); 49 | } 50 | 51 | @Test 52 | void testForEightElements() 53 | { 54 | assertTrue(UniquePaths.uniquePaths2(4,8,120)); 55 | } 56 | } -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/AlphabeticalTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | 8 | public class AlphabeticalTest { 9 | @Test 10 | public void isAlphabetical() { 11 | // expected to be true 12 | String input1 = "abcdefghijklmno"; 13 | String input2 = "abcdxxxyzzzz"; 14 | String input3 = "fpw"; 15 | 16 | // expected to be false 17 | String input4 = "123a"; 18 | String input5 = "abcABC"; 19 | String input6 = "abcdefghikjlmno"; 20 | 21 | assertTrue(Alphabetical.isAlphabetical(input1)); 22 | assertTrue(Alphabetical.isAlphabetical(input2)); 23 | assertTrue(Alphabetical.isAlphabetical(input3)); 24 | 25 | assertFalse(Alphabetical.isAlphabetical(input4)); 26 | assertFalse(Alphabetical.isAlphabetical(input5)); 27 | assertFalse(Alphabetical.isAlphabetical(input6)); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/AnagramsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class AnagramsTest { 8 | @Test 9 | public void isAlphabetical() { 10 | String input1 = "late"; 11 | Anagrams anagrams = new Anagrams(); 12 | assertTrue(anagrams.approach1(input1, "tale")); 13 | assertTrue(anagrams.approach1(input1, "teal")); 14 | assertTrue(anagrams.approach2(input1, "tale")); 15 | assertTrue(anagrams.approach2(input1, "teal")); 16 | assertTrue(anagrams.approach3(input1, "tale")); 17 | assertTrue(anagrams.approach3(input1, "teal")); 18 | assertTrue(anagrams.approach4(input1, "tale")); 19 | assertTrue(anagrams.approach4(input1, "teal")); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/CharacterSameTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import static org.junit.jupiter.api.Assertions.*; 5 | 6 | 7 | public class CharacterSameTest { 8 | @Test 9 | public void isAllCharactersSame() { 10 | String input1 = "aaa"; 11 | String input2 = "abc"; 12 | String input3 = "1 1 1 1"; 13 | String input4 = "111"; 14 | String input5 = ""; 15 | String input6 = " "; 16 | String input7 = ". "; 17 | 18 | assertTrue(CharactersSame.isAllCharactersSame(input1)); 19 | assertFalse(CharactersSame.isAllCharactersSame(input2)); 20 | assertFalse(CharactersSame.isAllCharactersSame(input3)); 21 | assertTrue(CharactersSame.isAllCharactersSame(input4)); 22 | assertTrue(CharactersSame.isAllCharactersSame(input5)); 23 | assertTrue(CharactersSame.isAllCharactersSame(input6)); 24 | assertFalse(CharactersSame.isAllCharactersSame(input7)); 25 | 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | 8 | public class CheckAnagramsTest { 9 | @Test 10 | public void CheckAnagrams() { 11 | String testString1 = "STUDY"; 12 | String testString2 = "DUSTY"; 13 | assertTrue(CheckAnagrams.isAnagrams(testString1,testString2)); 14 | } 15 | 16 | @Test 17 | public void CheckFalseAnagrams() { 18 | String testString1 = "STUDY"; 19 | String testString2 = "random"; 20 | assertFalse(CheckAnagrams.isAnagrams(testString1,testString2)); 21 | } 22 | 23 | @Test 24 | public void CheckSameWordAnagrams() { 25 | String testString1 = "STUDY"; 26 | assertTrue(CheckAnagrams.isAnagrams(testString1,testString1)); 27 | } 28 | 29 | @Test 30 | public void CheckDifferentCasesAnagram() { 31 | String testString1 = "STUDY"; 32 | String testString2 = "dusty"; 33 | assertTrue(CheckAnagrams.isAnagrams(testString1,testString2)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/PalindromeTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class PalindromeTest { 7 | @Test 8 | public void palindrome() { 9 | String input1 = "kayak"; 10 | String input2 = "kayaks"; 11 | Assertions.assertTrue(Palindrome.isPalindrome(input1)); 12 | Assertions.assertFalse(Palindrome.isPalindrome(input2)); 13 | Assertions.assertTrue(Palindrome.isPalindromeRecursion(input1)); 14 | Assertions.assertFalse(Palindrome.isPalindromeRecursion(input2)); 15 | Assertions.assertTrue(Palindrome.isPalindrome1(input1)); 16 | Assertions.assertFalse(Palindrome.isPalindrome1(input2)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/PangramTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | 8 | public class PangramTest { 9 | @Test 10 | public void isPangram() { 11 | String fullAlphabet = "abcdefghijklmnopqrstuvwxyz"; 12 | String notFullAlphabet = "abcdefghiklmnopqrstuvwxyz"; 13 | String fullMixedCaseAlphabet = "a BCDE fghIjkLMnop qrSTuv WXYz"; 14 | String sentence1 = "The quick brown fox jumps over the lazy dog"; 15 | String sentence2 = "The quick brown fox jumps over the lazy gentleman"; // missing letter d 16 | 17 | assertTrue(Pangram.isPangram(fullAlphabet)); 18 | assertFalse(Pangram.isPangram(notFullAlphabet)); 19 | assertTrue(Pangram.isPangram(fullMixedCaseAlphabet)); 20 | assertTrue(Pangram.isPangram(sentence1)); 21 | assertFalse(Pangram.isPangram(sentence2)); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/UpperTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.*; 6 | 7 | public class UpperTest { 8 | @Test 9 | public void toUpperCase() { 10 | String input1 = "hello world"; 11 | String input2 = "hElLo WoRlD"; 12 | String input3 = "HELLO WORLD"; 13 | assertEquals("HELLO WORLD", Upper.toUpperCase(input1)); 14 | assertEquals("HELLO WORLD", Upper.toUpperCase(input2)); 15 | assertEquals("HELLO WORLD", Upper.toUpperCase(input3)); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java: -------------------------------------------------------------------------------- 1 | package com.thealgorithms.strings; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | public class longestNonRepeativeSubstringTest { 7 | @Test 8 | public void palindrome() { 9 | String input1 = "HelloWorld"; 10 | String input2 = "javaIsAProgrammingLanguage"; 11 | Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input1 ) , 5 ) ; 12 | Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input2 ) , 9 ) ; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /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 | @Test 8 | public void palindrome() { 9 | String input1 = "HelloWorldFromJava"; 10 | String input2 = "javaIsAProgrammingLanguage"; 11 | Assertions.assertEquals( zigZagPattern.encode( input1 , 4 ) , "HooeWrrmalolFJvlda" ) ; 12 | Assertions.assertEquals( zigZagPattern.encode( input2 , 4 ) , "jAaLgasPrmgaaevIrgmnnuaoig" ) ; 13 | } 14 | } 15 | --------------------------------------------------------------------------------