├── .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
│ ├── KnightsTour.java
│ ├── NQueens.java
│ └── PowerSum.java
│ ├── ciphers
│ ├── AES.java
│ ├── AESEncryption.java
│ ├── AffineCipher.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
│ ├── 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
│ │ ├── 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
│ │ ├── RemoveDuplicateNodes.java
│ │ ├── SearchSinglyLinkedListRecursion.java
│ │ └── SinglyLinkedList.java
│ ├── queues
│ │ ├── CircularQueue.java
│ │ ├── Deques.java
│ │ ├── GenericArrayListQueue.java
│ │ ├── LinkedQueue.java
│ │ ├── PriorityQueues.java
│ │ ├── Queues.java
│ │ └── README.md
│ ├── stacks
│ │ ├── BalancedBrackets.java
│ │ ├── DecimalToAnyUsingStack.java
│ │ ├── DuplicateBrackets.java
│ │ ├── InfixToPostfix.java
│ │ ├── MaximumMinimumWindow.java
│ │ ├── NextGraterElement.java
│ │ ├── NextSmallerElement.java
│ │ ├── NodeStack.java
│ │ ├── README.md
│ │ ├── ReverseStack.java
│ │ ├── StackArray.java
│ │ ├── StackArrayList.java
│ │ └── StackOfLinkedList.java
│ └── trees
│ │ ├── AVLSimple
│ │ ├── 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
│ │ ├── 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
│ ├── DiceThrow.java
│ ├── DyanamicProgrammingKnapsack.java
│ ├── EditDistance.java
│ ├── EggDropping.java
│ ├── Fibonacci.java
│ ├── FloodFill.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
│ ├── PalindromicPartitioning.java
│ ├── RegexMatching.java
│ ├── RodCutting.java
│ ├── ShortestCommonSupersequenceLength.java
│ ├── SubsetSum.java
│ ├── Sum_Of_Subset.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
│ ├── DudeneyNumber.java
│ ├── EulerMethod.java
│ ├── FFT.java
│ ├── FFTBluestein.java
│ ├── Factorial.java
│ ├── FactorialRecursion.java
│ ├── FibonacciJavaStreams.java
│ ├── FibonacciNumber.java
│ ├── FindMax.java
│ ├── FindMaxRecursion.java
│ ├── FindMin.java
│ ├── FindMinRecursion.java
│ ├── Floor.java
│ ├── GCD.java
│ ├── GCDRecursion.java
│ ├── Gaussian.java
│ ├── GenericRoot.java
│ ├── HarshadNumber.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
│ ├── 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
│ ├── BestFit.java
│ ├── BoyerMoore.java
│ ├── BrianKernighanAlgorithm.java
│ ├── CRC32.java
│ ├── CRCAlgorithm.java
│ ├── CountChar.java
│ ├── CountWords.java
│ ├── Damm.java
│ ├── Dijkstra.java
│ ├── EulersFunction.java
│ ├── FibbonaciSeries.java
│ ├── FirstFit.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
│ ├── 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
│ └── WorstFit.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
│ ├── GnomeSort.java
│ ├── HeapSort.java
│ ├── InsertionSort.java
│ ├── MergeSort.java
│ ├── MergeSortNoExtraSpace.java
│ ├── MergeSortRecursive.java
│ ├── OddEvenSort.java
│ ├── PancakeSort.java
│ ├── QuickSort.java
│ ├── RadixSort.java
│ ├── SelectionSort.java
│ ├── ShellSort.java
│ ├── SimpleSort.java
│ ├── SlowSort.java
│ ├── SortAlgorithm.java
│ ├── SortUtils.java
│ ├── StoogeSort.java
│ ├── SwapSort.java
│ ├── TimSort.java
│ └── TreeSort.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
└── test
└── java
└── com
└── thealgorithms
├── maths
├── KaprekarNumbersTest.java
├── PascalTriangleTest.java
└── PronicNumberTest.java
├── others
└── ArrayLeftRotationTest.java
└── searches
└── QuickSelectTest.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: [push, pull_request]
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - uses: actions/checkout@v2
8 | - name: Set up JDK 17
9 | uses: actions/setup-java@v2
10 | with:
11 | java-version: 17
12 | distribution: 'adopt'
13 | - name: Build with Maven
14 | run: mvn --batch-mode --update-snapshots verify
15 |
--------------------------------------------------------------------------------
/.github/workflows/prettify.yml:
--------------------------------------------------------------------------------
1 | name: Prettify
2 | on: [push, pull_request]
3 | jobs:
4 | prettier:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - name: Checkout
8 | uses: actions/checkout@v2
9 | with:
10 | ref: ${{ github.head_ref }}
11 |
12 | - name: Prettify code
13 | uses: creyD/prettier_action@v3.3
14 | with:
15 | prettier_options: --write **/*.java
16 | commit_message: 'Prettify code'
17 | env:
18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
19 |
--------------------------------------------------------------------------------
/.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 |
13 | # gradle
14 | .gradle/
15 | gradle-app.setting
16 | !gradle-wrapper.jar
17 | build/
18 |
19 | # maven
20 | *.classpath
21 | *.project
22 | *.settings
23 | /target/
24 |
25 | local.properties
26 |
27 | ##----------idea----------
28 | *.iml
29 | .idea/
30 | *.ipr
31 | *.iws
32 |
33 | # Android Studio Navigation editor temp files
34 | .navigation/
35 |
36 | ##----------Other----------
37 | # osx
38 | *~
39 | .DS_Store
40 | gradle.properties
41 |
42 | .vscode
43 |
44 | *.log
45 |
--------------------------------------------------------------------------------
/.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 | [](https://github.com/TheAlgorithms/Java/actions/workflows/build.yml)
4 | [](https://discord.gg/c7MnfGFGa6)
5 | [](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 | [](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 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
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
7 | * Heaps are tree-like data structures that allow storing elements in a specific
8 | * way. Each node corresponds to an element and has one parent node (except for
9 | * the root) and at most two children nodes. Every element contains a key, and
10 | * those keys indicate how the tree shall be built. For instance, for a
11 | * min-heap, the key of a node shall be greater than or equal to its parent's
12 | * and lower than or equal to its children's (the opposite rule applies to a
13 | * max-heap).
14 | *
15 | *
16 | * All heap-related operations (inserting or deleting an element, extracting the
17 | * min or max) are performed in O(log n) time.
18 | *
19 | * @author Nicolas Renard
20 | */
21 | public interface Heap {
22 |
23 | /**
24 | * @return the top element in the heap, the one with lowest key for min-heap
25 | * or with the highest key for max-heap
26 | * @throws EmptyHeapException if heap is empty
27 | */
28 | HeapElement getElement() throws EmptyHeapException;
29 |
30 | /**
31 | * Inserts an element in the heap. Adds it to then end and toggle it until
32 | * it finds its right position.
33 | *
34 | * @param element an instance of the HeapElement class.
35 | */
36 | void insertElement(HeapElement element);
37 |
38 | /**
39 | * Delete an element in the heap.
40 | *
41 | * @param elementIndex int containing the position in the heap of the
42 | * element to be deleted.
43 | */
44 | void deleteElement(int elementIndex);
45 | }
46 |
--------------------------------------------------------------------------------
/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/MergeSortedSinglyLinkedList.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.datastructures.lists;
2 |
3 | public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
4 |
5 | public static void main(String[] args) {
6 | SinglyLinkedList listA = new SinglyLinkedList();
7 | SinglyLinkedList listB = new SinglyLinkedList();
8 |
9 | for (int i = 2; i <= 10; i += 2) {
10 | listA.insert(i);
11 | listB.insert(i - 1);
12 | }
13 | assert listA.toString().equals("2->4->6->8->10");
14 | assert listB.toString().equals("1->3->5->7->9");
15 | assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10");
16 | }
17 |
18 | /**
19 | * Merge two sorted SingleLinkedList
20 | *
21 | * @param listA the first sorted list
22 | * @param listB the second sored list
23 | * @return merged sorted list
24 | */
25 | public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) {
26 | Node headA = listA.getHead();
27 | Node headB = listB.getHead();
28 |
29 | int size = listA.size() + listB.size();
30 |
31 | Node head = new Node();
32 | Node tail = head;
33 | while (headA != null && headB != null) {
34 | if (headA.value <= headB.value) {
35 | tail.next = headA;
36 | headA = headA.next;
37 | } else {
38 | tail.next = headB;
39 | headB = headB.next;
40 | }
41 | tail = tail.next;
42 | }
43 | if (headA == null) {
44 | tail.next = headB;
45 | }
46 | if (headB == null) {
47 | tail.next = headA;
48 | }
49 | return new SinglyLinkedList(head.next, size);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/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
9 | * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
10 | */
11 | public class AbsoluteMax {
12 |
13 | public static void main(String[] args) {
14 | int[] testnums = {-2, 0, 16};
15 | assert absMax(testnums) == 16;
16 |
17 | int[] numbers = {3, -10, -2};
18 | System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
19 | }
20 |
21 | /**
22 | * get the value, return the absolute max value
23 | *
24 | * @param numbers contains elements
25 | * @return the absolute max value
26 | */
27 | public static int absMax(int[] numbers) {
28 | int absMaxValue = numbers[0];
29 | for (int i = 1, length = numbers.length; i < length; ++i) {
30 | if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
31 | absMaxValue = numbers[i];
32 | }
33 | }
34 | return absMaxValue;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/maths/AbsoluteMin.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * description:
7 | *
8 | *
9 | * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
10 | */
11 | public class AbsoluteMin {
12 |
13 | public static void main(String[] args) {
14 | int[] testnums = {4, 0, 16};
15 | assert absMin(testnums) == 0;
16 |
17 | int[] numbers = {3, -10, -2};
18 | System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
19 | }
20 |
21 | /**
22 | * get the value, returns the absolute min value min
23 | *
24 | * @param numbers contains elements
25 | * @return the absolute min value
26 | */
27 | public static int absMin(int[] numbers) {
28 | int absMinValue = numbers[0];
29 | for (int i = 1, length = numbers.length; i < length; ++i) {
30 | if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
31 | absMinValue = numbers[i];
32 | }
33 | }
34 | return absMinValue;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/maths/AbsoluteValue.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.Random;
4 |
5 | public class AbsoluteValue {
6 |
7 | public static void main(String[] args) {
8 | Random random = new Random();
9 |
10 | /* test 1000 random numbers */
11 | for (int i = 1; i <= 1000; ++i) {
12 | int randomNumber = random.nextInt();
13 | assert absVal(randomNumber) == Math.abs(randomNumber);
14 | }
15 | }
16 |
17 | /**
18 | * If value is less than zero, make value positive.
19 | *
20 | * @param value a number
21 | * @return the absolute value of a number
22 | */
23 | public static int absVal(int value) {
24 | return value < 0 ? -value : value;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/maths/AliquotSum.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | /**
4 | * In number theory, the aliquot sum s(n) of a positive integer n is the sum of
5 | * all proper divisors of n, that is, all divisors of n other than n itself. For
6 | * example, the proper divisors of 15 (that is, the positive divisors of 15 that
7 | * are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 +
8 | * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
9 | */
10 | public class AliquotSum {
11 |
12 | public static void main(String[] args) {
13 | assert aliquotSum(1) == 0;
14 | assert aliquotSum(6) == 6;
15 | assert aliquotSum(15) == 9;
16 | assert aliquotSum(19) == 1;
17 | }
18 |
19 | /**
20 | * Finds the aliquot sum of an integer number
21 | *
22 | * @param number a positive integer
23 | * @return aliquot sum of given {@code number}
24 | */
25 | public static int aliquotSum(int number) {
26 | int sum = 0;
27 | for (int i = 1, limit = number / 2; i <= limit; ++i) {
28 | if (number % i == 0) {
29 | sum += i;
30 | }
31 | }
32 | return sum;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/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 | public class Armstrong {
9 |
10 | public static void main(String[] args) {
11 | assert (isArmStrong(0));
12 | assert (isArmStrong(1));
13 | assert (isArmStrong(153));
14 | assert (isArmStrong(1634));
15 | assert (isArmStrong(371));
16 | assert (!isArmStrong(200));
17 | }
18 |
19 | /**
20 | * Checks whether a given number is an armstrong number or not.
21 | *
22 | * @param number number to check
23 | * @return {@code true} if given number is armstrong number, {@code false}
24 | * otherwise
25 | */
26 | private static boolean isArmStrong(int number) {
27 | int sum = 0;
28 | int temp = number;
29 | int numberOfDigits = 0;
30 | while (temp != 0) {
31 | numberOfDigits++;
32 | temp /= 10;
33 | }
34 | temp = number;
35 | /* copy number again */
36 | while (number > 0) {
37 | int remainder = number % 10;
38 | int power = 1;
39 | for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
40 | ;
41 | sum = sum + power;
42 | number /= 10;
43 | }
44 | return sum == temp;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/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/DeterminantOfMatrix.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.*;
4 |
5 | /*
6 | * @author Ojasva Jain
7 | * Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant
8 | */
9 | public class DeterminantOfMatrix {
10 |
11 | // Determinant calculator
12 | //@return determinant of the input matrix
13 | static int determinant(int a[][], int n) {
14 | int det = 0, sign = 1, p = 0, q = 0;
15 | if (n == 1) {
16 | det = a[0][0];
17 | } else {
18 | int b[][] = new int[n - 1][n - 1];
19 | for (int x = 0; x < n; x++) {
20 | p = 0;
21 | q = 0;
22 | for (int i = 1; i < n; i++) {
23 | for (int j = 0; j < n; j++) {
24 | if (j != x) {
25 | b[p][q++] = a[i][j];
26 | if (q % (n - 1) == 0) {
27 | p++;
28 | q = 0;
29 | }
30 | }
31 | }
32 | }
33 | det = det + a[0][x] * determinant(b, n - 1) * sign;
34 | sign = -sign;
35 | }
36 | }
37 | return det;
38 | }
39 |
40 | //Driver Method
41 | public static void main(String[] args) {
42 | Scanner in = new Scanner(System.in);
43 | //Input Matrix
44 | System.out.println("Enter matrix size (Square matrix only)");
45 | int n = in.nextInt();
46 | System.out.println("Enter matrix");
47 | int a[][] = new int[n][n];
48 | for (int i = 0; i < n; i++) {
49 | for (int j = 0; j < n; j++) {
50 | a[i][j] = in.nextInt();
51 | }
52 | }
53 | System.out.println(determinant(a, n));
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/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/FindMaxRecursion.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.Arrays;
4 | import java.util.Random;
5 |
6 | public class FindMaxRecursion {
7 |
8 | public static void main(String[] args) {
9 | Random rand = new Random();
10 |
11 | /* rand size */
12 | int size = rand.nextInt(100) + 1;
13 | int[] array = new int[size];
14 |
15 | /* init array with rand numbers */
16 | for (int i = 0; i < size; i++) {
17 | array[i] = rand.nextInt() % 100;
18 | }
19 |
20 | assert max(array, array.length) == Arrays.stream(array).max().getAsInt();
21 | assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt();
22 | }
23 |
24 | /**
25 | * Get max of array using divide and conquer algorithm
26 | *
27 | * @param array contains elements
28 | * @param low the index of the first element
29 | * @param high the index of the last element
30 | * @return max of {@code array}
31 | */
32 | public static int max(int[] array, int low, int high) {
33 | if (low == high) {
34 | return array[low]; // or array[high]
35 | }
36 |
37 | int mid = (low + high) >>> 1;
38 |
39 | int leftMax = max(array, low, mid); // get max in [low, mid]
40 | int rightMax = max(array, mid + 1, high); // get max in [mid+1, high]
41 |
42 | return Math.max(leftMax, rightMax);
43 | }
44 |
45 | /**
46 | * Get max of array using recursion algorithm
47 | *
48 | * @param array contains elements
49 | * @param len length of given array
50 | * @return max value of {@code array}
51 | */
52 | public static int max(int[] array, int len) {
53 | return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/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/FindMinRecursion.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.Arrays;
4 | import java.util.Random;
5 |
6 | public class FindMinRecursion {
7 |
8 | /**
9 | * Driver Code
10 | */
11 | public static void main(String[] args) {
12 | Random rand = new Random();
13 |
14 | /* rand size */
15 | int size = rand.nextInt(100) + 1;
16 | int[] array = new int[size];
17 |
18 | /* init array with rand numbers */
19 | for (int i = 0; i < size; i++) {
20 | array[i] = rand.nextInt() % 100;
21 | }
22 |
23 | assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt();
24 | assert min(array, array.length) == Arrays.stream(array).min().getAsInt();
25 | }
26 |
27 | /**
28 | * Get min of array using divide and conquer algorithm
29 | *
30 | * @param array contains elements
31 | * @param low the index of the first element
32 | * @param high the index of the last element
33 | * @return min of {@code array}
34 | */
35 | public static int min(int[] array, int low, int high) {
36 | if (low == high) {
37 | return array[low]; // or array[high]
38 | }
39 |
40 | int mid = (low + high) >>> 1;
41 |
42 | int leftMin = min(array, low, mid); // get min in [low, mid]
43 | int rightMin = min(array, mid + 1, high); // get min in [mid+1, high]
44 |
45 | return Math.min(leftMin, rightMin);
46 | }
47 |
48 | /**
49 | * Get min of array using recursion algorithm
50 | *
51 | * @param array contains elements
52 | * @param len length of given array
53 | * @return min value of {@code array}
54 | */
55 | public static int min(int[] array, int len) {
56 | return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]);
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/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/HarshadNumber.java:
--------------------------------------------------------------------------------
1 | // Wikipedia for Harshad Number : https://en.wikipedia.org/wiki/Harshad_number
2 | package com.thealgorithms.maths;
3 |
4 | import java.util.Scanner;
5 |
6 | public class HarshadNumber {
7 |
8 | public static void main(String[] args) {
9 | Scanner sc = new Scanner(System.in);
10 | System.out.print("Enter a number : ");
11 | long a = sc.nextLong();
12 |
13 | checkHarshadNumber(a);
14 | }
15 |
16 | /**
17 | * A function to check if a number is Harshad number or not
18 | *
19 | * @param a The number which should be checked
20 | */
21 | public static void checkHarshadNumber(long a) {
22 |
23 | long b = a;
24 | int sum = 0;
25 |
26 | // this is just for showing the explanation else it's of no use you can ommit it
27 | int[] each = new int[Long.toString(a).length()];
28 |
29 | int c = 0;
30 |
31 | while (b > 0) {
32 | sum += b % 10;
33 | each[c] = (int) (b % 10);
34 | b /= 10;
35 | c++;
36 | }
37 |
38 | if (a % sum == 0) {
39 | System.out.println(a + " is a Harshad Number");
40 |
41 | // For you better explanation how is that a Harshad Number
42 | System.out.println("\nExplaination :");
43 |
44 | for (int i = each.length - 1; i >= 0; i--) {
45 | System.out.print(each[i] + " ");
46 | if (i != 0) {
47 | System.out.print("+ ");
48 | }
49 | }
50 |
51 | System.out.println("= " + sum);
52 | System.out.println(sum + " × " + (a / sum) + " = " + a);
53 | } else {
54 | System.out.println(a + " is not a Harshad Number");
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/com/thealgorithms/maths/JugglerSequence.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /*
7 | * Java program for printing juggler sequence
8 | * Wikipedia: https://en.wikipedia.org/wiki/Juggler_sequence
9 | *
10 | * Author: Akshay Dubey (https://github.com/itsAkshayDubey)
11 | *
12 | * */
13 |
14 | public class JugglerSequence {
15 | /**
16 | * This method prints juggler sequence starting with the number in the parameter
17 | *
18 | * @param inputNumber Number from which juggler sequence is to be started
19 | */
20 | public static void jugglerSequence(int inputNumber) {
21 | // Copy method argument to a local variable
22 | int n = inputNumber;
23 | List
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/PrimeCheck.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | import java.util.Scanner;
4 |
5 | public class PrimeCheck {
6 |
7 | public static void main(String[] args) {
8 | Scanner scanner = new Scanner(System.in);
9 |
10 | System.out.print("Enter a number: ");
11 | int n = scanner.nextInt();
12 | if (isPrime(n)) {
13 | System.out.println(n + " is a prime number");
14 | } else {
15 | System.out.println(n + " is not a prime number");
16 | }
17 | scanner.close();
18 | }
19 |
20 | /**
21 | * *
22 | * Checks if a number is prime or not
23 | *
24 | * @param n the number
25 | * @return {@code true} if {@code n} is prime
26 | */
27 | public static boolean isPrime(int n) {
28 | if (n == 2) {
29 | return true;
30 | }
31 | if (n < 2 || n % 2 == 0) {
32 | return false;
33 | }
34 | for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
35 | if (n % i == 0) {
36 | return false;
37 | }
38 | }
39 | return true;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/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/SumOfArithmeticSeries.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.maths;
2 |
3 | /**
4 | * In mathematics, an arithmetic progression (AP) or arithmetic sequence is a
5 | * sequence of numbers such that the difference between the consecutive terms is
6 | * constant. Difference here means the second minus the first. For instance, the
7 | * sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common
8 | * difference of 2.
9 | *
10 | *
11 | * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression
12 | */
13 | public class SumOfArithmeticSeries {
14 |
15 | public static void main(String[] args) {
16 |
17 | /* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */
18 | assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0;
19 |
20 | /* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */
21 | assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0;
22 |
23 | /* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */
24 | assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0;
25 |
26 | /* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */
27 | assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0;
28 |
29 | assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0;
30 | }
31 |
32 | /**
33 | * Calculate sum of arithmetic series
34 | *
35 | * @param firstTerm the initial term of an arithmetic series
36 | * @param commonDiff the common difference of an arithmetic series
37 | * @param numOfTerms the total terms of an arithmetic series
38 | * @return sum of given arithmetic series
39 | */
40 | private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) {
41 | return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff);
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/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
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/CountWords.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * You enter a string into this program, and it will return how many words were
7 | * in that particular string
8 | *
9 | * @author Marcus
10 | */
11 | public class CountWords {
12 |
13 | public static void main(String[] args) {
14 | Scanner input = new Scanner(System.in);
15 | System.out.println("Enter your text: ");
16 | String str = input.nextLine();
17 |
18 | System.out.println("Your text has " + wordCount(str) + " word(s)");
19 | System.out.println("Your text has " + secondaryWordCount(str) + " word(s)");
20 | input.close();
21 | }
22 |
23 | private static int wordCount(String s) {
24 | if (s == null || s.isEmpty()) {
25 | return 0;
26 | }
27 | return s.trim().split("[\\s]+").length;
28 | }
29 |
30 | /**
31 | * counts the number of words in a sentence but ignores all potential
32 | * non-alphanumeric characters that do not represent a word. runs in O(n)
33 | * where n is the length of s
34 | *
35 | * @param s String: sentence with word(s)
36 | * @return int: number of words
37 | */
38 | private static int secondaryWordCount(String s) {
39 | if (s == null || s.isEmpty()) {
40 | return 0;
41 | }
42 | StringBuilder sb = new StringBuilder();
43 | for (char c : s.toCharArray()) {
44 | if (Character.isLetter(c) || Character.isDigit(c)) {
45 | sb.append(c);
46 | }
47 | }
48 | s = sb.toString();
49 | return s.trim().split("[\\s]+").length;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/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
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/others/TwoPointers.java:
--------------------------------------------------------------------------------
1 | package com.thealgorithms.others;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * The two pointer technique is a useful tool to utilize when searching for
7 | * pairs in a sorted array.
8 | *
9 | *
10 | * link: https://www.geeksforgeeks.org/two-pointers-technique/
11 | */
12 | class TwoPointers {
13 |
14 | public static void main(String[] args) {
15 | int[] arr = {10, 20, 35, 50, 75, 80};
16 | int key = 70;
17 | assert isPairedSum(arr, key);
18 | /* 20 + 60 == 70 */
19 |
20 | arr = new int[]{1, 2, 3, 4, 5, 6, 7};
21 | key = 13;
22 | assert isPairedSum(arr, key);
23 | /* 6 + 7 == 13 */
24 |
25 | key = 14;
26 | assert !isPairedSum(arr, key);
27 | }
28 |
29 | /**
30 | * Given a sorted array arr (sorted in ascending order). Find if there
31 | * exists any pair of elements such that their sum is equal to key.
32 | *
33 | * @param arr the array contains elements
34 | * @param key the number to search
35 | * @return {@code true} if there exists a pair of elements, {@code false}
36 | * otherwise.
37 | */
38 | private static boolean isPairedSum(int[] arr, int key) {
39 | /* array sorting is necessary for this algorithm to function correctly */
40 | Arrays.sort(arr);
41 | int i = 0;
42 | /* index of first element */
43 | int j = arr.length - 1;
44 | /* index of last element */
45 |
46 | while (i < j) {
47 | if (arr[i] + arr[j] == key) {
48 | return true;
49 | } else if (arr[i] + arr[j] < key) {
50 | i++;
51 | } else {
52 | j--;
53 | }
54 | }
55 | return false;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/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
5 | *
6 | *
27 | a. **BFS:** Breadth-first-search where all the children at each level are traversed at once.
28 | b. **DFS:** Depth-first-search where the first discovered child is traversed first.
29 | 4. **MultiWay Search Tree:** Tree in sorted order, but more than two children in each internal node.
30 | 5. **Trie:** A character based multiway search tree where words can be retrieved based on their prefix. Useful for implementing prefix based search algorithm.
--------------------------------------------------------------------------------
/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