Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot]
2e1cc59658
Chore(deps): bump gitpod/workspace-java-17
Bumps gitpod/workspace-java-17 from 2024-04-29-07-29-58 to 2024-04-29-23-03-42.

---
updated-dependencies:
- dependency-name: gitpod/workspace-java-17
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-01 10:57:07 +00:00
715 changed files with 8596 additions and 14027 deletions

View File

@ -1,8 +1,8 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/java/.devcontainer/base.Dockerfile
# [Choice] Java version (use -bullseye variants on local arm64/Apple Silicon): 11, 17, 11-bullseye, 17-bullseye, 11-buster, 17-buster
ARG VARIANT="21-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/java:1.1.0-${VARIANT}
ARG VARIANT="17-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT}
# [Option] Install Maven
ARG INSTALL_MAVEN="false"

View File

@ -8,7 +8,7 @@
// Update the VARIANT arg to pick a Java version: 11, 17
// Append -bullseye or -buster to pin to an OS version.
// Use the -bullseye variants on local arm64/Apple Silicon.
"VARIANT": "21-bullseye",
"VARIANT": "17-bullseye",
// Options
"INSTALL_MAVEN": "true",
"INSTALL_GRADLE": "true",

2
.github/CODEOWNERS vendored
View File

@ -1 +1 @@
* @yanglbme @vil02 @BamaCharanChhandogi @alxkm @siriak
* @yanglbme @vil02 @BamaCharanChhandogi

View File

@ -6,10 +6,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: 21
java-version: 17
distribution: 'adopt'
- name: Build with Maven
run: mvn --batch-mode --update-snapshots verify
@ -33,5 +33,3 @@ jobs:
run: mvn checkstyle:check
- name: SpotBugs
run: mvn spotbugs:check
- name: PMD
run: mvn pmd:check

View File

@ -9,7 +9,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: DoozyX/clang-format-lint-action@v0.18
- uses: DoozyX/clang-format-lint-action@v0.17
with:
source: './src'
extensions: 'java'

View File

@ -26,10 +26,10 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up JDK
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: 21
java-version: 17
distribution: 'adopt'
- name: Initialize CodeQL

View File

@ -1,4 +1,4 @@
FROM gitpod/workspace-java-21:2024-07-14-17-19-51
FROM gitpod/workspace-java-17:2024-04-29-23-03-42
ENV LLVM_SCRIPT="tmp_llvm.sh"

View File

@ -18,7 +18,6 @@
* [ParenthesesGenerator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java)
* [Permutation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Permutation.java)
* [PowerSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/PowerSum.java)
* [SubsequenceFinder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java)
* [WordSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/WordSearch.java)
* bitmanipulation
* [BitSwap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java)
@ -53,7 +52,6 @@
* [SimpleSubCipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java)
* [Vigenere](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/Vigenere.java)
* conversions
* [AffineConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/AffineConverter.java)
* [AnyBaseToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java)
* [AnyBaseToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/AnyBaseToDecimal.java)
* [AnytoAny](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/AnytoAny.java)
@ -62,7 +60,7 @@
* [BinaryToOctal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java)
* [DecimalToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java)
* [DecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java)
* [DecimalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/DecimalToHexadecimal.java)
* [DecimalToHexaDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/DecimalToHexaDecimal.java)
* [DecimalToOctal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/DecimalToOctal.java)
* [HexaDecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexaDecimalToBinary.java)
* [HexaDecimalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java)
@ -74,8 +72,6 @@
* [RgbHsvConversion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java)
* [RomanToInteger](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/RomanToInteger.java)
* [TurkishToLatinConversion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java)
* [UnitConversions](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/UnitConversions.java)
* [UnitsConverter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/UnitsConverter.java)
* datastructures
* bags
* [Bag](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/bags/Bag.java)
@ -100,15 +96,14 @@
* dynamicarray
* [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java)
* graphs
* [AStar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java)
* [A Star](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java)
* [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java)
* [BipartiteGraphDFS](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java)
* [BipartiteGrapfDFS](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java)
* [BoruvkaAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java)
* [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java)
* [Cycles](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java)
* [DijkstraAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java)
* [DIJSKSTRAS ALGORITHM](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java)
* [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java)
* [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/FordFulkerson.java)
* [Graphs](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java)
* [HamiltonianCycle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java)
* [KahnsAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java)
@ -126,6 +121,7 @@
* [HashMapCuckooHashing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java)
* [Intersection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java)
* [LinearProbingHashMap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java)
* [Main](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java)
* [MainCuckooHashing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java)
* [MajorityElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java)
* [Map](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java)
@ -145,7 +141,7 @@
* [CreateAndDetectLoop](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java)
* [CursorLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java)
* [DoublyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java)
* [MergeKSortedLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java)
* [Merge K SortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java)
* [MergeSortedArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java)
* [MergeSortedSinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java)
* [QuickSortLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/QuickSortLinkedList.java)
@ -158,15 +154,14 @@
* [Node](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/Node.java)
* queues
* [CircularQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java)
* [Deque](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Deque.java)
* [Deques](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Deques.java)
* [GenericArrayListQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java)
* [LinkedQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java)
* [PriorityQueues](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java)
* [Queue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Queue.java)
* [Queues](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Queues.java)
* stacks
* [NodeStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java)
* [ReverseStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java)
* [Stack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/Stack.java)
* [StackArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java)
* [StackArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackArrayList.java)
* [StackOfLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java)
@ -197,7 +192,6 @@
* [RedBlackBST](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java)
* [SameTreesCheck](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java)
* [SegmentTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java)
* [SplayTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java)
* [TreeRandomNode](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java)
* [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java)
* [VerticalOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java)
@ -231,6 +225,7 @@
* [EditDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java)
* [EggDropping](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java)
* [Fibonacci](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java)
* [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java)
* [KadaneAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java)
* [Knapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java)
* [KnapsackMemoization](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java)
@ -295,7 +290,6 @@
* [DistanceFormula](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/DistanceFormula.java)
* [DudeneyNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/DudeneyNumber.java)
* [EulerMethod](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/EulerMethod.java)
* [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/EulersFunction.java)
* [Factorial](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/Factorial.java)
* [FactorialRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FactorialRecursion.java)
* [FastInverseSqrt](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java)
@ -361,7 +355,6 @@
* [ReverseNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/ReverseNumber.java)
* [RomanNumeralUtil](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java)
* [SecondMinMax](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/SecondMinMax.java)
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java)
* [SimpsonIntegration](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java)
* [SquareFreeInteger](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java)
* [SquareRootWithBabylonianMethod](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java)
@ -383,7 +376,7 @@
* [ColorContrastRatio](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java)
* [InverseOfMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java)
* [MapReduce](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MapReduce.java)
* [MatrixTranspose](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MatrixTranspose.java)
* [matrixTranspose](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/matrixTranspose.java)
* [MedianOfMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfMatrix.java)
* [MedianOfRunningArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java)
* [MedianOfRunningArrayByte](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayByte.java)
@ -396,7 +389,7 @@
* [PalindromeSinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java)
* [RangeInSortedArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java)
* [Sort012D](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sort012D.java)
* [Sparsity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparsity.java)
* [Sparcity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparcity.java)
* [ThreeSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java)
* [TwoSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/TwoSumProblem.java)
* [WordBoggle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/WordBoggle.java)
@ -410,20 +403,22 @@
* [HammingDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/cn/HammingDistance.java)
* [Conway](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Conway.java)
* [CountChar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountChar.java)
* [CountSetBits](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountSetBits.java)
* [countSetBits](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/countSetBits.java)
* [CountWords](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountWords.java)
* [CRC16](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CRC16.java)
* [CRC32](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CRC32.java)
* [CRCAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CRCAlgorithm.java)
* [Damm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Damm.java)
* [Dijkstra](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Dijkstra.java)
* [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/EulersFunction.java)
* [FibbonaciSeries](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/FibbonaciSeries.java)
* [FloydTriangle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/FloydTriangle.java)
* [GaussLegendre](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/GaussLegendre.java)
* [GuassLegendre](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/GuassLegendre.java)
* [HappyNumbersSeq](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java)
* [Huffman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Huffman.java)
* [Implementing auto completing features using trie](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java)
* [InsertDeleteInArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java)
* [KMP](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/KMP.java)
* [KochSnowflake](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/KochSnowflake.java)
* [Krishnamurthy](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Krishnamurthy.java)
* [LinearCongruentialGenerator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java)
@ -439,13 +434,17 @@
* [PerlinNoise](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PerlinNoise.java)
* [PrintAMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java)
* [QueueUsingTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java)
* [RabinKarp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RabinKarp.java)
* [RemoveDuplicateFromString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java)
* [ReturnSubsequence](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/ReturnSubsequence.java)
* [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/ReverseStackUsingRecursion.java)
* [RotateMatrixBy90Degrees](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.java)
* [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RootPrecision.java)
* [RotateMatriceBy90Degree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java)
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java)
* [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/SkylineProblem.java)
* [StringMatchFiniteAutomata](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java)
* [Sudoku](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Sudoku.java)
* [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TopKWords.java)
* [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TowerOfHanoi.java)
* [TwoPointers](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TwoPointers.java)
* [Verhoeff](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Verhoeff.java)
@ -480,7 +479,7 @@
* [RowColumnWiseSorted2dArrayBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java)
* [SaddlebackSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java)
* [SearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java)
* [SortOrderAgnosticBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearch.java)
* [sortOrderAgnosticBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java)
* [SquareRootBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java)
* [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/TernarySearch.java)
* [UnionFind](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/UnionFind.java)
@ -491,7 +490,7 @@
* [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BitonicSort.java)
* [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BogoSort.java)
* [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BubbleSort.java)
* [BubbleSortRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.java)
* [BubbleSortRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java)
* [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BucketSort.java)
* [CircleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CircleSort.java)
* [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java)
@ -502,7 +501,6 @@
* [DualPivotQuickSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java)
* [DutchNationalFlagSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java)
* [ExchangeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/ExchangeSort.java)
* [FlashSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/FlashSort.java)
* [GnomeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/GnomeSort.java)
* [HeapSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/HeapSort.java)
* [InsertionSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/InsertionSort.java)
@ -513,26 +511,22 @@
* [MergeSortRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java)
* [OddEvenSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/OddEvenSort.java)
* [PancakeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PancakeSort.java)
* [PatienceSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PatienceSort.java)
* [PigeonholeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java)
* [QuickSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/QuickSort.java)
* [RadixSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/RadixSort.java)
* [SelectionSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SelectionSort.java)
* [SelectionSortRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SelectionSortRecursive.java)
* [ShellSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/ShellSort.java)
* [SimpleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SimpleSort.java)
* [SlowSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SlowSort.java)
* [SortAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java)
* [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SortUtils.java)
* [SortUtilsRandomGenerator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java)
* [SpreadSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SpreadSort.java)
* [StoogeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/StoogeSort.java)
* [StrandSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/StrandSort.java)
* [SwapSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/SwapSort.java)
* [TimSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/TimSort.java)
* [TopologicalSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/TopologicalSort.java)
* [TreeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/TreeSort.java)
* [WaveSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/WaveSort.java)
* [WiggleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/WiggleSort.java)
* stacks
* [BalancedBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/stacks/BalancedBrackets.java)
@ -555,16 +549,14 @@
* [HammingDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/HammingDistance.java)
* [HorspoolSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/HorspoolSearch.java)
* [Isomorphic](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Isomorphic.java)
* [KMP](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/KMP.java)
* [LetterCombinationsOfPhoneNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java)
* [LongestNonRepetitiveSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.java)
* [longestNonRepeativeSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java)
* [LongestPalindromicSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java)
* [Lower](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Lower.java)
* [MyAtoi](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/MyAtoi.java)
* [Palindrome](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Palindrome.java)
* [Pangram](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Pangram.java)
* [PermuteString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/PermuteString.java)
* [RabinKarp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/RabinKarp.java)
* [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ReverseString.java)
* [ReverseStringRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java)
* [ReverseWordsInString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java)
@ -574,7 +566,7 @@
* [ValidParentheses](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ValidParentheses.java)
* [WordLadder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/WordLadder.java)
* zigZagPattern
* [ZigZagPattern](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java)
* [zigZagPattern](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java)
* test
* java
* com
@ -586,11 +578,9 @@
* [FloodFillTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java)
* [MazeRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java)
* [MColoringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/MColoringTest.java)
* [NQueensTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/NQueensTest.java)
* [ParenthesesGeneratorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/ParenthesesGeneratorTest.java)
* [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java)
* [PowerSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java)
* [SubsequenceFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/SubsequenceFinderTest.java)
* [WordSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java)
* bitmanipulation
* [BitSwapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java)
@ -614,14 +604,10 @@
* [SimpleSubCipherTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java)
* [VigenereTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/VigenereTest.java)
* conversions
* [AnyBaseToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/AnyBaseToDecimalTest.java)
* [BinaryToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java)
* [BinaryToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java)
* [BinaryToOctalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java)
* [DecimalToAnyBaseTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToAnyBaseTest.java)
* [DecimalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToBinaryTest.java)
* [DecimalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToHexadecimalTest.java)
* [DecimalToOctalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToOctalTest.java)
* [DecimalToHexaDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToHexaDecimalTest.java)
* [HexaDecimalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java)
* [HexaDecimalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java)
* [HexToOctTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexToOctTest.java)
@ -630,11 +616,7 @@
* [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java)
* [OctalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java)
* [RomanToIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java)
* [UnitConversionsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/UnitConversionsTest.java)
* [UnitsConverterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/UnitsConverterTest.java)
* datastructures
* bag
* [BagTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/bag/BagTest.java)
* bloomfilter
* [BloomFilterTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java)
* buffers
@ -652,12 +634,8 @@
* [TwoPSetTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/crdt/TwoPSetTest.java)
* disjointsetunion
* [DisjointSetUnionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionTest.java)
* dynamicarray
* [DynamicArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/dynamicarray/DynamicArrayTest.java)
* graphs
* [BoruvkaAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithmTest.java)
* [DijkstraAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithmTest.java)
* [FordFulkersonTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/FordFulkersonTest.java)
* [HamiltonianCycleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java)
* [KosarajuTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java)
* [TarjansAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java)
@ -666,7 +644,6 @@
* hashing
* [GenericHashMapUsingArrayListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java)
* [GenericHashMapUsingArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java)
* [HashMapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapTest.java)
* [LinearProbingHashMapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java)
* [MajorityElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java)
* [MapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java)
@ -675,23 +652,14 @@
* [FibonacciHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java)
* [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java)
* lists
* [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java)
* [QuickSortLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/QuickSortLinkedListTest.java)
* [ReverseKGroupTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/ReverseKGroupTest.java)
* [RotateSinglyLinkedListsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedListsTest.java)
* [SinglyLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java)
* [SkipListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java)
* queues
* [CircularQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/CircularQueueTest.java)
* [DequeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/DequeTest.java)
* [GenericArrayListQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/GenericArrayListQueueTest.java)
* [LinkedQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java)
* [PriorityQueuesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java)
* [QueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/QueueTest.java)
* stacks
* [LinkedListStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/stacks/LinkedListStackTest.java)
* [StackArrayListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayListTest.java)
* [StackArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/stacks/StackArrayTest.java)
* trees
* [BinaryTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java)
* [BSTFromSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java)
@ -709,7 +677,6 @@
* [PostOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java)
* [PreOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java)
* [SameTreesCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java)
* [SplayTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SplayTreeTest.java)
* [TreeTestUtils](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java)
* [VerticalOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java)
* [ZigzagTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java)
@ -717,27 +684,17 @@
* [BinaryExponentiationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java)
* [StrassenMatrixMultiplicationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java)
* dynamicprogramming
* [BoardPathTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/BoardPathTest.java)
* [CatalanNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java)
* [ClimbStairsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/ClimbStairsTest.java)
* [EditDistanceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/EditDistanceTest.java)
* [climbStairsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java)
* [EggDroppingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java)
* [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java)
* [KnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackTest.java)
* [LevenshteinDistanceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java)
* [LongestAlternatingSubsequenceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequenceTest.java)
* [LongestIncreasingSubsequenceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceTests.java)
* [LongestPalindromicSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstringTest.java)
* [LongestValidParenthesesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LongestValidParenthesesTest.java)
* [MinimumPathSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/MinimumPathSumTest.java)
* [MinimumSumPartitionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/MinimumSumPartitionTest.java)
* [OptimalJobSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java)
* [PalindromicPartitioningTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioningTest.java)
* [PartitionProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java)
* [RegexMatchingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/RegexMatchingTest.java)
* [ShortestCommonSupersequenceLengthTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLengthTest.java)
* [SubsetCountTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java)
* [SubsetSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SubsetSumTest.java)
* [SumOfSubsetTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SumOfSubsetTest.java)
* [TribonacciTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/TribonacciTest.java)
* [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/UniquePathsTests.java)
@ -770,12 +727,9 @@
* [CollatzConjectureTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java)
* [CombinationsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/CombinationsTest.java)
* [CrossCorrelationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/CrossCorrelationTest.java)
* [DeterminantOfMatrixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/DeterminantOfMatrixTest.java)
* [DigitalRootTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/DigitalRootTest.java)
* [DistanceFormulaTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java)
* [DudeneyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java)
* [EulersFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/EulersFunctionTest.java)
* [FactorialRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FactorialRecursionTest.java)
* [FactorialTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FactorialTest.java)
* [FastInverseSqrtTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FastInverseSqrtTests.java)
* [FFTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FFTTest.java)
@ -783,7 +737,6 @@
* [FibonacciLoopTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FibonacciLoopTest.java)
* [FibonacciNumberCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FibonacciNumberCheckTest.java)
* [FibonacciNumberGoldenRationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FibonacciNumberGoldenRationTest.java)
* [FindKthNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindKthNumberTest.java)
* [FindMaxRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java)
* [FindMaxTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindMaxTest.java)
* [FindMinRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindMinRecursionTest.java)
@ -791,7 +744,6 @@
* [FloorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FloorTest.java)
* [FrizzyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java)
* [GaussianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GaussianTest.java)
* [GCDRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GCDRecursionTest.java)
* [GCDTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GCDTest.java)
* [GenericRootTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GenericRootTest.java)
* [HarshadNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java)
@ -804,17 +756,13 @@
* [LongDivisionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LongDivisionTest.java)
* [LucasSeriesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java)
* [MatrixRankTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MatrixRankTest.java)
* [MatrixUtilTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MatrixUtilTest.java)
* [MaxValueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MaxValueTest.java)
* [MeansTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MeansTest.java)
* [MedianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MedianTest.java)
* [MillerRabinPrimalityCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MillerRabinPrimalityCheckTest.java)
* [MinValueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MinValueTest.java)
* [MobiusFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java)
* [ModeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ModeTest.java)
* [NonRepeatingElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/NonRepeatingElementTest.java)
* [NthUglyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java)
* [NumberOfDigitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/NumberOfDigitsTest.java)
* [PalindromeNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PalindromeNumberTest.java)
* [ParseIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ParseIntegerTest.java)
* [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java)
@ -825,14 +773,12 @@
* [PollardRhoTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PollardRhoTest.java)
* [PowerOfTwoOrNotTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java)
* [PowerUsingRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PowerUsingRecursionTest.java)
* [PowTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PowTest.java)
* [PrimeCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java)
* [PrimeFactorizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java)
* [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java)
* [PythagoreanTripleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java)
* [ReverseNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java)
* [SecondMinMaxTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SecondMinMaxTest.java)
* [SieveOfEratosthenesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SieveOfEratosthenesTest.java)
* [SquareFreeIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java)
* [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java)
* [SquareRootWithNewtonRaphsonTestMethod](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java)
@ -863,12 +809,12 @@
* [ConwayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ConwayTest.java)
* [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java)
* [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
* [CountSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountSetBitsTest.java)
* [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java)
* [CountWordsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountWordsTest.java)
* [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java)
* [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java)
* [EulersFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/EulersFunctionTest.java)
* [FirstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java)
* [FloydTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FloydTriangleTest.java)
* [KadaneAlogrithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java)
* [LineSweepTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LineSweepTest.java)
* [LinkListSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkListSortTest.java)
@ -877,11 +823,7 @@
* [NewManShanksPrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java)
* [NextFitTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NextFitTest.java)
* [PasswordGenTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/PasswordGenTest.java)
* [QueueUsingTwoStacksTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java)
* [RemoveDuplicateFromStringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/RemoveDuplicateFromStringTest.java)
* [ReturnSubsequenceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ReturnSubsequenceTest.java)
* [ReverseStackUsingRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ReverseStackUsingRecursionTest.java)
* [StringMatchFiniteAutomataTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/StringMatchFiniteAutomataTest.java)
* [SieveOfEratosthenesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/SieveOfEratosthenesTest.java)
* [TestPrintMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java)
* [TwoPointersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TwoPointersTest.java)
* [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java)
@ -903,39 +845,28 @@
* [RabinKarpAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java)
* [RecursiveBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RecursiveBinarySearchTest.java)
* [RowColumnWiseSorted2dArrayBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java)
* [SortOrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/SortOrderAgnosticBinarySearchTest.java)
* [sortOrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java)
* [TestSearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java)
* sorts
* [BeadSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BeadSortTest.java)
* [BinaryInsertionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java)
* [BitonicSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BitonicSortTest.java)
* [BogoSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BogoSortTest.java)
* [BubbleSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BubbleSortRecursiveTest.java)
* [BubbleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java)
* [BucketSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BucketSortTest.java)
* [CircleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CircleSortTest.java)
* [CocktailShakerSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java)
* [CombSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CombSortTest.java)
* [CountingSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CountingSortTest.java)
* [CycleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CycleSortTest.java)
* [DualPivotQuickSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java)
* [DutchNationalFlagSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java)
* [ExchangeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/ExchangeSortTest.java)
* [FlashSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/FlashSortTest.java)
* [GnomeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/GnomeSortTest.java)
* [HeapSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/HeapSortTest.java)
* [InsertionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java)
* [IntrospectiveSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java)
* [MergeSortNoExtraSpaceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortNoExtraSpaceTest.java)
* [MergeSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java)
* [MergeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortTest.java)
* [OddEvenSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java)
* [PancakeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PancakeSortTest.java)
* [PatienceSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PatienceSortTest.java)
* [PigeonholeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java)
* [QuickSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/QuickSortTest.java)
* [RadixSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/RadixSortTest.java)
* [SelectionSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java)
* [SelectionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java)
* [ShellSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/ShellSortTest.java)
* [SimpleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java)
@ -943,24 +874,12 @@
* [SortingAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java)
* [SortUtilsRandomGeneratorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java)
* [SortUtilsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java)
* [SpreadSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SpreadSortTest.java)
* [StoogeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/StoogeSortTest.java)
* [StrandSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/StrandSortTest.java)
* [SwapSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SwapSortTest.java)
* [TimSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TimSortTest.java)
* [TopologicalSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java)
* [TreeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TreeSortTest.java)
* [WaveSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WaveSortTest.java)
* [WiggleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java)
* stacks
* [BalancedBracketsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/BalancedBracketsTest.java)
* [DecimalToAnyUsingStackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DecimalToAnyUsingStackTest.java)
* [DuplicateBracketsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/DuplicateBracketsTest.java)
* [InfixToPostfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/InfixToPostfixTest.java)
* [LargestRectangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/LargestRectangleTest.java)
* [NextGreaterElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/NextGreaterElementTest.java)
* [NextSmallerElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/NextSmallerElementTest.java)
* [PostfixToInfixTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/PostfixToInfixTest.java)
* [StackPostfixNotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/stacks/StackPostfixNotationTest.java)
* strings
* [AhoCorasickTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AhoCorasickTest.java)
@ -973,13 +892,11 @@
* [HorspoolSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java)
* [IsomorphicTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/IsomorphicTest.java)
* [LetterCombinationsOfPhoneNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java)
* [LongestNonRepetitiveSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LongestNonRepetitiveSubstringTest.java)
* [LongestPalindromicSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LongestPalindromicSubstringTest.java)
* [longestNonRepeativeSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java)
* [LowerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LowerTest.java)
* [MyAtoiTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/MyAtoiTest.java)
* [PalindromeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PalindromeTest.java)
* [PangramTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PangramTest.java)
* [PermuteStringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PermuteStringTest.java)
* [ReverseStringRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java)
* [ReverseStringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ReverseStringTest.java)
* [ReverseWordsInStringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ReverseWordsInStringTest.java)
@ -989,4 +906,4 @@
* [ValidParenthesesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java)
* [WordLadderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/WordLadderTest.java)
* zigZagPattern
* [ZigZagPatternTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java)
* [zigZagPatternTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java)

View File

@ -99,7 +99,7 @@
<!-- Checks for Javadoc comments. -->
<!-- See https://checkstyle.org/checks/javadoc/index.html -->
<module name="InvalidJavadocPosition"/>
<!-- TODO <module name="InvalidJavadocPosition"/> -->
<!-- TODO <module name="JavadocMethod"/> -->
<!-- TODO <module name="JavadocType"/> -->
<!-- TODO <module name="JavadocVariable"/> -->
@ -108,19 +108,19 @@
<!-- Checks for Naming Conventions. -->
<!-- See https://checkstyle.org/checks/naming/index.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<!-- TODO <module name="ConstantName"/> -->
<!-- TODO <module name="LocalFinalVariableName"/> -->
<!-- TODO <module name="LocalVariableName"/> -->
<!-- TODO <module name="MemberName"/> -->
<!-- TODO <module name="MethodName"/> -->
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<!-- TODO <module name="ParameterName"/> -->
<!-- TODO <module name="StaticVariableName"/> -->
<!-- TODO <module name="TypeName"/> -->
<!-- Checks for imports -->
<!-- See https://checkstyle.org/checks/imports/index.html -->
<module name="AvoidStarImport"/>
<!-- TODO <module name="AvoidStarImport"/> -->
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
<module name="RedundantImport"/>
<module name="UnusedImports">
@ -139,49 +139,49 @@
<module name="MethodParamPad"/>
<!-- TODO <module name="NoWhitespaceAfter"/> -->
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<!-- TODO <module name="OperatorWrap"/> -->
<!-- TODO <module name="ParenPad"/> -->
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<!-- TODO <module name="WhitespaceAround"/> -->
<!-- Modifier Checks -->
<!-- See https://checkstyle.org/checks/modifier/index.html -->
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<!-- TODO <module name="ModifierOrder"/> -->
<!-- TODO <module name="RedundantModifier"/> -->
<!-- Checks for blocks. You know, those {}'s -->
<!-- See https://checkstyle.org/checks/blocks/index.html -->
<module name="AvoidNestedBlocks"/>
<!-- TODO <module name="AvoidNestedBlocks"/> -->
<!-- TODO <module name="EmptyBlock"/> -->
<!-- TODO <module name="LeftCurly"/> -->
<module name="NeedBraces"/>
<!-- TODO <module name="NeedBraces"/> -->
<!-- TODO <module name="RightCurly"/> -->
<!-- Checks for common coding problems -->
<!-- See https://checkstyle.org/checks/coding/index.html -->
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<!-- TODO <module name="EqualsHashCode"/> -->
<!-- TODO <module name="HiddenField"/> -->
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<!-- TODO <module name="InnerAssignment"/> -->
<!-- TODO <module name="MagicNumber"/> -->
<module name="MissingSwitchDefault"/>
<module name="MultipleVariableDeclarations"/>
<!-- TODO <module name="MissingSwitchDefault"/> -->
<!-- TODO <module name="MultipleVariableDeclarations"/> -->
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- Checks for class design -->
<!-- See https://checkstyle.org/checks/design/index.html -->
<!-- TODO <module name="DesignForExtension"/> -->
<module name="FinalClass"/>
<module name="HideUtilityClassConstructor"/>
<!-- TODO <module name="FinalClass"/> -->
<!-- TODO <module name="HideUtilityClassConstructor"/> -->
<module name="InterfaceIsType"/>
<!-- TODO <module name="VisibilityModifier"/> -->
<!-- Miscellaneous other checks. -->
<!-- See https://checkstyle.org/checks/misc/index.html -->
<module name="ArrayTypeStyle"/>
<!-- TODO <module name="ArrayTypeStyle"/> -->
<!-- TODO <module name="FinalParameters"/> -->
<!-- TODO <module name="TodoComment"/> -->
<module name="UpperEll"/>

View File

@ -1,90 +0,0 @@
com.thealgorithms.bitmanipulation.SingleBitOperations=UselessParentheses
com.thealgorithms.ciphers.AffineCipher=UselessParentheses
com.thealgorithms.ciphers.ColumnarTranspositionCipher=UnnecessaryFullyQualifiedName
com.thealgorithms.ciphers.DES=UselessParentheses
com.thealgorithms.ciphers.HillCipher=UselessParentheses
com.thealgorithms.ciphers.RSA=UselessParentheses
com.thealgorithms.conversions.AnyBaseToAnyBase=UselessParentheses
com.thealgorithms.conversions.AnytoAny=UselessParentheses
com.thealgorithms.conversions.HexToOct=UselessParentheses
com.thealgorithms.conversions.IntegerToRoman=UnnecessaryFullyQualifiedName
com.thealgorithms.datastructures.crdt.LWWElementSet=UselessParentheses
com.thealgorithms.datastructures.crdt.Pair=UnusedPrivateField
com.thealgorithms.datastructures.graphs.AStar=UselessParentheses
com.thealgorithms.datastructures.graphs.AdjacencyMatrixGraph=CollapsibleIfStatements,UnnecessaryFullyQualifiedName,UselessParentheses
com.thealgorithms.datastructures.graphs.BipartiteGraphDFS=CollapsibleIfStatements
com.thealgorithms.datastructures.graphs.Kruskal=UselessParentheses
com.thealgorithms.datastructures.hashmap.hashing.HashMapCuckooHashing=UselessParentheses
com.thealgorithms.datastructures.heaps.FibonacciHeap=UselessParentheses
com.thealgorithms.datastructures.heaps.HeapElement=UselessParentheses
com.thealgorithms.datastructures.heaps.HeapNode=UselessParentheses
com.thealgorithms.datastructures.lists.DoublyLinkedList=UselessParentheses
com.thealgorithms.datastructures.lists.SearchSinglyLinkedListRecursion=UselessParentheses
com.thealgorithms.datastructures.lists.SinglyLinkedList=UnusedLocalVariable
com.thealgorithms.datastructures.queues.PriorityQueue=UselessParentheses
com.thealgorithms.datastructures.stacks.NodeStack=UnnecessaryFullyQualifiedName,UnusedFormalParameter
com.thealgorithms.datastructures.stacks.StackArray=UselessParentheses
com.thealgorithms.datastructures.trees.CheckBinaryTreeIsValidBST=UselessParentheses
com.thealgorithms.datastructures.trees.SegmentTree=UselessParentheses
com.thealgorithms.devutils.nodes.LargeTreeNode=UselessParentheses
com.thealgorithms.devutils.nodes.SimpleNode=UselessParentheses
com.thealgorithms.devutils.nodes.SimpleTreeNode=UselessParentheses
com.thealgorithms.devutils.nodes.TreeNode=UselessParentheses
com.thealgorithms.divideandconquer.ClosestPair=UnnecessaryFullyQualifiedName,UselessParentheses
com.thealgorithms.divideandconquer.Point=UselessParentheses
com.thealgorithms.dynamicprogramming.MatrixChainMultiplication=UselessParentheses
com.thealgorithms.dynamicprogramming.ShortestSuperSequence=UselessParentheses
com.thealgorithms.dynamicprogramming.UniquePaths=UnnecessarySemicolon
com.thealgorithms.dynamicprogramming.WineProblem=UselessParentheses
com.thealgorithms.maths.BinomialCoefficient=UselessParentheses
com.thealgorithms.maths.Complex=UselessParentheses
com.thealgorithms.maths.DistanceFormulaTest=UnnecessaryFullyQualifiedName
com.thealgorithms.maths.Gaussian=UselessParentheses
com.thealgorithms.maths.GcdSolutionWrapper=UselessParentheses
com.thealgorithms.maths.HeronsFormula=UselessParentheses
com.thealgorithms.maths.KaprekarNumbers=UselessParentheses
com.thealgorithms.maths.KeithNumber=UselessParentheses
com.thealgorithms.maths.LeonardoNumber=UselessParentheses
com.thealgorithms.maths.LinearDiophantineEquationsSolver=UselessParentheses
com.thealgorithms.maths.MatrixUtil=UselessParentheses
com.thealgorithms.maths.RomanNumeralUtil=UselessParentheses
com.thealgorithms.maths.SecondMinMax=UselessParentheses
com.thealgorithms.maths.SecondMinMaxTest=UnnecessaryFullyQualifiedName
com.thealgorithms.maths.StandardDeviation=UselessParentheses
com.thealgorithms.maths.SumOfArithmeticSeries=UselessParentheses
com.thealgorithms.maths.TrinomialTriangle=UselessParentheses
com.thealgorithms.maths.VampireNumber=CollapsibleIfStatements
com.thealgorithms.maths.Volume=UselessParentheses
com.thealgorithms.matrixexponentiation.Fibonacci=UnnecessaryFullyQualifiedName
com.thealgorithms.misc.Sparsity=UselessParentheses
com.thealgorithms.misc.ThreeSumProblem=UselessParentheses
com.thealgorithms.misc.WordBoggle=UselessParentheses
com.thealgorithms.others.CRC16=UselessParentheses
com.thealgorithms.others.Damm=UnnecessaryFullyQualifiedName
com.thealgorithms.others.Luhn=UnnecessaryFullyQualifiedName
com.thealgorithms.others.Mandelbrot=UselessParentheses
com.thealgorithms.others.MaximumSumOfDistinctSubarraysWithLengthK=CollapsibleIfStatements
com.thealgorithms.others.MiniMaxAlgorithm=UselessParentheses
com.thealgorithms.others.PageRank=UselessParentheses
com.thealgorithms.others.PerlinNoise=UselessParentheses
com.thealgorithms.others.QueueUsingTwoStacks=UselessParentheses
com.thealgorithms.others.QueueWithStack=UselessParentheses
com.thealgorithms.others.Trieac=UselessParentheses
com.thealgorithms.others.Verhoeff=UnnecessaryFullyQualifiedName
com.thealgorithms.searches.InterpolationSearch=UselessParentheses
com.thealgorithms.searches.KMPSearch=UselessParentheses
com.thealgorithms.searches.LinearSearchThread=EmptyCatchBlock
com.thealgorithms.searches.RabinKarpAlgorithm=UselessParentheses
com.thealgorithms.sorts.CircleSort=EmptyControlStatement
com.thealgorithms.sorts.CombSort=UselessParentheses
com.thealgorithms.sorts.DutchNationalFlagSort=UselessParentheses
com.thealgorithms.sorts.LinkListSort=EmptyControlStatement,UnusedLocalVariable
com.thealgorithms.sorts.MergeSortNoExtraSpace=UselessParentheses
com.thealgorithms.sorts.PigeonholeSort=UselessParentheses
com.thealgorithms.sorts.RadixSort=UselessParentheses
com.thealgorithms.sorts.WiggleSort=UselessParentheses
com.thealgorithms.stacks.PostfixToInfix=UselessParentheses
com.thealgorithms.strings.HorspoolSearch=UnnecessaryFullyQualifiedName,UselessParentheses
com.thealgorithms.strings.MyAtoi=UselessParentheses
com.thealgorithms.strings.Palindrome=UselessParentheses
com.thealgorithms.strings.Solution=CollapsibleIfStatements

61
pom.xml
View File

@ -10,9 +10,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<assertj.version>3.26.3</assertj.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<assertj.version>3.25.3</assertj.version>
</properties>
<dependencyManagement>
@ -20,7 +20,7 @@
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<version>5.10.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -31,7 +31,7 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
@ -44,18 +44,18 @@
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.11.0</version>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.17.0</version>
<version>3.14.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.5.0-M2</version>
<version>4.5.0-M1</version>
</dependency>
</dependencies>
@ -63,7 +63,7 @@
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.0</version>
<version>3.2.5</version>
<configuration>
<forkNode implementation="org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"/>
</configuration>
@ -71,18 +71,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<version>3.10.1</version>
<configuration>
<source>21</source>
<target>21</target>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-Xlint:-auxiliaryclass</arg>
<arg>-Xlint:-rawtypes</arg>
<arg>-Xlint:-unchecked</arg>
<arg>-Xlint:-lossy-conversions</arg>
<arg>-Werror</arg>
</compilerArgs>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
<plugin>
@ -107,7 +99,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.5.0</version>
<version>3.3.1</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<consoleOutput>true</consoleOutput>
@ -118,40 +110,17 @@
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.18.1</version>
<version>9.3</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.8.6.3</version>
<version>4.8.4.0</version>
<configuration>
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
<includeTests>true</includeTests>
<plugins>
<plugin>
<groupId>com.mebigfatguy.fb-contrib</groupId>
<artifactId>fb-contrib</artifactId>
<version>7.6.4</version>
</plugin>
<plugin>
<groupId>com.h3xstream.findsecbugs</groupId>
<artifactId>findsecbugs-plugin</artifactId>
<version>1.13.0</version>
</plugin>
</plugins>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-pmd-plugin</artifactId>
<version>3.25.0</version>
<configuration>
<printFailingErrors>true</printFailingErrors>
<includeTests>true</includeTests>
<linkXRef>false</linkXRef>
<excludeFromFailureFile>pmd-exclude.properties</excludeFromFailureFile>
</configuration>
</plugin>
</plugins>

View File

@ -5,18 +5,30 @@
<Match>
<Bug pattern="EI_EXPOSE_REP2" />
</Match>
<Match>
<Bug pattern="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD" />
</Match>
<Match>
<Bug pattern="DMI_RANDOM_USED_ONLY_ONCE" />
</Match>
<Match>
<Bug pattern="VA_FORMAT_STRING_USES_NEWLINE" />
</Match>
<Match>
<Bug pattern="SF_SWITCH_NO_DEFAULT" />
</Match>
<Match>
<Bug pattern="UC_USELESS_OBJECT" />
</Match>
<Match>
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" />
</Match>
<Match>
<Bug pattern="DM_NEXTINT_VIA_NEXTDOUBLE" />
</Match>
<Match>
<Bug pattern="NM_CLASS_NAMING_CONVENTION" />
</Match>
<Match>
<Bug pattern="SIC_INNER_SHOULD_BE_STATIC" />
</Match>
@ -41,6 +53,9 @@
<Match>
<Bug pattern="INT_BAD_REM_BY_1" />
</Match>
<Match>
<Bug pattern="NM_METHOD_NAMING_CONVENTION" />
</Match>
<Match>
<Bug pattern="ICAST_IDIV_CAST_TO_DOUBLE" />
</Match>
@ -59,12 +74,33 @@
<Match>
<Bug pattern="MS_EXPOSE_REP" />
</Match>
<Match>
<Bug pattern="IM_BAD_CHECK_FOR_ODD" />
</Match>
<Match>
<Bug pattern="WMI_WRONG_MAP_ITERATOR" />
</Match>
<Match>
<Bug pattern="DM_BOXED_PRIMITIVE_FOR_PARSING" />
</Match>
<Match>
<Bug pattern="MS_SHOULD_BE_FINAL" />
</Match>
<Match>
<Bug pattern="UWF_UNWRITTEN_FIELD" />
</Match>
<Match>
<Bug pattern="SS_SHOULD_BE_STATIC" />
</Match>
<Match>
<Bug pattern="HE_EQUALS_USE_HASHCODE" />
</Match>
<Match>
<Bug pattern="IT_NO_SUCH_ELEMENT" />
</Match>
<Match>
<Bug pattern="DLS_DEAD_LOCAL_STORE" />
</Match>
<Match>
<Bug pattern="UWF_NULL_FIELD" />
</Match>
@ -77,6 +113,9 @@
<Match>
<Bug pattern="NP_IMMEDIATE_DEREFERENCE_OF_READLINE" />
</Match>
<Match>
<Bug pattern="RV_RETURN_VALUE_IGNORED" />
</Match>
<Match>
<Bug pattern="EQ_COMPARETO_USE_OBJECT_EQUALS" />
</Match>
@ -86,132 +125,7 @@
<Match>
<Bug pattern="RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE" />
</Match>
<!-- fb-contrib -->
<Match>
<Bug pattern="OCP_OVERLY_CONCRETE_PARAMETER" />
</Match>
<Match>
<Bug pattern="LSC_LITERAL_STRING_COMPARISON" />
</Match>
<Match>
<Bug pattern="CE_CLASS_ENVY" />
</Match>
<Match>
<Bug pattern="PSC_PRESIZE_COLLECTIONS" />
</Match>
<Match>
<Bug pattern="SACM_STATIC_ARRAY_CREATED_IN_METHOD" />
</Match>
<Match>
<Bug pattern="LUI_USE_SINGLETON_LIST" />
</Match>
<Match>
<Bug pattern="CLI_CONSTANT_LIST_INDEX" />
</Match>
<Match>
<Bug pattern="CNC_COLLECTION_NAMING_CONFUSION" />
</Match>
<Match>
<Bug pattern="TR_TAIL_RECURSION" />
</Match>
<Match>
<Bug pattern="USBR_UNNECESSARY_STORE_BEFORE_RETURN" />
</Match>
<Match>
<Bug pattern="BL_BURYING_LOGIC" />
</Match>
<Match>
<Bug pattern="PCOA_PARTIALLY_CONSTRUCTED_OBJECT_ACCESS" />
</Match>
<Match>
<Bug pattern="UTWR_USE_TRY_WITH_RESOURCES" />
</Match>
<Match>
<Bug pattern="MUI_CONTAINSKEY_BEFORE_GET" />
</Match>
<Match>
<Bug pattern="IMC_IMMATURE_CLASS_PRINTSTACKTRACE" />
</Match>
<Match>
<Bug pattern="UCPM_USE_CHARACTER_PARAMETERIZED_METHOD" />
</Match>
<Match>
<Bug pattern="SUA_SUSPICIOUS_UNINITIALIZED_ARRAY" />
</Match>
<Match>
<Bug pattern="SPP_USE_MATH_CONSTANT" />
</Match>
<Match>
<Bug pattern="UJM_UNJITABLE_METHOD" />
</Match>
<Match>
<Bug pattern="SEC_SIDE_EFFECT_CONSTRUCTOR" />
</Match>
<Match>
<Bug pattern="MDM_STRING_BYTES_ENCODING" />
</Match>
<Match>
<Bug pattern="PMB_POSSIBLE_MEMORY_BLOAT" />
</Match>
<Match>
<Bug pattern="LSYC_LOCAL_SYNCHRONIZED_COLLECTION" />
</Match>
<Match>
<Bug pattern="IOI_USE_OF_FILE_STREAM_CONSTRUCTORS" />
</Match>
<Match>
<Bug pattern="UP_UNUSED_PARAMETER" />
</Match>
<Match>
<Bug pattern="DSOC_DUBIOUS_SET_OF_COLLECTIONS" />
</Match>
<Match>
<Bug pattern="NAB_NEEDLESS_BOX_TO_UNBOX" />
</Match>
<Match>
<Bug pattern="FPL_FLOATING_POINT_LOOPS" />
</Match>
<Match>
<Bug pattern="ITU_INAPPROPRIATE_TOSTRING_USE" />
</Match>
<Match>
<Bug pattern="SPP_PASSING_THIS_AS_PARM" />
</Match>
<Match>
<Bug pattern="FCBL_FIELD_COULD_BE_LOCAL" />
</Match>
<Match>
<Bug pattern="CFS_CONFUSING_FUNCTION_SEMANTICS" />
</Match>
<Match>
<Bug pattern="PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS" />
</Match>
<Match>
<Bug pattern="FCCD_FIND_CLASS_CIRCULAR_DEPENDENCY" />
</Match>
<Match>
<Bug pattern="PL_PARALLEL_LISTS" />
</Match>
<Match>
<Bug pattern="PCAIL_POSSIBLE_CONSTANT_ALLOCATION_IN_LOOP" />
</Match>
<Match>
<Bug pattern="STT_STRING_PARSING_A_FIELD" />
</Match>
<Match>
<Bug pattern="IMC_IMMATURE_CLASS_BAD_SERIALVERSIONUID" />
</Match>
<Match>
<Bug pattern="DRE_DECLARED_RUNTIME_EXCEPTION" />
</Match>
<Match>
<Bug pattern="SLS_SUSPICIOUS_LOOP_SEARCH" />
</Match>
<!-- find-sec-bugs -->
<Match>
<Bug pattern="PREDICTABLE_RANDOM" />
</Match>
<Match>
<Bug pattern="HARD_CODE_KEY" />
<Bug pattern="RV_ABSOLUTE_VALUE_OF_HASHCODE" />
</Match>
</FindBugsFilter>

View File

@ -1,14 +1,15 @@
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/** Program description - To find all possible paths from source to destination*/
/**Wikipedia link -> https://en.wikipedia.org/wiki/Shortest_path_problem */
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
/**
* Program description - To find all possible paths from source to destination
* <a href="https://en.wikipedia.org/wiki/Shortest_path_problem">Wikipedia</a>
*
* @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a>
*/
public class AllPathsFromSourceToTarget {
// No. of vertices in graph

View File

@ -1,42 +1,29 @@
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.List;
import java.util.*;
/**
* Finds all combinations of 0...n-1 of length k
* Finds all permutations of 1...n of length k
* @author TheClerici (<a href="https://github.com/TheClerici">git-TheClerici</a>)
*/
public final class ArrayCombination {
private ArrayCombination() {
}
public class ArrayCombination {
private static int length;
/**
* Finds all combinations of length k of 0..n-1 using backtracking.
*
* @param n Number of the elements.
* @param k Length of the combination.
* @return A list of all combinations of length k.
* Find all combinations of 1..n by creating an array and using backtracking in Combination.java
* @param n max value of the array.
* @param k length of combination
* @return a list of all combinations of length k. If k == 0, return null.
*/
public static List<List<Integer>> combination(int n, int k) {
if (n < 0 || k < 0 || k > n) {
throw new IllegalArgumentException("Wrong input.");
public static List<TreeSet<Integer>> combination(int n, int k) {
if (n <= 0) {
return null;
}
List<List<Integer>> combinations = new ArrayList<>();
combine(combinations, new ArrayList<>(), 0, n, k);
return combinations;
}
private static void combine(List<List<Integer>> combinations, List<Integer> current, int start, int n, int k) {
if (current.size() == k) { // Base case: combination found
combinations.add(new ArrayList<>(current)); // Copy to avoid modification
return;
}
for (int i = start; i < n; i++) {
current.add(i);
combine(combinations, current, i + 1, n, k);
current.removeLast(); // Backtrack
length = k;
Integer[] arr = new Integer[n];
for (int i = 1; i <= n; i++) {
arr[i - 1] = i;
}
return Combination.combination(arr, length);
}
}

View File

@ -1,17 +1,12 @@
package com.thealgorithms.backtracking;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import java.util.*;
/**
* Finds all permutations of given array
* @author Alan Piao (<a href="https://github.com/cpiao3">git-Alan Piao</a>)
*/
public final class Combination {
private Combination() {
}
public class Combination {
private static int length;
@ -43,9 +38,7 @@ public final class Combination {
* @param <T> the type of elements in the array.
*/
private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
if (index + length - currSet.size() > arr.length) {
return;
}
if (index + length - currSet.size() > arr.length) return;
if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) {
currSet.add(arr[i]);

View File

@ -1,8 +1,6 @@
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.*;
/*
* Problem Statement: -
@ -26,12 +24,10 @@ import java.util.List;
51 46 55 44 53 4 21 12
*/
public final class KnightsTour {
private KnightsTour() {
}
public class KnightsTour {
private static final int BASE = 12;
private static final int[][] MOVES = {
private static final int base = 12;
private static final int[][] moves = {
{1, -2},
{2, -1},
{2, 1},
@ -45,19 +41,19 @@ public final class KnightsTour {
private static int total; // total squares in chess
public static void main(String[] args) {
grid = new int[BASE][BASE];
total = (BASE - 4) * (BASE - 4);
grid = new int[base][base];
total = (base - 4) * (base - 4);
for (int r = 0; r < BASE; r++) {
for (int c = 0; c < BASE; c++) {
if (r < 2 || r > BASE - 3 || c < 2 || c > BASE - 3) {
for (int r = 0; r < base; r++) {
for (int c = 0; c < base; c++) {
if (r < 2 || r > base - 3 || c < 2 || c > base - 3) {
grid[r][c] = -1;
}
}
}
int row = 2 + (int) (Math.random() * (BASE - 4));
int col = 2 + (int) (Math.random() * (BASE - 4));
int row = 2 + (int) (Math.random() * (base - 4));
int col = 2 + (int) (Math.random() * (base - 4));
grid[row][col] = 1;
@ -99,7 +95,7 @@ public final class KnightsTour {
private static List<int[]> neighbors(int row, int column) {
List<int[]> neighbour = new ArrayList<>();
for (int[] m : MOVES) {
for (int[] m : moves) {
int x = m[0];
int y = m[1];
if (grid[row + y][column + x] == 0) {
@ -113,7 +109,7 @@ public final class KnightsTour {
// Returns the total count of neighbors
private static int countNeighbors(int row, int column) {
int num = 0;
for (int[] m : MOVES) {
for (int[] m : moves) {
if (grid[row + m[1]][column + m[0]] == 0) {
num++;
}

View File

@ -1,10 +1,6 @@
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.*;
/**
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
@ -14,9 +10,7 @@ class Node {
Set<Integer> edges = new HashSet<Integer>();
}
public final class MColoring {
private MColoring() {
}
public class MColoring {
static int possiblePaint(ArrayList<Node> nodes, int n, int m) {
// Create a visited array of n nodes
@ -59,9 +53,7 @@ public final class MColoring {
// If number of colors used exceeds m,
// return 0
maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color));
if (maxColors > m) {
return 0;
}
if (maxColors > m) return 0;
// If the adjacent node is not visited,
// mark it visited and push it in queue

View File

@ -1,8 +1,6 @@
package com.thealgorithms.backtracking;
public final class MazeRecursion {
private MazeRecursion() {
}
public class MazeRecursion {
public static void mazeRecursion() {
// First create a 2 dimensions array to mimic a maze map

View File

@ -32,14 +32,15 @@ import java.util.List;
* queen is not placed safely. If there is no such way then return an empty list
* as solution
*/
public final class NQueens {
private NQueens() {
}
public class NQueens {
public static List<List<String>> getNQueensArrangements(int queens) {
List<List<String>> arrangements = new ArrayList<>();
getSolution(queens, arrangements, new int[queens], 0);
return arrangements;
public static void main(String[] args) {
placeQueens(1);
placeQueens(2);
placeQueens(3);
placeQueens(4);
placeQueens(5);
placeQueens(6);
}
public static void placeQueens(final int queens) {

View File

@ -19,7 +19,7 @@ public final class ParenthesesGenerator {
*/
public static List<String> generateParentheses(final int n) {
if (n < 0) {
throw new IllegalArgumentException("The number of pairs of parentheses cannot be negative");
throw new IllegalArgumentException("The number of pairs of parentheses cannot be nagative");
}
List<String> result = new ArrayList<>();
generateParenthesesHelper(result, "", 0, 0, n);

View File

@ -7,9 +7,7 @@ import java.util.List;
* Finds all permutations of given array
* @author Alan Piao (<a href="https://github.com/cpiao3">Git-Alan Piao</a>)
*/
public final class Permutation {
private Permutation() {
}
public class Permutation {
/**
* Find all permutations of given array using backtracking

View File

@ -8,33 +8,32 @@ package com.thealgorithms.backtracking;
*/
public class PowerSum {
private int count = 0;
private int sum = 0;
private int count = 0, sum = 0;
public int powSum(int n, int x) {
sum(n, x, 1);
public int powSum(int N, int X) {
Sum(N, X, 1);
return count;
}
// here i is the natural number which will be raised by X and added in sum.
public void sum(int n, int x, int i) {
public void Sum(int N, int X, int i) {
// if sum is equal to N that is one of our answer and count is increased.
if (sum == n) {
if (sum == N) {
count++;
return;
} // we will be adding next natural number raised to X only if on adding it in sum the
// result is less than N.
else if (sum + power(i, x) <= n) {
sum += power(i, x);
sum(n, x, i + 1);
else if (sum + power(i, X) <= N) {
sum += power(i, X);
Sum(N, X, i + 1);
// backtracking and removing the number added last since no possible combination is
// there with it.
sum -= power(i, x);
sum -= power(i, X);
}
if (power(i, x) < n) {
if (power(i, X) < N) {
// calling the sum function with next natural number after backtracking if when it is
// raised to X is still less than X.
sum(n, x, i + 1);
Sum(N, X, i + 1);
}
}

View File

@ -1,54 +0,0 @@
package com.thealgorithms.backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* Class generates all subsequences for a given list of elements using backtracking
*/
public final class SubsequenceFinder {
private SubsequenceFinder() {
}
/**
* Find all subsequences of given list using backtracking
*
* @param sequence a list of items on the basis of which we need to generate all subsequences
* @param <T> the type of elements in the array
* @return a list of all subsequences
*/
public static <T> List<List<T>> generateAll(List<T> sequence) {
List<List<T>> allSubSequences = new ArrayList<>();
if (sequence.isEmpty()) {
allSubSequences.add(new ArrayList<>());
return allSubSequences;
}
List<T> currentSubsequence = new ArrayList<>();
backtrack(sequence, currentSubsequence, 0, allSubSequences);
return allSubSequences;
}
/**
* Iterate through each branch of states
* We know that each state has exactly two branching
* It terminates when it reaches the end of the given sequence
*
* @param sequence all elements
* @param currentSubsequence current subsequence
* @param index current index
* @param allSubSequences contains all sequences
* @param <T> the type of elements which we generate
*/
private static <T> void backtrack(List<T> sequence, List<T> currentSubsequence, final int index, List<List<T>> allSubSequences) {
assert index <= sequence.size();
if (index == sequence.size()) {
allSubSequences.add(new ArrayList<>(currentSubsequence));
return;
}
backtrack(sequence, currentSubsequence, index + 1, allSubSequences);
currentSubsequence.add(sequence.get(index));
backtrack(sequence, currentSubsequence, index + 1, allSubSequences);
currentSubsequence.removeLast();
}
}

View File

@ -51,9 +51,7 @@ public class WordSearch {
int yi = y + dy[i];
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
boolean exists = doDFS(xi, yi, nextIdx + 1);
if (exists) {
return true;
}
if (exists) return true;
}
}
visited[x][y] = false;
@ -68,9 +66,7 @@ public class WordSearch {
if (board[i][j] == word.charAt(0)) {
visited = new boolean[board.length][board[0].length];
boolean exists = doDFS(i, j, 1);
if (exists) {
return true;
}
if (exists) return true;
}
}
}

View File

@ -12,7 +12,7 @@ public final class HighestSetBit {
private HighestSetBit() {
}
public static Optional<Integer> findHighestSetBit(int num) {
public final static Optional<Integer> findHighestSetBit(int num) {
if (num < 0) {
throw new IllegalArgumentException("Input cannot be negative");
}

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class IndexOfRightMostSetBit {
private IndexOfRightMostSetBit() {
}
public class IndexOfRightMostSetBit {
public static int indexOfRightMostSetBit(int n) {
if (n == 0) {
return -1; // No set bits

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class IsEven {
private IsEven() {
}
public class IsEven {
public static boolean isEven(int number) {
return (number & 1) == 0;
}

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class IsPowerTwo {
private IsPowerTwo() {
}
public class IsPowerTwo {
public static boolean isPowerTwo(int number) {
if (number <= 0) {
return false;

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class NonRepeatingNumberFinder {
private NonRepeatingNumberFinder() {
}
public class NonRepeatingNumberFinder {
public static int findNonRepeatingNumber(int[] arr) {
int result = 0;

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi
*/
public final class NumbersDifferentSigns {
private NumbersDifferentSigns() {
}
public class NumbersDifferentSigns {
public static boolean differentSigns(int num1, int num2) {
return (num1 ^ num2) < 0;

View File

@ -5,9 +5,7 @@ package com.thealgorithms.bitmanipulation;
* @author Bama Charan Chhandogi
*/
public final class ReverseBits {
private ReverseBits() {
}
public class ReverseBits {
public static int reverseBits(int n) {
int result = 0;

View File

@ -7,9 +7,7 @@ import java.util.Scanner;
* This class is build to demonstrate the application of the AES-algorithm on a
* single 128-Bit block of data.
*/
public final class AES {
private AES() {
}
public class AES {
/**
* Precalculated values for x to the power of 2 in Rijndaels galois field.
@ -2756,8 +2754,8 @@ public final class AES {
in = input.nextLine();
BigInteger encryptionKey = new BigInteger(in, 16);
System.out.println(
"The encrypted message is: \n"
+ encrypt(plaintext, encryptionKey).toString(16)
"The encrypted message is: \n" +
encrypt(plaintext, encryptionKey).toString(16)
);
}
case 'D', 'd' -> {
@ -2772,8 +2770,8 @@ public final class AES {
in = input.nextLine();
BigInteger decryptionKey = new BigInteger(in, 16);
System.out.println(
"The deciphered message is:\n"
+ decrypt(ciphertext, decryptionKey).toString(16)
"The deciphered message is:\n" +
decrypt(ciphertext, decryptionKey).toString(16)
);
}
default -> System.out.println("** End **");

View File

@ -3,12 +3,7 @@ package com.thealgorithms.ciphers;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
/**
@ -17,9 +12,7 @@ import javax.crypto.spec.GCMParameterSpec;
* hence in the following program we display it in hexadecimal format of the
* underlying bytes.
*/
public final class AESEncryption {
private AESEncryption() {
}
public class AESEncryption {
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static Cipher aesCipher;

View File

@ -1,8 +1,6 @@
package com.thealgorithms.ciphers;
final class AffineCipher {
private AffineCipher() {
}
class AffineCipher {
// Key values of a and b
static int a = 17;
@ -27,7 +25,7 @@ final class AffineCipher {
static String decryptCipher(String cipher) {
String msg = "";
int aInv = 0;
int a_inv = 0;
int flag = 0;
// Find a^-1 (the multiplicative inverse of a
@ -38,7 +36,7 @@ final class AffineCipher {
// Check if (a*i)%26 == 1,
// then i will be the multiplicative inverse of a
if (flag == 1) {
aInv = i;
a_inv = i;
}
}
for (int i = 0; i < cipher.length(); i++) {
@ -46,7 +44,7 @@ final class AffineCipher {
{here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ') {
msg = msg + (char) (((aInv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
} else { // else simply append space character
msg += cipher.charAt(i);
}

View File

@ -11,7 +11,7 @@ package com.thealgorithms.ciphers;
public class Blowfish {
// Initializing substitution boxes
String[][] sBox = {
String[][] S = {
{
"d1310ba6",
"98dfb5ac",
@ -1047,7 +1047,7 @@ public class Blowfish {
};
// Initializing subkeys with digits of pi
String[] subKeys = {
String[] P = {
"243f6a88",
"85a308d3",
"13198a2e",
@ -1104,9 +1104,7 @@ public class Blowfish {
private String binToHex(String binary) {
long num = Long.parseUnsignedLong(binary, 2);
String hex = Long.toHexString(num);
while (hex.length() < (binary.length() / 4)) {
hex = "0" + hex;
}
while (hex.length() < (binary.length() / 4)) hex = "0" + hex;
return hex;
}
@ -1122,9 +1120,7 @@ public class Blowfish {
a = hexToBin(a);
b = hexToBin(b);
String ans = "";
for (int i = 0; i < a.length(); i++) {
ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
}
for (int i = 0; i < a.length(); i++) ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
ans = binToHex(ans);
return ans;
}
@ -1158,7 +1154,7 @@ public class Blowfish {
for (int i = 0; i < 8; i += 2) {
// column number for S-box is a 8-bit value
long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2);
a[i / 2] = sBox[i / 2][(int) col];
a[i / 2] = S[i / 2][(int) col];
}
ans = addBin(a[0], a[1]);
ans = xor(ans, a[2]);
@ -1169,9 +1165,9 @@ public class Blowfish {
// generate subkeys
private void keyGenerate(String key) {
int j = 0;
for (int i = 0; i < subKeys.length; i++) {
for (int i = 0; i < P.length; i++) {
// XOR-ing 32-bit parts of the key with initial subkeys
subKeys[i] = xor(subKeys[i], key.substring(j, j + 8));
P[i] = xor(P[i], key.substring(j, j + 8));
j = (j + 8) % key.length();
}
@ -1179,11 +1175,10 @@ public class Blowfish {
// round function
private String round(int time, String plainText) {
String left;
String right;
String left, right;
left = plainText.substring(0, 8);
right = plainText.substring(8, 16);
left = xor(left, subKeys[time]);
left = xor(left, P[time]);
// output from F function
String fOut = f(left);
@ -1206,15 +1201,13 @@ public class Blowfish {
// generating key
keyGenerate(key);
for (int i = 0; i < 16; i++) {
plainText = round(i, plainText);
}
for (int i = 0; i < 16; i++) plainText = round(i, plainText);
// postprocessing
String right = plainText.substring(0, 8);
String left = plainText.substring(8, 16);
right = xor(right, subKeys[16]);
left = xor(left, subKeys[17]);
right = xor(right, P[16]);
left = xor(left, P[17]);
return left + right;
}
@ -1230,15 +1223,13 @@ public class Blowfish {
// generating key
keyGenerate(key);
for (int i = 17; i > 1; i--) {
cipherText = round(i, cipherText);
}
for (int i = 17; i > 1; i--) cipherText = round(i, cipherText);
// postprocessing
String right = cipherText.substring(0, 8);
String left = cipherText.substring(8, 16);
right = xor(right, subKeys[1]);
left = xor(left, subKeys[0]);
right = xor(right, P[1]);
left = xor(left, P[0]);
return left + right;
}
}

View File

@ -7,9 +7,7 @@ import java.util.Objects;
*
* @author <a href="https://github.com/freitzzz">freitzzz</a>
*/
public final class ColumnarTranspositionCipher {
private ColumnarTranspositionCipher() {
}
public class ColumnarTranspositionCipher {
private static String keyword;
private static Object[][] table;

View File

@ -8,7 +8,7 @@ package com.thealgorithms.ciphers;
public class DES {
private String key;
private final String[] subKeys;
private String subKeys[];
private void sanitize(String key) {
int length = key.length();
@ -32,68 +32,66 @@ public class DES {
this.key = key;
}
// Permutation table to convert initial 64-bit key to 56 bit key
private static final int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
// Permutation table to convert initial 64 bit key to 56 bit key
private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
// Lookup table used to shift the initial key, in order to generate the subkeys
private static final int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
// Table to convert the 56 bit subkeys to 48 bit subkeys
private static final int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32};
private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32};
// Initial permutation of each 64 but message block
private static final int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
// Initial permutatation of each 64 but message block
private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
// Expansion table to convert right half of message blocks from 32 bits to 48 bits
private static final int[] EXPANSION = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1};
private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1};
// The eight substitution boxes are defined below
private static final int[][] S1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
private static final int[][] S2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
private static final int[][] S3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
private static final int[][] S4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
private static final int[][] S5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
private static final int[][] S6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
private static final int[][] S7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
private static final int[][] S8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
private static final int[][][] S = {S1, S2, S3, S4, S5, S6, S7, S8};
private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
// Permutation table, used in the Feistel function post s-box usage
static final int[] PERMUTATION = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
// Permutation table, used in the feistel function post s-box usage
static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
// Table used for final inversion of the message box after 16 rounds of Feistel Function
static final int[] IP_INVERSE = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
private String[] getSubkeys(String originalKey) {
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via pc1
int i;
int j;
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
int i, j;
for (i = 0; i < 56; i++) {
permutedKey.append(originalKey.charAt(PC1[i] - 1));
}
String[] subKeys = new String[16];
String subKeys[] = new String[16];
String initialPermutedKey = permutedKey.toString();
String c0 = initialPermutedKey.substring(0, 28);
String d0 = initialPermutedKey.substring(28);
String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28);
// We will now operate on the left and right halves of the permutedKey
for (i = 0; i < 16; i++) {
String cN = c0.substring(KEY_SHIFTS[i]) + c0.substring(0, KEY_SHIFTS[i]);
String dN = d0.substring(KEY_SHIFTS[i]) + d0.substring(0, KEY_SHIFTS[i]);
subKeys[i] = cN + dN;
c0 = cN; // Re-assign the values to create running permutation
d0 = dN;
String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]);
String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]);
subKeys[i] = Cn + Dn;
C0 = Cn; // Re-assign the values to create running permutation
D0 = Dn;
}
// Let us shrink the keys to 48 bits (well, characters here) using pc2
// Let us shrink the keys to 48 bits (well, characters here) using PC2
for (i = 0; i < 16; i++) {
String key = subKeys[i];
permutedKey.setLength(0);
@ -106,9 +104,8 @@ public class DES {
return subKeys;
}
private String xOR(String a, String b) {
int i;
int l = a.length();
private String XOR(String a, String b) {
int i, l = a.length();
StringBuilder xor = new StringBuilder();
for (i = 0; i < l; i++) {
int firstBit = a.charAt(i) - 48; // 48 is '0' in ascii
@ -119,8 +116,7 @@ public class DES {
}
private String createPaddedString(String s, int desiredLength, char pad) {
int i;
int l = s.length();
int i, l = s.length();
StringBuilder paddedString = new StringBuilder();
int diff = desiredLength - l;
for (i = 0; i < diff; i++) {
@ -141,9 +137,9 @@ public class DES {
int i;
StringBuilder expandedKey = new StringBuilder();
for (i = 0; i < 48; i++) {
expandedKey.append(messageBlock.charAt(EXPANSION[i] - 1));
expandedKey.append(messageBlock.charAt(expansion[i] - 1));
}
String mixedKey = xOR(expandedKey.toString(), key);
String mixedKey = XOR(expandedKey.toString(), key);
StringBuilder substitutedString = new StringBuilder();
// Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
@ -151,46 +147,45 @@ public class DES {
String block = mixedKey.substring(i, i + 6);
int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
String substitutedBlock = pad(Integer.toBinaryString(S[i / 6][row][col]), 4);
String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
substitutedString.append(substitutedBlock);
}
StringBuilder permutedString = new StringBuilder();
for (i = 0; i < 32; i++) {
permutedString.append(substitutedString.charAt(PERMUTATION[i] - 1));
permutedString.append(substitutedString.charAt(permutation[i] - 1));
}
return permutedString.toString();
}
private String encryptBlock(String message, String[] keys) {
private String encryptBlock(String message, String keys[]) {
StringBuilder permutedMessage = new StringBuilder();
int i;
for (i = 0; i < 64; i++) {
permutedMessage.append(message.charAt(IP[i] - 1));
}
String e0 = permutedMessage.substring(0, 32);
String f0 = permutedMessage.substring(32);
String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32);
// Iterate 16 times
for (i = 0; i < 16; i++) {
String eN = f0; // Previous Right block
String fN = xOR(e0, feistel(f0, keys[i]));
e0 = eN;
f0 = fN;
String Ln = R0; // Previous Right block
String Rn = XOR(L0, feistel(R0, keys[i]));
L0 = Ln;
R0 = Rn;
}
String combinedBlock = f0 + e0; // Reverse the 16th block
String combinedBlock = R0 + L0; // Reverse the 16th block
permutedMessage.setLength(0);
for (i = 0; i < 64; i++) {
permutedMessage.append(combinedBlock.charAt(IP_INVERSE[i] - 1));
permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1));
}
return permutedMessage.toString();
}
// To decode, we follow the same process as encoding, but with reversed keys
private String decryptBlock(String message, String[] keys) {
String[] reversedKeys = new String[keys.length];
private String decryptBlock(String message, String keys[]) {
String reversedKeys[] = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
reversedKeys[i] = keys[keys.length - i - 1];
}
@ -203,9 +198,7 @@ public class DES {
*/
public String encrypt(String message) {
StringBuilder encryptedMessage = new StringBuilder();
int l = message.length();
int i;
int j;
int l = message.length(), i, j;
if (l % 8 != 0) {
int desiredLength = (l / 8 + 1) * 8;
l = desiredLength;
@ -230,16 +223,14 @@ public class DES {
*/
public String decrypt(String message) {
StringBuilder decryptedMessage = new StringBuilder();
int l = message.length();
int i;
int j;
int l = message.length(), i, j;
if (l % 64 != 0) {
throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
}
for (i = 0; i < l; i += 64) {
String block = message.substring(i, i + 64);
String result = decryptBlock(block, subKeys);
byte[] res = new byte[8];
String result = decryptBlock(block.toString(), subKeys);
byte res[] = new byte[8];
for (j = 0; j < 64; j += 8) {
res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2);
}

View File

@ -11,9 +11,7 @@ import java.util.Scanner;
* for encryption. The cipher key and plaintext/ciphertext are user inputs.
* @author Ojasva Jain
*/
public final class HillCipher {
private HillCipher() {
}
public class HillCipher {
static Scanner userInput = new Scanner(System.in);
@ -35,7 +33,7 @@ public final class HillCipher {
validateDeterminant(keyMatrix, matrixSize);
int[][] messageVector = new int[matrixSize][1];
String cipherText = "";
String CipherText = "";
int[][] cipherMatrix = new int[matrixSize][1];
int j = 0;
while (j < message.length()) {
@ -48,8 +46,7 @@ public final class HillCipher {
System.out.println(messageVector[i][0]);
j++;
}
int x;
int i;
int x, i;
for (i = 0; i < matrixSize; i++) {
cipherMatrix[i][0] = 0;
@ -60,10 +57,10 @@ public final class HillCipher {
cipherMatrix[i][0] = cipherMatrix[i][0] % 26;
}
for (i = 0; i < matrixSize; i++) {
cipherText += (char) (cipherMatrix[i][0] + 65);
CipherText += (char) (cipherMatrix[i][0] + 65);
}
}
System.out.println("Ciphertext: " + cipherText);
System.out.println("Ciphertext: " + CipherText);
}
// Following function decrypts a message
@ -84,7 +81,7 @@ public final class HillCipher {
// solving for the required plaintext message
int[][] messageVector = new int[n][1];
String plainText = "";
String PlainText = "";
int[][] plainMatrix = new int[n][1];
int j = 0;
while (j < message.length()) {
@ -97,8 +94,7 @@ public final class HillCipher {
System.out.println(messageVector[i][0]);
j++;
}
int x;
int i;
int x, i;
for (i = 0; i < n; i++) {
plainMatrix[i][0] = 0;
@ -109,18 +105,15 @@ public final class HillCipher {
plainMatrix[i][0] = plainMatrix[i][0] % 26;
}
for (i = 0; i < n; i++) {
plainText += (char) (plainMatrix[i][0] + 65);
PlainText += (char) (plainMatrix[i][0] + 65);
}
}
System.out.println("Plaintext: " + plainText);
System.out.println("Plaintext: " + PlainText);
}
// Determinant calculator
public static int determinant(int[][] a, int n) {
int det = 0;
int sign = 1;
int p = 0;
int q = 0;
int det = 0, sign = 1, p = 0, q = 0;
if (n == 1) {
det = a[0][0];
@ -149,6 +142,7 @@ public final class HillCipher {
// Function to implement Hill Cipher
static void hillCipher(String message) {
message.toUpperCase();
System.out.println("What do you want to process from the message?");
System.out.println("Press 1: To Encrypt");
System.out.println("Press 2: To Decrypt");

View File

@ -13,11 +13,9 @@ package com.thealgorithms.ciphers;
* @author Hikmet ÇAKIR
* @since 08-07-2022+03:00
*/
public final class Polybius {
private Polybius() {
}
public class Polybius {
private static final char[][] KEY = {
private static final char[][] key = {
// 0 1 2 3 4
/* 0 */ {'A', 'B', 'C', 'D', 'E'},
/* 1 */ {'F', 'G', 'H', 'I', 'J'},
@ -28,9 +26,9 @@ public final class Polybius {
private static String findLocationByCharacter(final char character) {
final StringBuilder location = new StringBuilder();
for (int i = 0; i < KEY.length; i++) {
for (int j = 0; j < KEY[i].length; j++) {
if (character == KEY[i][j]) {
for (int i = 0; i < key.length; i++) {
for (int j = 0; j < key[i].length; j++) {
if (character == key[i][j]) {
location.append(i).append(j);
break;
}
@ -55,7 +53,7 @@ public final class Polybius {
for (int i = 0; i < chars.length; i += 2) {
int pozitionX = Character.getNumericValue(chars[i]);
int pozitionY = Character.getNumericValue(chars[i + 1]);
plaintext.append(KEY[pozitionX][pozitionY]);
plaintext.append(key[pozitionX][pozitionY]);
}
return plaintext.toString();
}

View File

@ -2,9 +2,7 @@ package com.thealgorithms.ciphers;
import java.util.Scanner;
final class ProductCipher {
private ProductCipher() {
}
class ProductCipher {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
@ -26,8 +24,8 @@ final class ProductCipher {
// Transposition encryption
String transpositionInput = substitutionOutput.toString();
int modulus = transpositionInput.length() % n;
if (modulus != 0) {
int modulus;
if ((modulus = transpositionInput.length() % n) != 0) {
modulus = n - modulus;
for (; modulus != 0; modulus--) {
@ -68,6 +66,7 @@ final class ProductCipher {
System.out.println("Plaintext: ");
System.out.println(plaintext);
sc.close();
}
}
}

View File

@ -47,7 +47,7 @@ public class RSA {
/**
* Generate a new public and private key set.
*/
public final synchronized void generateKeys(int bits) {
public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bits / 2, 100, r);
BigInteger q = new BigInteger(bits / 2, 100, r);

View File

@ -31,9 +31,7 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
}
public BitSet getNextKeyStream() {
for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) {
this.clock();
}
for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock();
BitSet result = new BitSet(KEY_STREAM_LENGTH);
for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {

View File

@ -19,19 +19,17 @@ public abstract class CompositeLFSR implements BaseLFSR {
boolean result = false;
for (var register : registers) {
result ^= register.getLastBit();
if (register.getClockBit() == majorityBit) {
register.clock();
}
if (register.getClockBit() == majorityBit) register.clock();
}
return result;
}
private boolean getMajorityBit() {
Map<Boolean, Integer> bitCount = new TreeMap<>();
bitCount.put(Boolean.FALSE, 0);
bitCount.put(Boolean.TRUE, 0);
bitCount.put(false, 0);
bitCount.put(true, 0);
registers.forEach(lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
return bitCount.get(Boolean.FALSE) <= bitCount.get(Boolean.TRUE);
return bitCount.get(false) <= bitCount.get(true);
}
}

View File

@ -7,9 +7,7 @@ package com.thealgorithms.ciphers.a5;
import java.util.BitSet;
public final class Utils {
private Utils() {
}
public class Utils {
public static boolean increment(BitSet bits, int size) {
int i = size - 1;

View File

@ -1,23 +0,0 @@
package com.thealgorithms.conversions;
public final class AffineConverter {
private final double slope;
private final double intercept;
public AffineConverter(final double inSlope, final double inIntercept) {
slope = inSlope;
intercept = inIntercept;
}
public double convert(final double inValue) {
return slope * inValue + intercept;
}
public AffineConverter invert() {
assert slope != 0.0;
return new AffineConverter(1.0 / slope, -intercept / slope);
}
public AffineConverter compose(final AffineConverter other) {
return new AffineConverter(slope * other.slope, slope * other.intercept + intercept);
}
}

View File

@ -13,9 +13,7 @@ import java.util.Scanner;
* @author Michael Rolland
* @version 2017.10.10
*/
public final class AnyBaseToAnyBase {
private AnyBaseToAnyBase() {
}
public class AnyBaseToAnyBase {
/**
* Smallest and largest base you want to accept as valid input
@ -27,8 +25,7 @@ public final class AnyBaseToAnyBase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String n;
int b1;
int b2;
int b1, b2;
while (true) {
try {
System.out.print("Enter number: ");
@ -133,8 +130,7 @@ public final class AnyBaseToAnyBase {
// Declare variables: decimal value of n,
// character of base b1, character of base b2,
// and the string that will be returned.
int decimalValue = 0;
int charB2;
int decimalValue = 0, charB2;
char charB1;
String output = "";
// Go through every character of n

View File

@ -3,50 +3,52 @@ package com.thealgorithms.conversions;
/**
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
*/
public final class AnyBaseToDecimal {
private static final int CHAR_OFFSET_FOR_DIGIT = '0';
private static final int CHAR_OFFSET_FOR_UPPERCASE = 'A' - 10;
// Driver program
public class AnyBaseToDecimal {
private AnyBaseToDecimal() {
public static void main(String[] args) {
assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2);
assert convertToDecimal("777", 8) == Integer.valueOf("777", 8);
assert convertToDecimal("999", 10) == Integer.valueOf("999", 10);
assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16);
assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36);
}
/**
* Convert any radix to a decimal number.
* Convert any radix to decimal number
*
* @param input the string to be converted
* @param radix the radix (base) of the input string
* @return the decimal equivalent of the input string
* @throws NumberFormatException if the input string or radix is invalid
* @param s the string to be convert
* @param radix the radix
* @return decimal of bits
* @throws NumberFormatException if {@code bits} or {@code radix} is invalid
*/
public static int convertToDecimal(String input, int radix) {
int result = 0;
int power = 1;
public static int convertToDecimal(String s, int radix) {
int num = 0;
int pow = 1;
for (int i = input.length() - 1; i >= 0; i--) {
int digit = valOfChar(input.charAt(i));
for (int i = s.length() - 1; i >= 0; i--) {
int digit = valOfChar(s.charAt(i));
if (digit >= radix) {
throw new NumberFormatException("For input string: " + input);
throw new NumberFormatException("For input string " + s);
}
result += digit * power;
power *= radix;
num += valOfChar(s.charAt(i)) * pow;
pow *= radix;
}
return result;
return num;
}
/**
* Convert a character to its integer value.
* Convert character to integer
*
* @param character the character to be converted
* @return the integer value represented by the character
* @throws NumberFormatException if the character is not an uppercase letter or a digit
* @param c the character
* @return represented digit of given character
* @throws NumberFormatException if {@code ch} is not UpperCase or Digit
* character.
*/
private static int valOfChar(char character) {
if (Character.isDigit(character)) {
return character - CHAR_OFFSET_FOR_DIGIT;
} else if (Character.isUpperCase(character)) {
return character - CHAR_OFFSET_FOR_UPPERCASE;
} else {
throw new NumberFormatException("invalid character:" + character);
public static int valOfChar(char c) {
if (!(Character.isUpperCase(c) || Character.isDigit(c))) {
throw new NumberFormatException("invalid character :" + c);
}
return Character.isDigit(c) ? c - '0' : c - 'A' + 10;
}
}

View File

@ -6,18 +6,14 @@ import java.util.Scanner;
// number.
// sn ,sb,db ---> ()dn . this is what we have to do .
public final class AnytoAny {
private AnytoAny() {
}
public class AnytoAny {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int sn = scn.nextInt();
int sb = scn.nextInt();
int db = scn.nextInt();
int m = 1;
int dec = 0;
int dn = 0;
int m = 1, dec = 0, dn = 0;
while (sn != 0) {
dec = dec + (sn % 10) * m;
m *= sb;

View File

@ -1,33 +1,32 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* This class converts a Binary number to a Decimal number
*/
final class BinaryToDecimal {
private static final int BINARY_BASE = 2;
class BinaryToDecimal {
private BinaryToDecimal() {
public static long binaryToDecimal(long binNum) {
long binCopy, d, s = 0, power = 0;
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
s += d * (long) Math.pow(2, power++);
binCopy /= 10;
}
return s;
}
/**
* Converts a binary number to its decimal equivalent.
* Main Method
*
* @param binaryNumber The binary number to convert.
* @return The decimal equivalent of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
* @param args Command line arguments
*/
public static long binaryToDecimal(long binaryNumber) {
long decimalValue = 0;
long power = 0;
while (binaryNumber != 0) {
long digit = binaryNumber % 10;
if (digit > 1) {
throw new IllegalArgumentException("Incorrect binary digit: " + digit);
}
decimalValue += (long) (digit * Math.pow(BINARY_BASE, power++));
binaryNumber /= 10;
}
return decimalValue;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Binary number: ");
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));
sc.close();
}
}

View File

@ -1,63 +1,57 @@
package com.thealgorithms.conversions;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*/
public final class BinaryToHexadecimal {
private static final int BITS_IN_HEX_DIGIT = 4;
private static final int BASE_BINARY = 2;
private static final int BASE_DECIMAL = 10;
private static final int HEX_START_DECIMAL = 10;
private static final int HEX_END_DECIMAL = 15;
private BinaryToHexadecimal() {
}
public class BinaryToHexadecimal {
/**
* Converts a binary number to a hexadecimal number.
* This method converts a binary number to a hexadecimal number.
*
* @param binary The binary number to convert.
* @return The hexadecimal representation of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
* @param binary The binary number
* @return The hexadecimal number
*/
public static String binToHex(int binary) {
Map<Integer, String> hexMap = initializeHexMap();
StringBuilder hex = new StringBuilder();
static String binToHex(int binary) {
// hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for
// decimal numbers 0 to 15
HashMap<Integer, String> hm = new HashMap<>();
// String to store hexadecimal code
String hex = "";
int i;
for (i = 0; i < 10; i++) {
hm.put(i, String.valueOf(i));
}
for (i = 10; i < 16; i++) {
hm.put(i, String.valueOf((char) ('A' + i - 10)));
}
int currbit;
while (binary != 0) {
int decimalValue = 0;
for (int i = 0; i < BITS_IN_HEX_DIGIT; i++) {
int currentBit = binary % BASE_DECIMAL;
if (currentBit > 1) {
throw new IllegalArgumentException("Incorrect binary digit: " + currentBit);
}
binary /= BASE_DECIMAL;
decimalValue += (int) (currentBit * Math.pow(BASE_BINARY, i));
int code4 = 0; // to store decimal equivalent of number formed by 4 decimal digits
for (i = 0; i < 4; i++) {
currbit = binary % 10;
binary = binary / 10;
code4 += currbit * (int) Math.pow(2, i);
}
hex.insert(0, hexMap.get(decimalValue));
hex = hm.get(code4) + hex;
}
return !hex.isEmpty() ? hex.toString() : "0";
return hex;
}
/**
* Initializes the hexadecimal map with decimal to hexadecimal mappings.
* Main method
*
* @return The initialized map containing mappings from decimal numbers to hexadecimal digits.
* @param args Command line arguments
*/
private static Map<Integer, String> initializeHexMap() {
Map<Integer, String> hexMap = new HashMap<>();
for (int i = 0; i < BASE_DECIMAL; i++) {
hexMap.put(i, String.valueOf(i));
}
for (int i = HEX_START_DECIMAL; i <= HEX_END_DECIMAL; i++) {
hexMap.put(i, String.valueOf((char) ('A' + i - HEX_START_DECIMAL)));
}
return hexMap;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter binary number:");
int binary = sc.nextInt();
String hex = binToHex(binary);
System.out.println("Hexadecimal Code:" + hex);
sc.close();
}
}

View File

@ -1,11 +1,25 @@
package com.thealgorithms.conversions;
public final class BinaryToOctal {
private static final int BITS_PER_OCTAL_DIGIT = 3;
private static final int BINARY_BASE = 2;
private static final int DECIMAL_BASE = 10;
import java.util.Scanner;
private BinaryToOctal() {
/**
* Converts any Binary number to an Octal Number
*
* @author Zachary Jones
*/
public class BinaryToOctal {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: ");
int b = sc.nextInt();
System.out.println("Octal equivalent: " + convertBinaryToOctal(b));
sc.close();
}
/**
@ -13,33 +27,21 @@ public final class BinaryToOctal {
*
* @param binary The binary number
* @return The octal number
* @throws IllegalArgumentException if the input is not a valid binary number
*/
public static String convertBinaryToOctal(int binary) {
if (binary == 0) {
return "0";
}
if (!String.valueOf(binary).matches("[01]+")) {
throw new IllegalArgumentException("Input is not a valid binary number.");
}
StringBuilder octal = new StringBuilder();
int currentBit;
int bitValueMultiplier = 1;
String octal = "";
int currBit = 0, j = 1;
while (binary != 0) {
int octalDigit = 0;
for (int i = 0; i < BITS_PER_OCTAL_DIGIT && binary != 0; i++) {
currentBit = binary % DECIMAL_BASE;
binary /= DECIMAL_BASE;
octalDigit += currentBit * bitValueMultiplier;
bitValueMultiplier *= BINARY_BASE;
int code3 = 0;
for (int i = 0; i < 3; i++) {
currBit = binary % 10;
binary = binary / 10;
code3 += currBit * j;
j *= 2;
}
octal.insert(0, octalDigit);
bitValueMultiplier = 1; // Reset multiplier for the next group
octal = code3 + octal;
j = 1;
}
return octal.toString();
return octal;
}
}

View File

@ -1,69 +1,67 @@
package com.thealgorithms.conversions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Class that provides methods to convert a decimal number to a string representation
* in any specified base between 2 and 36.
*
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
*/
public final class DecimalToAnyBase {
private static final int MIN_BASE = 2;
private static final int MAX_BASE = 36;
private static final char ZERO_CHAR = '0';
private static final char A_CHAR = 'A';
private static final int DIGIT_OFFSET = 10;
// Driver Program
public class DecimalToAnyBase {
private DecimalToAnyBase() {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal input below: ");
int decInput = Integer.parseInt(br.readLine());
System.out.println();
System.out.println("Enter the base below: ");
int base = Integer.parseInt(br.readLine());
System.out.println();
System.out.println("Decimal Input"
+ " is: " + decInput);
System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
br.close();
}
/**
* Converts a decimal number to a string representation in the specified base.
* For example, converting the decimal number 10 to base 2 would return "1010".
* This method produces a String value of any given input decimal in any
* base
*
* @param decimal the decimal number to convert
* @param base the base to convert to (must be between {@value #MIN_BASE} and {@value #MAX_BASE})
* @return the string representation of the number in the specified base
* @throws IllegalArgumentException if the base is out of the supported range
* @param inp Decimal of which we need the value in base in String format
* @return string format of the converted value in the given base
*/
public static String convertToAnyBase(int decimal, int base) {
if (base < MIN_BASE || base > MAX_BASE) {
throw new IllegalArgumentException("Base must be between " + MIN_BASE + " and " + MAX_BASE);
public static String convertToAnyBase(int inp, int base) {
ArrayList<Character> charArr = new ArrayList<>();
while (inp > 0) {
charArr.add(reVal(inp % base));
inp /= base;
}
if (decimal == 0) {
return String.valueOf(ZERO_CHAR);
StringBuilder str = new StringBuilder(charArr.size());
for (Character ch : charArr) {
str.append(ch);
}
List<Character> digits = new ArrayList<>();
while (decimal > 0) {
digits.add(convertToChar(decimal % base));
decimal /= base;
}
StringBuilder result = new StringBuilder(digits.size());
for (int i = digits.size() - 1; i >= 0; i--) {
result.append(digits.get(i));
}
return result.toString();
return str.reverse().toString();
}
/**
* Converts an integer value to its corresponding character in the specified base.
* This method is used to convert values from 0 to 35 into their appropriate character representation.
* For example, 0-9 are represented as '0'-'9', and 10-35 are represented as 'A'-'Z'.
* This method produces character value of the input integer and returns it
*
* @param value the integer value to convert (should be less than the base value)
* @return the character representing the value in the specified base
* @param num integer of which we need the character value of
* @return character value of input integer
*/
private static char convertToChar(int value) {
if (value >= 0 && value <= 9) {
return (char) (ZERO_CHAR + value);
public static char reVal(int num) {
if (num >= 0 && num <= 9) {
return (char) (num + '0');
} else {
return (char) (A_CHAR + value - DIGIT_OFFSET);
return (char) (num - 10 + 'A');
}
}
}

View File

@ -1,49 +1,55 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* This class provides methods to convert a decimal number to a binary number.
* This class converts a Decimal number to a Binary number
*/
final class DecimalToBinary {
private static final int BINARY_BASE = 2;
private static final int DECIMAL_MULTIPLIER = 10;
class DecimalToBinary {
private DecimalToBinary() {
/**
* Main Method
*
* @param args Command Line Arguments
*/
public static void main(String[] args) {
conventionalConversion();
bitwiseConversion();
}
/**
* Converts a decimal number to a binary number using a conventional algorithm.
* @param decimalNumber the decimal number to convert
* @return the binary representation of the decimal number
* This method converts a decimal number to a binary number using a
* conventional algorithm.
*/
public static int convertUsingConventionalAlgorithm(int decimalNumber) {
int binaryNumber = 0;
int position = 1;
while (decimalNumber > 0) {
int remainder = decimalNumber % BINARY_BASE;
binaryNumber += remainder * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber /= BINARY_BASE;
}
return binaryNumber;
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
System.out.printf("Conventional conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = n % 2;
b = b + d * (int) Math.pow(10, c++);
n /= 2;
} // converting decimal to binary
System.out.println("\tBinary number: " + b);
input.close();
}
/**
* Converts a decimal number to a binary number using a bitwise algorithm.
* @param decimalNumber the decimal number to convert
* @return the binary representation of the decimal number
* This method converts a decimal number to a binary number using a bitwise
* algorithm
*/
public static int convertUsingBitwiseAlgorithm(int decimalNumber) {
int binaryNumber = 0;
int position = 1;
while (decimalNumber > 0) {
int leastSignificantBit = decimalNumber & 1;
binaryNumber += leastSignificantBit * position;
position *= DECIMAL_MULTIPLIER;
decimalNumber >>= 1;
public static void bitwiseConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
System.out.printf("Bitwise conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = (n & 1);
b += d * (int) Math.pow(10, c++);
n >>= 1;
}
return binaryNumber;
System.out.println("\tBinary number: " + b);
input.close();
}
}

View File

@ -0,0 +1,49 @@
package com.thealgorithms.conversions;
// hex = [0 - 9] -> [A - F]
class DecimalToHexaDecimal {
private static final int sizeOfIntInHalfBytes = 8;
private static final int numberOfBitsInAHalfByte = 4;
private static final int halfByte = 0x0F;
private static final char[] hexDigits = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F',
};
// Returns the hex value of the dec entered in the parameter.
public static String decToHex(int dec) {
StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
hexBuilder.setLength(sizeOfIntInHalfBytes);
for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i) {
int j = dec & halfByte;
hexBuilder.setCharAt(i, hexDigits[j]);
dec >>= numberOfBitsInAHalfByte;
}
return hexBuilder.toString().toLowerCase();
}
// Test above function.
public static void main(String[] args) {
System.out.println("Test...");
int dec = 305445566;
String libraryDecToHex = Integer.toHexString(dec);
String decToHex = decToHex(dec);
System.out.println("Result from the library : " + libraryDecToHex);
System.out.println("Result decToHex method : " + decToHex);
}
}

View File

@ -1,42 +0,0 @@
package com.thealgorithms.conversions;
/**
* This class provides a method to convert a decimal number to a hexadecimal string.
*/
final class DecimalToHexadecimal {
private static final int SIZE_OF_INT_IN_HALF_BYTES = 8;
private static final int NUMBER_OF_BITS_IN_HALF_BYTE = 4;
private static final int HALF_BYTE_MASK = 0x0F;
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private DecimalToHexadecimal() {
}
/**
* Converts a decimal number to a hexadecimal string.
* @param decimal the decimal number to convert
* @return the hexadecimal representation of the decimal number
*/
public static String decToHex(int decimal) {
StringBuilder hexBuilder = new StringBuilder(SIZE_OF_INT_IN_HALF_BYTES);
for (int i = SIZE_OF_INT_IN_HALF_BYTES - 1; i >= 0; --i) {
int currentHalfByte = decimal & HALF_BYTE_MASK;
hexBuilder.insert(0, HEX_DIGITS[currentHalfByte]);
decimal >>= NUMBER_OF_BITS_IN_HALF_BYTE;
}
return removeLeadingZeros(hexBuilder.toString().toLowerCase());
}
private static String removeLeadingZeros(String str) {
if (str == null || str.isEmpty()) {
return str;
}
int i = 0;
while (i < str.length() && str.charAt(i) == '0') {
i++;
}
return i == str.length() ? "0" : str.substring(i);
}
}

View File

@ -1,38 +1,32 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* This class converts Decimal numbers to Octal Numbers
*/
public final class DecimalToOctal {
private static final int OCTAL_BASE = 8;
private static final int INITIAL_OCTAL_VALUE = 0;
private static final int INITIAL_PLACE_VALUE = 1;
private DecimalToOctal() {
}
public class DecimalToOctal {
/**
* Converts a decimal number to its octal equivalent.
* Main Method
*
* @param decimal The decimal number to convert.
* @return The octal equivalent as an integer.
* @throws IllegalArgumentException if the decimal number is negative.
* @param args Command line Arguments
*/
public static int convertToOctal(int decimal) {
if (decimal < 0) {
throw new IllegalArgumentException("Decimal number cannot be negative.");
// enter in a decimal value to get Octal output
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k, d, s = 0, c = 0;
System.out.print("Decimal number: ");
n = sc.nextInt();
k = n;
while (k != 0) {
d = k % 8;
s += d * (int) Math.pow(10, c++);
k /= 8;
}
int octal = INITIAL_OCTAL_VALUE;
int placeValue = INITIAL_PLACE_VALUE;
while (decimal != 0) {
int remainder = decimal % OCTAL_BASE;
octal += remainder * placeValue;
decimal /= OCTAL_BASE;
placeValue *= 10;
}
return octal;
System.out.println("Octal equivalent:" + s);
sc.close();
}
}

View File

@ -1,62 +1,72 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* Converts any Hexadecimal Number to Octal
*
* @author Tanmay Joshi
*/
public final class HexToOct {
private HexToOct() {
}
public class HexToOct {
/**
* Converts a Hexadecimal number to a Decimal number.
* This method converts a Hexadecimal number to a decimal number
*
* @param hex The Hexadecimal number as a String.
* @return The Decimal equivalent as an integer.
* @param s The Hexadecimal Number
* @return The Decimal number
*/
public static int hexToDecimal(String hex) {
String hexDigits = "0123456789ABCDEF";
hex = hex.toUpperCase();
int decimalValue = 0;
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
int digitValue = hexDigits.indexOf(hexChar);
decimalValue = 16 * decimalValue + digitValue;
public static int hex2decimal(String s) {
String str = "0123456789ABCDEF";
s = s.toUpperCase();
int val = 0;
for (int i = 0; i < s.length(); i++) {
char a = s.charAt(i);
int n = str.indexOf(a);
val = 16 * val + n;
}
return decimalValue;
return val;
}
/**
* Converts a Decimal number to an Octal number.
* This method converts a Decimal number to a octal number
*
* @param decimal The Decimal number as an integer.
* @return The Octal equivalent as an integer.
* @param q The Decimal Number
* @return The Octal number
*/
public static int decimalToOctal(int decimal) {
int octalValue = 0;
int placeValue = 1;
while (decimal > 0) {
int remainder = decimal % 8;
octalValue += remainder * placeValue;
decimal /= 8;
placeValue *= 10;
public static int decimal2octal(int q) {
int now;
int i = 1;
int octnum = 0;
while (q > 0) {
now = q % 8;
octnum = (now * (int) (Math.pow(10, i))) + octnum;
q /= 8;
i++;
}
return octalValue;
octnum /= 10;
return octnum;
}
/**
* Converts a Hexadecimal number to an Octal number.
* Main method that gets the hex input from user and converts it into octal.
*
* @param hex The Hexadecimal number as a String.
* @return The Octal equivalent as an integer.
* @param args arguments
*/
public static int hexToOctal(String hex) {
int decimalValue = hexToDecimal(hex);
return decimalToOctal(decimalValue);
public static void main(String[] args) {
String hexadecnum;
int decnum, octalnum;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum
// convert decimal to octal
octalnum = decimal2octal(decnum);
System.out.println("Number in octal: " + octalnum);
scan.close();
}
}

View File

@ -2,6 +2,9 @@ package com.thealgorithms.conversions;
// Hex [0-9],[A-F] -> Binary [0,1]
public class HexaDecimalToBinary {
private final int LONG_BITS = 8;
public String convert(String numHex) {
// String a HexaDecimal:
int conHex = Integer.parseInt(numHex, 16);
@ -12,8 +15,7 @@ public class HexaDecimalToBinary {
}
public String completeDigits(String binNum) {
final int longBits = 8;
for (int i = binNum.length(); i < longBits; i++) {
for (int i = binNum.length(); i < LONG_BITS; i++) {
binNum = "0" + binNum;
}
return binNum;

View File

@ -2,9 +2,7 @@ package com.thealgorithms.conversions;
import java.util.Scanner;
public final class HexaDecimalToDecimal {
private HexaDecimalToDecimal() {
}
public class HexaDecimalToDecimal {
// convert hexadecimal to decimal
public static int getHexaToDec(String hex) {
@ -20,20 +18,20 @@ public final class HexaDecimalToDecimal {
// Main method gets the hexadecimal input from user and converts it into Decimal output.
public static void main(String[] args) {
String hexaInput;
int decOutput;
String hexa_Input;
int dec_output;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexaInput = scan.nextLine();
hexa_Input = scan.nextLine();
// convert hexadecimal to decimal
decOutput = getHexaToDec(hexaInput);
dec_output = getHexaToDec(hexa_Input);
/*
Pass the string to the getHexaToDec function
and it returns the decimal form in the variable decOutput.
and it returns the decimal form in the variable dec_output.
*/
System.out.println("Number in Decimal: " + decOutput);
System.out.println("Number in Decimal: " + dec_output);
scan.close();
}
}

View File

@ -7,11 +7,9 @@ package com.thealgorithms.conversions;
* ('I', 1); ('IV',4); ('V', 5); ('IX',9); ('X', 10); ('XL',40); ('L', 50);
* ('XC',90); ('C', 100); ('D', 500); ('M', 1000);
*/
public final class IntegerToRoman {
private IntegerToRoman() {
}
public class IntegerToRoman {
private static final int[] ALL_ROMAN_NUMBERS_IN_ARABIC = new int[] {
private static final int[] allArabianRomanNumbers = new int[] {
1000,
900,
500,
@ -26,7 +24,7 @@ public final class IntegerToRoman {
4,
1,
};
private static final String[] ALL_ROMAN_NUMBERS = new String[] {
private static final String[] allRomanNumbers = new String[] {
"M",
"CM",
"D",
@ -50,13 +48,13 @@ public final class IntegerToRoman {
StringBuilder builder = new StringBuilder();
for (int a = 0; a < ALL_ROMAN_NUMBERS_IN_ARABIC.length; a++) {
int times = num / ALL_ROMAN_NUMBERS_IN_ARABIC[a];
for (int a = 0; a < allArabianRomanNumbers.length; a++) {
int times = num / allArabianRomanNumbers[a];
for (int b = 0; b < times; b++) {
builder.append(ALL_ROMAN_NUMBERS[a]);
builder.append(allRomanNumbers[a]);
}
num -= times * ALL_ROMAN_NUMBERS_IN_ARABIC[a];
num -= times * allArabianRomanNumbers[a];
}
return builder.toString();

View File

@ -6,9 +6,7 @@ package com.thealgorithms.conversions;
* @author Bama Charan Chhandogi
*/
public final class OctalToBinary {
private OctalToBinary() {
}
public class OctalToBinary {
public static long convertOctalToBinary(int octalNumber) {
long binaryNumber = 0;
int digitPosition = 1;

View File

@ -1,42 +1,45 @@
package com.thealgorithms.conversions;
/**
* Class for converting an octal number to a decimal number. Octal numbers are based on 8, using digits from 0 to 7.
*
*/
public final class OctalToDecimal {
private static final int OCTAL_BASE = 8;
import java.util.Scanner;
private OctalToDecimal() {
/**
* Converts any Octal Number to a Decimal Number
*
* @author Zachary Jones
*/
public class OctalToDecimal {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Octal Input: ");
String inputOctal = sc.nextLine();
int result = convertOctalToDecimal(inputOctal);
if (result != -1) {
System.out.println("Result convertOctalToDecimal : " + result);
}
sc.close();
}
/**
* Converts a given octal number (as a string) to its decimal representation.
* If the input is not a valid octal number (i.e., contains characters other than 0-7),
* the method throws an IllegalArgumentException.
* This method converts an octal number to a decimal number.
*
* @param inputOctal The octal number as a string
* @return The decimal equivalent of the octal number
* @throws IllegalArgumentException if the input is not a valid octal number
* @param inputOctal The octal number
* @return The decimal number
*/
public static int convertOctalToDecimal(String inputOctal) {
if (inputOctal == null || inputOctal.isEmpty()) {
throw new IllegalArgumentException("Input cannot be null or empty");
try {
// Actual conversion of Octal to Decimal:
return Integer.parseInt(inputOctal, 8);
} catch (NumberFormatException ne) {
// Printing a warning message if the input is not a valid octal
// number:
System.out.println("Invalid Input, Expecting octal number 0-7");
return -1;
}
int decimalValue = 0;
for (int i = 0; i < inputOctal.length(); i++) {
char currentChar = inputOctal.charAt(i);
if (currentChar < '0' || currentChar > '7') {
throw new IllegalArgumentException("Incorrect input: Expecting an octal number (digits 0-7)");
}
int currentDigit = currentChar - '0';
decimalValue = decimalValue * OCTAL_BASE + currentDigit;
}
return decimalValue;
}
}

View File

@ -1,61 +1,63 @@
package com.thealgorithms.conversions;
import java.util.Scanner;
/**
* Class for converting an Octal number to its Hexadecimal equivalent.
* Converts any Octal Number to HexaDecimal
*
* @author Tanmay Joshi
*/
public final class OctalToHexadecimal {
private static final int OCTAL_BASE = 8;
private static final int HEX_BASE = 16;
private static final String HEX_DIGITS = "0123456789ABCDEF";
public class OctalToHexadecimal {
private OctalToHexadecimal() {
/**
* This method converts a Octal number to a decimal number
*
* @param s The Octal Number
* @return The Decimal number
*/
public static int octToDec(String s) {
int i = 0;
for (int j = 0; j < s.length(); j++) {
char num = s.charAt(j);
num -= '0';
i *= 8;
i += num;
}
return i;
}
/**
* Converts an Octal number (as a string) to its Decimal equivalent.
* This method converts a Decimal number to a Hexadecimal number
*
* @param octalNumber The Octal number as a string
* @return The Decimal equivalent of the Octal number
* @throws IllegalArgumentException if the input contains invalid octal digits
* @param d The Decimal Number
* @return The Hexadecimal number
*/
public static int octalToDecimal(String octalNumber) {
if (octalNumber == null || octalNumber.isEmpty()) {
throw new IllegalArgumentException("Input cannot be null or empty");
}
int decimalValue = 0;
for (int i = 0; i < octalNumber.length(); i++) {
char currentChar = octalNumber.charAt(i);
if (currentChar < '0' || currentChar > '7') {
throw new IllegalArgumentException("Incorrect octal digit: " + currentChar);
}
int currentDigit = currentChar - '0';
decimalValue = decimalValue * OCTAL_BASE + currentDigit;
}
return decimalValue;
}
/**
* Converts a Decimal number to its Hexadecimal equivalent.
*
* @param decimalNumber The Decimal number
* @return The Hexadecimal equivalent of the Decimal number
*/
public static String decimalToHexadecimal(int decimalNumber) {
if (decimalNumber == 0) {
public static String decimalToHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0) {
return "0";
}
StringBuilder hexValue = new StringBuilder();
while (decimalNumber > 0) {
int digit = decimalNumber % HEX_BASE;
hexValue.insert(0, HEX_DIGITS.charAt(digit));
decimalNumber /= HEX_BASE;
String hex = "";
while (d > 0) {
int digit = d % 16;
hex = digits.charAt(digit) + hex;
d = d / 16;
}
return hex;
}
return hexValue.toString();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Octal number: ");
// Take octal number as input from user in a string
String oct = input.next();
// Pass the octal number to function and get converted decimal form
int decimal = octToDec(oct);
// Pass the decimal number to function and get converted Hex form of the number
String hex = decimalToHex(decimal);
System.out.println("The Hexadecimal equivalant is: " + hex);
input.close();
}
}

View File

@ -13,9 +13,7 @@ import java.util.Arrays;
* (description adapted from <a href="https://en.wikipedia.org/wiki/RGB_color_model">[1]</a> and
* <a href="https://en.wikipedia.org/wiki/HSL_and_HSV">[2]</a>).
*/
public final class RgbHsvConversion {
private RgbHsvConversion() {
}
public class RgbHsvConversion {
public static void main(String[] args) {
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html

View File

@ -1,13 +1,12 @@
package com.thealgorithms.conversions;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public final class RomanToInteger {
private RomanToInteger() {
}
public class RomanToInteger {
private static final Map<Character, Integer> map = new HashMap<>() {
private static final long serialVersionUID = 87605733047260530L;
private static final Map<Character, Integer> ROMAN_TO_INT = new HashMap<>() {
{
put('I', 1);
put('V', 5);
@ -24,31 +23,31 @@ public final class RomanToInteger {
/**
* This function convert Roman number into Integer
*
* @param a Roman number string
* @param A Roman number string
* @return integer
*/
public static int romanToInt(String a) {
a = a.toUpperCase();
public static int romanToInt(String A) {
A = A.toUpperCase();
char prev = ' ';
int sum = 0;
int newPrev = 0;
for (int i = a.length() - 1; i >= 0; i--) {
char c = a.charAt(i);
for (int i = A.length() - 1; i >= 0; i--) {
char c = A.charAt(i);
if (prev != ' ') {
// checking current Number greater than previous or not
newPrev = ROMAN_TO_INT.get(prev) > newPrev ? ROMAN_TO_INT.get(prev) : newPrev;
// checking current Number greater then previous or not
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
}
int currentNum = ROMAN_TO_INT.get(c);
int currentNum = map.get(c);
// if current number greater than prev max previous then add
// if current number greater then prev max previous then add
if (currentNum >= newPrev) {
sum += currentNum;
} else {
// subtract upcoming number until upcoming number not greater than prev max
// subtract upcoming number until upcoming number not greater then prev max
sum -= currentNum;
}

View File

@ -7,9 +7,7 @@ import java.util.Scanner;
*
* @author Özgün Gökşenli
*/
public final class TurkishToLatinConversion {
private TurkishToLatinConversion() {
}
public class TurkishToLatinConversion {
/**
* Main method

View File

@ -1,14 +0,0 @@
package com.thealgorithms.conversions;
import static java.util.Map.entry;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
public final class UnitConversions {
private UnitConversions() {
}
public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)), entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)),
entry(Pair.of("Réaumur", "Celsius"), new AffineConverter(5.0 / 4.0, 0.0)), entry(Pair.of("Delisle", "Celsius"), new AffineConverter(-2.0 / 3.0, 100.0)), entry(Pair.of("Rankine", "Kelvin"), new AffineConverter(5.0 / 9.0, 0.0))));
}

View File

@ -1,86 +0,0 @@
package com.thealgorithms.conversions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.Pair;
public final class UnitsConverter {
private final Map<Pair<String, String>, AffineConverter> conversions;
private final Set<String> units;
private static void putIfNeeded(Map<Pair<String, String>, AffineConverter> conversions, final String inputUnit, final String outputUnit, final AffineConverter converter) {
if (!inputUnit.equals(outputUnit)) {
final var key = Pair.of(inputUnit, outputUnit);
conversions.putIfAbsent(key, converter);
}
}
private static Map<Pair<String, String>, AffineConverter> addInversions(final Map<Pair<String, String>, AffineConverter> knownConversions) {
Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>();
for (final var curConversion : knownConversions.entrySet()) {
final var inputUnit = curConversion.getKey().getKey();
final var outputUnit = curConversion.getKey().getValue();
putIfNeeded(res, inputUnit, outputUnit, curConversion.getValue());
putIfNeeded(res, outputUnit, inputUnit, curConversion.getValue().invert());
}
return res;
}
private static Map<Pair<String, String>, AffineConverter> addCompositions(final Map<Pair<String, String>, AffineConverter> knownConversions) {
Map<Pair<String, String>, AffineConverter> res = new HashMap<Pair<String, String>, AffineConverter>();
for (final var first : knownConversions.entrySet()) {
final var firstKey = first.getKey();
putIfNeeded(res, firstKey.getKey(), firstKey.getValue(), first.getValue());
for (final var second : knownConversions.entrySet()) {
final var secondKey = second.getKey();
if (firstKey.getValue().equals(secondKey.getKey())) {
final var newConversion = second.getValue().compose(first.getValue());
putIfNeeded(res, firstKey.getKey(), secondKey.getValue(), newConversion);
}
}
}
return res;
}
private static Map<Pair<String, String>, AffineConverter> addAll(final Map<Pair<String, String>, AffineConverter> knownConversions) {
final var res = addInversions(knownConversions);
return addCompositions(res);
}
private static Map<Pair<String, String>, AffineConverter> computeAllConversions(final Map<Pair<String, String>, AffineConverter> basicConversions) {
var tmp = basicConversions;
var res = addAll(tmp);
while (res.size() != tmp.size()) {
tmp = res;
res = addAll(tmp);
}
return res;
}
private static Set<String> extractUnits(final Map<Pair<String, String>, AffineConverter> conversions) {
Set<String> res = new HashSet<>();
for (final var conversion : conversions.entrySet()) {
res.add(conversion.getKey().getKey());
}
return res;
}
public UnitsConverter(final Map<Pair<String, String>, AffineConverter> basicConversions) {
conversions = computeAllConversions(basicConversions);
units = extractUnits(conversions);
}
public double convert(final String inputUnit, final String outputUnit, final double value) {
if (inputUnit.equals(outputUnit)) {
throw new IllegalArgumentException("inputUnit must be different from outputUnit.");
}
final var conversionKey = Pair.of(inputUnit, outputUnit);
return conversions.get(conversionKey).convert(value);
}
public Set<String> availableUnits() {
return units;
}
}

View File

@ -4,23 +4,23 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A collection that allows adding and iterating over elements but does not support element removal.
* Collection which does not allow removing elements (only collect and iterate)
*
* @param <E> the type of elements in this bag
* @param <Element> - the generic type of an element in this bag
*/
public class Bag<E> implements Iterable<E> {
public class Bag<Element> implements Iterable<Element> {
private Node<E> firstElement; // First element in the bag
private int size; // Number of elements in the bag
private Node<Element> firstElement; // first element of the bag
private int size; // size of bag
// Node class representing each element in the bag
private static final class Node<E> {
private E content;
private Node<E> nextElement;
private static class Node<Element> {
private Element content;
private Node<Element> nextElement;
}
/**
* Constructs an empty bag.
* Create an empty bag
*/
public Bag() {
firstElement = null;
@ -28,17 +28,13 @@ public class Bag<E> implements Iterable<E> {
}
/**
* Checks if the bag is empty.
*
* @return true if the bag is empty, false otherwise
* @return true if this bag is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
return firstElement == null;
}
/**
* Returns the number of elements in the bag.
*
* @return the number of elements
*/
public int size() {
@ -46,26 +42,24 @@ public class Bag<E> implements Iterable<E> {
}
/**
* Adds an element to the bag.
*
* @param element the element to add
* @param element - the element to add
*/
public void add(E element) {
Node<E> newNode = new Node<>();
newNode.content = element;
newNode.nextElement = firstElement;
firstElement = newNode;
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
firstElement.content = element;
firstElement.nextElement = oldfirst;
size++;
}
/**
* Checks if the bag contains a specific element.
* Checks if the bag contains a specific element
*
* @param element the element to check for
* @return true if the bag contains the element, false otherwise
* @param element which you want to look for
* @return true if bag contains element, otherwise false
*/
public boolean contains(E element) {
for (E value : this) {
public boolean contains(Element element) {
for (Element value : this) {
if (value.equals(element)) {
return true;
}
@ -74,37 +68,61 @@ public class Bag<E> implements Iterable<E> {
}
/**
* Returns an iterator over the elements in this bag.
*
* @return an iterator that iterates over the elements in the bag
* @return an iterator that iterates over the elements in this bag in
* arbitrary order
*/
@Override
public Iterator<E> iterator() {
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
// Private class for iterating over elements
private static class ListIterator<E> implements Iterator<E> {
@SuppressWarnings("hiding")
private class ListIterator<Element> implements Iterator<Element> {
private Node<E> currentElement;
private Node<Element> currentElement;
ListIterator(Node<E> firstElement) {
this.currentElement = firstElement;
public ListIterator(Node<Element> firstElement) {
currentElement = firstElement;
}
@Override
public boolean hasNext() {
return currentElement != null;
}
/**
* remove is not allowed in a bag
*/
@Override
public E next() {
public void remove() {
throw new UnsupportedOperationException();
}
public Element next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E element = currentElement.content;
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
/**
* main-method for testing
*/
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
bag.add("1");
bag.add("1");
bag.add("2");
System.out.println("size of bag = " + bag.size());
for (String s : bag) {
System.out.println(s);
}
System.out.println(bag.contains(null));
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
}

View File

@ -2,61 +2,35 @@ package com.thealgorithms.datastructures.bloomfilter;
import java.util.BitSet;
/**
* A generic BloomFilter implementation for probabilistic membership checking.
*
* @param <T> The type of elements to be stored in the Bloom filter.
*/
public class BloomFilter<T> {
private final int numberOfHashFunctions;
private final BitSet bitArray;
private final Hash<T>[] hashFunctions;
private int numberOfHashFunctions;
private BitSet bitArray;
private Hash<T>[] hashFunctions;
/**
* Constructs a BloomFilter with a specified number of hash functions and bit array size.
*
* @param numberOfHashFunctions the number of hash functions to use
* @param bitArraySize the size of the bit array
*/
@SuppressWarnings("unchecked")
public BloomFilter(int numberOfHashFunctions, int bitArraySize) {
public BloomFilter(int numberOfHashFunctions, int n) {
this.numberOfHashFunctions = numberOfHashFunctions;
this.bitArray = new BitSet(bitArraySize);
this.hashFunctions = new Hash[numberOfHashFunctions];
initializeHashFunctions();
hashFunctions = new Hash[numberOfHashFunctions];
bitArray = new BitSet(n);
insertHash();
}
/**
* Initializes the hash functions with unique indices.
*/
private void initializeHashFunctions() {
private void insertHash() {
for (int i = 0; i < numberOfHashFunctions; i++) {
hashFunctions[i] = new Hash<>(i);
hashFunctions[i] = new Hash(i);
}
}
/**
* Inserts an element into the Bloom filter.
*
* @param key the element to insert
*/
public void insert(T key) {
for (Hash<T> hash : hashFunctions) {
int position = Math.abs(hash.compute(key) % bitArray.size());
int position = hash.compute(key) % bitArray.size();
bitArray.set(position);
}
}
/**
* Checks if an element might be in the Bloom filter.
*
* @param key the element to check
* @return {@code true} if the element might be in the Bloom filter, {@code false} if it is definitely not
*/
public boolean contains(T key) {
for (Hash<T> hash : hashFunctions) {
int position = Math.abs(hash.compute(key) % bitArray.size());
int position = hash.compute(key) % bitArray.size();
if (!bitArray.get(position)) {
return false;
}
@ -64,46 +38,24 @@ public class BloomFilter<T> {
return true;
}
/**
* Inner class representing a hash function used by the Bloom filter.
*
* @param <T> The type of elements to be hashed.
*/
private static class Hash<T> {
private class Hash<T> {
private final int index;
int index;
/**
* Constructs a Hash function with a specified index.
*
* @param index the index of this hash function
*/
Hash(int index) {
public Hash(int index) {
this.index = index;
}
/**
* Computes the hash of the given key.
*
* @param key the element to hash
* @return the hash value
*/
public int compute(T key) {
return index * asciiString(String.valueOf(key));
}
/**
* Computes the ASCII value sum of the characters in a string.
*
* @param word the string to compute
* @return the sum of ASCII values of the characters
*/
private int asciiString(String word) {
int sum = 0;
for (char c : word.toCharArray()) {
sum += c;
int number = 0;
for (int i = 0; i < word.length(); i++) {
number += word.charAt(i);
}
return sum;
return number;
}
}
}

View File

@ -24,9 +24,7 @@ public class CircularBuffer<Item> {
}
public Item get() {
if (isEmpty()) {
return null;
}
if (isEmpty()) return null;
Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet();
@ -34,9 +32,7 @@ public class CircularBuffer<Item> {
}
public boolean put(Item item) {
if (isFull()) {
return false;
}
if (isFull()) return false;
buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet();
@ -47,15 +43,13 @@ public class CircularBuffer<Item> {
private int pointer;
private final int max;
CircularPointer(int pointer, int max) {
public CircularPointer(int pointer, int max) {
this.pointer = pointer;
this.max = max;
}
public int getAndIncrement() {
if (pointer == max) {
pointer = 0;
}
if (pointer == max) pointer = 0;
int tmp = pointer;
pointer++;
return tmp;

View File

@ -10,13 +10,14 @@ import java.util.Map;
public class LFUCache<K, V> {
private class Node {
private final K key;
private K key;
private V value;
private int frequency;
private Node previous;
private Node next;
Node(K key, V value, int frequency) {
public Node(K key, V value, int frequency) {
this.key = key;
this.value = value;
this.frequency = frequency;
@ -25,67 +26,67 @@ public class LFUCache<K, V> {
private Node head;
private Node tail;
private final Map<K, Node> cache;
private final int capacity;
private Map<K, Node> map = null;
private Integer capacity;
private static final int DEFAULT_CAPACITY = 100;
public LFUCache() {
this(DEFAULT_CAPACITY);
this.capacity = DEFAULT_CAPACITY;
}
public LFUCache(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Capacity must be greater than zero.");
}
public LFUCache(Integer capacity) {
this.capacity = capacity;
this.cache = new HashMap<>();
this.map = new HashMap<>();
}
/**
* Retrieves the value for the given key from the cache. Increases the frequency of the node.
* This method returns value present in the cache corresponding to the key passed as parameter
*
* @param key The key to look up.
* @return The value associated with the key, or null if the key is not present.
* @param <K> key for which value is to be retrieved
* @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is
* not present in the cache
*/
public V get(K key) {
Node node = cache.get(key);
if (node == null) {
if (this.map.get(key) == null) {
return null;
}
Node node = map.get(key);
removeNode(node);
node.frequency += 1;
addNodeWithUpdatedFrequency(node);
return node.value;
}
/**
* Adds or updates a key-value pair in the cache. If the cache is full, the least frequently used item is evicted.
* This method stores <K> key and <V> value in the cache
*
* @param key The key to insert or update.
* @param value The value to insert or update.
* @param <K> key which is to be stored in the cache
* @param <V> value which is to be stored in the cache
*/
public void put(K key, V value) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
node.frequency += 1;
removeNode(node);
addNodeWithUpdatedFrequency(node);
} else {
if (cache.size() >= capacity) {
cache.remove(this.head.key);
if (map.size() >= capacity) {
map.remove(this.head.key);
removeNode(head);
}
Node node = new Node(key, value, 1);
addNodeWithUpdatedFrequency(node);
cache.put(key, node);
map.put(key, node);
}
}
/**
* Adds a node to the linked list in the correct position based on its frequency.
* This method stores the node in the cache with updated frequency
*
* @param node The node to add.
* @param Node node which is to be updated in the cache
*/
private void addNodeWithUpdatedFrequency(Node node) {
if (tail != null && head != null) {
@ -122,9 +123,9 @@ public class LFUCache<K, V> {
}
/**
* Removes a node from the linked list.
* This method removes node from the cache
*
* @param node The node to remove.
* @param Node node which is to be removed in the cache
*/
private void removeNode(Node node) {
if (node.previous != null) {

View File

@ -126,10 +126,10 @@ public class LRUCache<K, V> {
private I key;
private J value;
Entry() {
public Entry() {
}
Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;

View File

@ -124,10 +124,10 @@ public class MRUCache<K, V> {
private I key;
private J value;
Entry() {
public Entry() {
}
Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;

View File

@ -17,7 +17,7 @@ import java.util.Map;
*/
class GCounter {
private final Map<Integer, Integer> counterMap;
private final Map<Integer, Integer> P;
private final int myId;
private final int n;
@ -26,13 +26,13 @@ class GCounter {
*
* @param n The number of nodes in the cluster.
*/
GCounter(int myId, int n) {
public GCounter(int myId, int n) {
this.myId = myId;
this.n = n;
this.counterMap = new HashMap<>();
this.P = new HashMap<>();
for (int i = 0; i < n; i++) {
counterMap.put(i, 0);
P.put(i, 0);
}
}
@ -40,7 +40,7 @@ class GCounter {
* Increments the counter for the current node.
*/
public void increment() {
counterMap.put(myId, counterMap.get(myId) + 1);
P.put(myId, P.get(myId) + 1);
}
/**
@ -50,7 +50,7 @@ class GCounter {
*/
public int value() {
int sum = 0;
for (int v : counterMap.values()) {
for (int v : P.values()) {
sum += v;
}
return sum;
@ -64,7 +64,7 @@ class GCounter {
*/
public boolean compare(GCounter other) {
for (int i = 0; i < n; i++) {
if (this.counterMap.get(i) > other.counterMap.get(i)) {
if (this.P.get(i) > other.P.get(i)) {
return false;
}
}
@ -78,7 +78,7 @@ class GCounter {
*/
public void merge(GCounter other) {
for (int i = 0; i < n; i++) {
this.counterMap.put(i, Math.max(this.counterMap.get(i), other.counterMap.get(i)));
this.P.put(i, Math.max(this.P.get(i), other.P.get(i)));
}
}
}

View File

@ -26,7 +26,7 @@ class Element {
* @param timestamp The timestamp associated with the element.
* @param bias The bias of the element (ADDS or REMOVALS).
*/
Element(String key, int timestamp, Bias bias) {
public Element(String key, int timestamp, Bias bias) {
this.key = key;
this.timestamp = timestamp;
this.bias = bias;
@ -49,7 +49,7 @@ class LWWElementSet {
/**
* Constructs an empty LWWElementSet.
*/
LWWElementSet() {
public LWWElementSet() {
this.addSet = new HashMap<>();
this.removeSet = new HashMap<>();
}
@ -124,14 +124,14 @@ class LWWElementSet {
* @return True if the first element's timestamp is greater or the bias is ADDS and timestamps are equal.
*/
public boolean compareTimestamps(Element e, Element other) {
if (e.bias != other.bias) {
if (!e.bias.equals(other.bias)) {
throw new IllegalArgumentException("Invalid bias value");
}
Bias bias = e.bias;
int timestampComparison = Integer.compare(e.timestamp, other.timestamp);
if (timestampComparison == 0) {
return bias != Bias.ADDS;
return !bias.equals(Bias.ADDS);
}
return timestampComparison < 0;
}

View File

@ -17,8 +17,8 @@ import java.util.Map;
*/
class PNCounter {
private final Map<Integer, Integer> pCounter;
private final Map<Integer, Integer> nCounter;
private final Map<Integer, Integer> P;
private final Map<Integer, Integer> N;
private final int myId;
private final int n;
@ -28,15 +28,15 @@ class PNCounter {
* @param myId The identifier of the current node.
* @param n The number of nodes in the cluster.
*/
PNCounter(int myId, int n) {
public PNCounter(int myId, int n) {
this.myId = myId;
this.n = n;
this.pCounter = new HashMap<>();
this.nCounter = new HashMap<>();
this.P = new HashMap<>();
this.N = new HashMap<>();
for (int i = 0; i < n; i++) {
pCounter.put(i, 0);
nCounter.put(i, 0);
P.put(i, 0);
N.put(i, 0);
}
}
@ -44,14 +44,14 @@ class PNCounter {
* Increments the increment counter for the current node.
*/
public void increment() {
pCounter.put(myId, pCounter.get(myId) + 1);
P.put(myId, P.get(myId) + 1);
}
/**
* Increments the decrement counter for the current node.
*/
public void decrement() {
nCounter.put(myId, nCounter.get(myId) + 1);
N.put(myId, N.get(myId) + 1);
}
/**
@ -60,8 +60,8 @@ class PNCounter {
* @return The total value of the counter.
*/
public int value() {
int sumP = pCounter.values().stream().mapToInt(Integer::intValue).sum();
int sumN = nCounter.values().stream().mapToInt(Integer::intValue).sum();
int sumP = P.values().stream().mapToInt(Integer::intValue).sum();
int sumN = N.values().stream().mapToInt(Integer::intValue).sum();
return sumP - sumN;
}
@ -76,7 +76,7 @@ class PNCounter {
throw new IllegalArgumentException("Cannot compare PN-Counters with different number of nodes");
}
for (int i = 0; i < n; i++) {
if (this.pCounter.get(i) > other.pCounter.get(i) && this.nCounter.get(i) > other.nCounter.get(i)) {
if (this.P.get(i) > other.P.get(i) && this.N.get(i) > other.N.get(i)) {
return false;
}
}
@ -93,8 +93,8 @@ class PNCounter {
throw new IllegalArgumentException("Cannot merge PN-Counters with different number of nodes");
}
for (int i = 0; i < n; i++) {
this.pCounter.put(i, Math.max(this.pCounter.get(i), other.pCounter.get(i)));
this.nCounter.put(i, Math.max(this.nCounter.get(i), other.nCounter.get(i)));
this.P.put(i, Math.max(this.P.get(i), other.P.get(i)));
this.N.put(i, Math.max(this.N.get(i), other.N.get(i)));
}
}
}

View File

@ -1,204 +1,222 @@
package com.thealgorithms.datastructures.dynamicarray;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* This class implements a dynamic array.
* This class implements a dynamic array
*
* @param <E> the type that each index of the array will hold
*/
public class DynamicArray<E> implements Iterable<E> {
private static final int DEFAULT_CAPACITY = 16;
private int capacity;
private int size;
private int modCount; // Tracks structural modifications for the iterator
private Object[] elements;
/**
* Constructor with initial capacity.
* constructor
*
* @param capacity the starting length of the desired array
* @throws IllegalArgumentException if the specified capacity is negative
*/
public DynamicArray(final int capacity) {
if (capacity < 0) {
throw new IllegalArgumentException("Capacity cannot be negative.");
}
this.size = 0;
this.modCount = 0;
this.elements = new Object[capacity];
this.capacity = capacity;
this.elements = new Object[this.capacity];
}
/**
* No-args constructor with default capacity.
* No-args constructor
*/
public DynamicArray() {
this(DEFAULT_CAPACITY);
}
/**
* Adds an element to the array. If full, creates a new array with double the size.
* Adds an element to the array If full, creates a copy array twice the size
* of the current one
*
* @param element the element to be added to the array
* @param element the element of type <E> to be added to the array
*/
public void add(final E element) {
ensureCapacity(size + 1);
elements[size++] = element;
modCount++; // Increment modification count
if (this.size == this.elements.length) {
this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
}
this.elements[this.size] = element;
size++;
}
/**
* Places an element at the desired index, expanding capacity if necessary.
* Places element of type <E> at the desired index
*
* @param index the index for the element to be placed
* @param index the index for the element to be placed
* @param element the element to be inserted
* @throws IndexOutOfBoundsException if n is less than 0 or greater or equal to the number of elements in the array
*/
public void put(final int index, E element) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative.");
}
ensureCapacity(index + 1);
elements[index] = element;
if (index >= size) {
size = index + 1;
}
modCount++; // Increment modification count
this.elements[index] = element;
}
/**
* Gets the element at a given index.
* get method for element at a given index returns null if the index is
* empty
*
* @param index the desired index of the element
* @return the element at the specified index
* @throws IndexOutOfBoundsException if n is less than 0 or greater or equal to the number of elements in the array
* @return <E> the element at the specified index
*/
@SuppressWarnings("unchecked")
public E get(final int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
return (E) elements[index];
return getElement(index);
}
/**
* Removes an element from the array.
* Removes an element from the array
*
* @param index the index of the element to be removed
* @return the element removed
* @throws IndexOutOfBoundsException if n is less than 0 or greater or equal to the number of elements in the array
* @return <E> the element removed
*/
public E remove(final int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
final E oldElement = getElement(index);
fastRemove(this.elements, index);
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) {
this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
}
@SuppressWarnings("unchecked") E oldElement = (E) elements[index];
fastRemove(index);
modCount++; // Increment modification count
return oldElement;
}
/**
* Gets the size of the array.
* get method for size field
*
* @return the size
* @return int size
*/
public int getSize() {
return size;
return this.size;
}
/**
* Checks if the array is empty.
* isEmpty helper method
*
* @return true if the array contains no elements, false otherwise
* @return boolean true if the array contains no elements, false otherwise
*/
public boolean isEmpty() {
return size == 0;
return this.size == 0;
}
public Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
private void ensureCapacity(int minCapacity) {
if (minCapacity > elements.length) {
int newCapacity = Math.max(elements.length * 2, minCapacity);
elements = Arrays.copyOf(elements, newCapacity);
private void fastRemove(final Object[] elements, final int index) {
final int newSize = this.size - 1;
if (newSize > index) {
System.arraycopy(elements, index + 1, elements, index, newSize - index);
}
elements[this.size = newSize] = null;
}
private void fastRemove(int index) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elements, index + 1, elements, index, numMoved);
}
elements[--size] = null; // Clear to let GC do its work
private E getElement(final int index) {
return (E) this.elements[index];
}
private int newCapacity(int capacity) {
this.capacity = capacity;
return this.capacity;
}
/**
* returns a String representation of this object
*
* @return String a String representing the array
*/
@Override
public String toString() {
return Arrays.toString(Arrays.copyOf(elements, size));
return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
}
/**
* Creates and returns a new Dynamic Array Iterator
*
* @return Iterator a Dynamic Array Iterator
*/
@Override
public Iterator<E> iterator() {
return new DynamicArrayIterator();
}
private final class DynamicArrayIterator implements Iterator<E> {
private class DynamicArrayIterator implements Iterator<E> {
private int cursor;
private int expectedModCount;
DynamicArrayIterator() {
this.expectedModCount = modCount;
}
@Override
public boolean hasNext() {
checkForComodification();
return cursor < size;
return this.cursor != size;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
if (cursor >= size) {
if (this.cursor > DynamicArray.this.size) {
throw new NoSuchElementException();
}
return (E) elements[cursor++];
if (this.cursor > DynamicArray.this.elements.length) {
throw new ConcurrentModificationException();
}
final E element = DynamicArray.this.getElement(this.cursor);
this.cursor++;
return element;
}
@Override
public void remove() {
if (cursor <= 0) {
if (this.cursor < 0) {
throw new IllegalStateException();
}
checkForComodification();
DynamicArray.this.remove(--cursor);
expectedModCount = ++modCount;
}
private void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
DynamicArray.this.remove(this.cursor);
this.cursor--;
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext()) {
action.accept(next());
for (int i = 0; i < DynamicArray.this.size; i++) {
action.accept(DynamicArray.this.getElement(i));
}
}
}
/**
* This class is the driver for the DynamicArray<E> class it tests a variety
* of methods and prints the output
*/
public static void main(String[] args) {
DynamicArray<String> names = new DynamicArray<>();
names.add("Peubes");
names.add("Marley");
for (String name : names) {
System.out.println(name);
}
names.stream().forEach(System.out::println);
System.out.println(names);
System.out.println(names.getSize());
names.remove(0);
for (String name : names) {
System.out.println(name);
}
}
}

View File

@ -3,15 +3,9 @@
*/
package com.thealgorithms.datastructures.graphs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.*;
public final class AStar {
private AStar() {
}
public class A_Star {
private static class Graph {
@ -20,7 +14,7 @@ public final class AStar {
private ArrayList<ArrayList<Edge>> graph;
// Initialise ArrayLists in Constructor
Graph(int size) {
public Graph(int size) {
this.graph = new ArrayList<>();
for (int i = 0; i < size; i++) {
this.graph.add(new ArrayList<>());
@ -44,7 +38,7 @@ public final class AStar {
private int to;
private int weight;
Edge(int from, int to, int weight) {
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
@ -70,7 +64,7 @@ public final class AStar {
private ArrayList<Integer> path; // list of visited nodes in this path.
private int estimated; // heuristic value associated to the last node od the path (current node).
PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
this.distance = distance;
this.path = path;
this.estimated = estimated;

View File

@ -1,6 +1,6 @@
package com.thealgorithms.datastructures.graphs;
import java.util.Scanner;
import java.util.*;
class BellmanFord /*
* Implementation of Bellman ford to detect negative cycles. Graph accepts
@ -11,8 +11,7 @@ class BellmanFord /*
*/
{
int vertex;
int edge;
int vertex, edge;
private Edge[] edges;
private int index = 0;
@ -24,8 +23,7 @@ class BellmanFord /*
class Edge {
int u;
int v;
int u, v;
int w;
/**
@ -33,7 +31,7 @@ class BellmanFord /*
* @param v End vertex
* @param c Weight
*/
Edge(int a, int b, int c) {
public Edge(int a, int b, int c) {
u = a;
v = b;
w = c;
@ -57,19 +55,10 @@ class BellmanFord /*
obj.go();
}
public void go() {
// shows distance to all vertices
// Interactive run for understanding the
// class first time. Assumes source vertex is 0 and
try (Scanner sc = new Scanner(System.in)) {
int i;
int v;
int e;
int u;
int ve;
int w;
int j;
int neg = 0;
public void go() { // shows distance to all vertices // Interactive run for understanding the
try ( // class first time. Assumes source vertex is 0 and
Scanner sc = new Scanner(System.in)) {
int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please");
v = sc.nextInt();
e = sc.nextInt();
@ -118,6 +107,7 @@ class BellmanFord /*
System.out.println();
}
}
sc.close();
}
}
@ -130,11 +120,7 @@ class BellmanFord /*
Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray()
// method // Just shows results of computation, if graph is passed to it. The
// graph should
int i;
int j;
int v = vertex;
int e = edge;
int neg = 0;
int i, j, v = vertex, e = edge, neg = 0;
double[] dist = new double[v]; // Distance array for holding the finalized shortest path
// distance between source
// and all vertices

View File

@ -14,18 +14,16 @@ import java.util.Arrays;
*
* Output : YES
*/
public final class BipartiteGraphDFS {
private BipartiteGraphDFS() {
}
public class BipartiteGrapfDFS {
private static boolean bipartite(int v, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
if (color[node] == -1) {
color[node] = 1;
}
for (Integer it : adj.get(node)) {
if (color[it] == -1) {
color[it] = 1 - color[node];
if (!bipartite(v, adj, color, it)) {
if (!bipartite(V, adj, color, it)) {
return false;
}
} else if (color[it] == color[node]) {
@ -35,14 +33,14 @@ public final class BipartiteGraphDFS {
return true;
}
public static boolean isBipartite(int v, ArrayList<ArrayList<Integer>> adj) {
public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
int[] color = new int[v + 1];
int[] color = new int[V + 1];
Arrays.fill(color, -1);
for (int i = 0; i < v; i++) {
for (int i = 0; i < V; i++) {
if (color[i] == -1) {
if (!bipartite(v, adj, color, i)) {
if (!bipartite(V, adj, color, i)) {
return false;
}
}
@ -54,23 +52,23 @@ public final class BipartiteGraphDFS {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine().trim());
while (t-- > 0) {
String[] str1 = read.readLine().trim().split(" ");
int numVertices = Integer.parseInt(str1[0]);
int numEdges = Integer.parseInt(str1[1]);
String[] S = read.readLine().trim().split(" ");
int V = Integer.parseInt(S[0]);
int E = Integer.parseInt(S[1]);
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < numVertices; i++) {
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
for (int i = 0; i < numEdges; i++) {
String[] str2 = read.readLine().trim().split(" ");
int vertexU = Integer.parseInt(str2[0]);
int vertexV = Integer.parseInt(str2[1]);
adj.get(vertexU).add(vertexV);
adj.get(vertexV).add(vertexU);
for (int i = 0; i < E; i++) {
String[] s = read.readLine().trim().split(" ");
int u = Integer.parseInt(s[0]);
int v = Integer.parseInt(s[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
boolean ans = isBipartite(numVertices, adj);
boolean ans = isBipartite(V, adj);
if (ans) {
System.out.println("YES");
} else {

View File

@ -15,17 +15,16 @@ class Graph<E extends Comparable<E>> {
E name;
Node(E name) {
public Node(E name) {
this.name = name;
}
}
class Edge {
Node startNode;
Node endNode;
Node startNode, endNode;
Edge(Node startNode, Node endNode) {
public Edge(Node startNode, Node endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
@ -34,7 +33,7 @@ class Graph<E extends Comparable<E>> {
ArrayList<Edge> edgeList;
ArrayList<Node> nodeList;
Graph() {
public Graph() {
edgeList = new ArrayList<Edge>();
nodeList = new ArrayList<Node>();
}
@ -47,8 +46,7 @@ class Graph<E extends Comparable<E>> {
* @param endNode the ending Node from the edge
*/
public void addEdge(E startNode, E endNode) {
Node start = null;
Node end = null;
Node start = null, end = null;
for (Node node : nodeList) {
if (startNode.compareTo(node.name) == 0) {
start = node;
@ -81,7 +79,8 @@ class Graph<E extends Comparable<E>> {
Set<Node> markedNodes = new HashSet<Node>();
for (Node n : nodeList) {
if (markedNodes.add(n)) {
if (!markedNodes.contains(n)) {
markedNodes.add(n);
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
count++;
}
@ -108,9 +107,7 @@ class Graph<E extends Comparable<E>> {
}
}
public final class ConnectedComponent {
private ConnectedComponent() {
}
public class ConnectedComponent {
public static void main(String[] args) {
Graph<Character> graphChars = new Graph<>();

View File

@ -5,13 +5,12 @@ import java.util.Scanner;
class Cycle {
private final int nodes;
private final int edges;
private int nodes, edges;
private int[][] adjacencyMatrix;
private boolean[] visited;
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
Cycle() {
public Cycle() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of nodes: ");
nodes = in.nextInt();
@ -28,8 +27,7 @@ class Cycle {
System.out.println("Enter the details of each edges <Start Node> <End Node>");
for (int i = 0; i < edges; i++) {
int start;
int end;
int start, end;
start = in.nextInt();
end = in.nextInt();
adjacencyMatrix[start][end] = 1;
@ -80,9 +78,7 @@ class Cycle {
}
}
public final class Cycles {
private Cycles() {
}
public class Cycles {
public static void main(String[] args) {
Cycle c = new Cycle();

View File

@ -0,0 +1,85 @@
/*
Refer https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
for better understanding
*/
package com.thealgorithms.datastructures.graphs;
class dijkstras {
int k = 9;
int minDist(int[] dist, Boolean[] Set) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int r = 0; r < k; r++) {
if (!Set[r] && dist[r] <= min) {
min = dist[r];
min_index = r;
}
}
return min_index;
}
void print(int[] dist) {
System.out.println("Vertex \t\t Distance");
for (int i = 0; i < k; i++) {
System.out.println(i + " \t " + dist[i]);
}
}
void dijkstra(int[][] graph, int src) {
int[] dist = new int[k];
Boolean[] Set = new Boolean[k];
for (int i = 0; i < k; i++) {
dist[i] = Integer.MAX_VALUE;
Set[i] = false;
}
dist[src] = 0;
for (int c = 0; c < k - 1; c++) {
int u = minDist(dist, Set);
Set[u] = true;
for (int v = 0; v < k; v++) {
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
print(dist);
}
public static void main(String[] args) {
int[][] graph = new int[][] {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0},
};
dijkstras t = new dijkstras();
t.dijkstra(graph, 0);
} // main
} // djikstras
/*
OUTPUT :
Vertex Distance
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
*/

View File

@ -1,91 +0,0 @@
package com.thealgorithms.datastructures.graphs;
import java.util.Arrays;
/**
* Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph.
*/
public class DijkstraAlgorithm {
private final int vertexCount;
/**
* Constructs a Dijkstra object with the given number of vertices.
*
* @param vertexCount The number of vertices in the graph.
*/
public DijkstraAlgorithm(int vertexCount) {
this.vertexCount = vertexCount;
}
/**
* Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices.
*
* The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i}
* to vertex {@code j}. A value of 0 indicates no edge exists between the vertices.
*
* @param graph The graph represented as an adjacency matrix.
* @param source The source vertex.
* @return An array where the value at each index {@code i} represents the shortest distance from the source vertex to vertex {@code i}.
* @throws IllegalArgumentException if the source vertex is out of range.
*/
public int[] run(int[][] graph, int source) {
if (source < 0 || source >= vertexCount) {
throw new IllegalArgumentException("Incorrect source");
}
int[] distances = new int[vertexCount];
boolean[] processed = new boolean[vertexCount];
Arrays.fill(distances, Integer.MAX_VALUE);
Arrays.fill(processed, false);
distances[source] = 0;
for (int count = 0; count < vertexCount - 1; count++) {
int u = getMinDistanceVertex(distances, processed);
processed[u] = true;
for (int v = 0; v < vertexCount; v++) {
if (!processed[v] && graph[u][v] != 0 && distances[u] != Integer.MAX_VALUE && distances[u] + graph[u][v] < distances[v]) {
distances[v] = distances[u] + graph[u][v];
}
}
}
printDistances(distances);
return distances;
}
/**
* Finds the vertex with the minimum distance value from the set of vertices that have not yet been processed.
*
* @param distances The array of current shortest distances from the source vertex.
* @param processed The array indicating whether each vertex has been processed.
* @return The index of the vertex with the minimum distance value.
*/
private int getMinDistanceVertex(int[] distances, boolean[] processed) {
int min = Integer.MAX_VALUE;
int minIndex = -1;
for (int v = 0; v < vertexCount; v++) {
if (!processed[v] && distances[v] <= min) {
min = distances[v];
minIndex = v;
}
}
return minIndex;
}
/**
* Prints the shortest distances from the source vertex to all other vertices.
*
* @param distances The array of shortest distances.
*/
private void printDistances(int[] distances) {
System.out.println("Vertex \t Distance");
for (int i = 0; i < vertexCount; i++) {
System.out.println(i + " \t " + distances[i]);
}
}
}

View File

@ -4,31 +4,31 @@ import java.util.Scanner;
public class FloydWarshall {
private int[][] distanceMatrix;
private int[][] DistanceMatrix;
private int numberofvertices; // number of vertices in the graph
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
distanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex
// The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices;
}
public void floydwarshall(int[][] adjacencyMatrix) { // calculates all the distances from source to destination vertex
public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
distanceMatrix[source][destination] = adjacencyMatrix[source][destination];
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
}
}
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
if (distanceMatrix[source][intermediate] + distanceMatrix[intermediate][destination] < distanceMatrix[source][destination]) { // calculated distance it get replaced as
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] < DistanceMatrix[source][destination]) { // calculated distance it get replaced as
// new shortest distance // if the new
// distance calculated is less then the
// earlier shortest
distanceMatrix[source][destination] = distanceMatrix[source][intermediate] + distanceMatrix[intermediate][destination];
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
}
}
}
@ -40,7 +40,7 @@ public class FloydWarshall {
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
for (int destination = 1; destination <= numberofvertices; destination++) {
System.out.print(distanceMatrix[source][destination] + "\t");
System.out.print(DistanceMatrix[source][destination] + "\t");
}
System.out.println();
}

View File

@ -1,57 +0,0 @@
package com.thealgorithms.datastructures.graphs;
import java.util.LinkedList;
import java.util.Queue;
public final class FordFulkerson {
private static final int INF = Integer.MAX_VALUE;
private FordFulkerson() {
}
public static int networkFlow(int vertexCount, int[][] capacity, int[][] flow, int source, int sink) {
int totalFlow = 0;
while (true) {
int[] parent = new int[vertexCount];
boolean[] visited = new boolean[vertexCount];
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
visited[source] = true;
parent[source] = -1;
while (!queue.isEmpty() && !visited[sink]) {
int current = queue.poll();
for (int next = 0; next < vertexCount; next++) {
if (!visited[next] && capacity[current][next] - flow[current][next] > 0) {
queue.add(next);
visited[next] = true;
parent[next] = current;
}
}
}
if (!visited[sink]) {
break; // No more augmenting paths
}
int pathFlow = INF;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = Math.min(pathFlow, capacity[u][v] - flow[u][v]);
}
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
flow[u][v] += pathFlow;
flow[v][u] -= pathFlow;
}
totalFlow += pathFlow;
}
return totalFlow;
}
}

View File

@ -6,7 +6,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
ArrayList<Vertex> vertices;
AdjacencyListGraph() {
public AdjacencyListGraph() {
vertices = new ArrayList<>();
}
@ -15,7 +15,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
E data;
ArrayList<Vertex> adjacentVertices;
Vertex(E data) {
public Vertex(E data) {
adjacentVertices = new ArrayList<>();
this.data = data;
}
@ -75,8 +75,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
* already did
*/
public boolean addEdge(E from, E to) {
Vertex fromV = null;
Vertex toV = null;
Vertex fromV = null, toV = null;
for (Vertex v : vertices) {
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
fromV = v;
@ -121,9 +120,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
}
}
public final class Graphs {
private Graphs() {
}
public class Graphs {
public static void main(String[] args) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();

View File

@ -2,14 +2,13 @@ package com.thealgorithms.datastructures.graphs;
/**
* Java program for Hamiltonian Cycle
* <a href="https://en.wikipedia.org/wiki/Hamiltonian_path">wikipedia</a>
* (https://en.wikipedia.org/wiki/Hamiltonian_path)
*
* @author <a href="https://github.com/itsAkshayDubey">Akshay Dubey</a>
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/
public class HamiltonianCycle {
private int vertex;
private int pathCount;
private int V, pathCount;
private int[] cycle;
private int[][] graph;
@ -22,8 +21,8 @@ public class HamiltonianCycle {
* else returns 1D array with value -1.
*/
public int[] findHamiltonianCycle(int[][] graph) {
this.vertex = graph.length;
this.cycle = new int[this.vertex + 1];
this.V = graph.length;
this.cycle = new int[this.V + 1];
// Initialize path array with -1 value
for (int i = 0; i < this.cycle.length; i++) {
@ -53,36 +52,36 @@ public class HamiltonianCycle {
* @returns true if path is found false otherwise
*/
public boolean isPathFound(int vertex) {
boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.vertex;
boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
if (isLastVertexConnectedToStart) {
return true;
}
/* all vertices selected but last vertex not linked to 0 **/
if (this.pathCount == this.vertex) {
/** all vertices selected but last vertex not linked to 0 **/
if (this.pathCount == this.V) {
return false;
}
for (int v = 0; v < this.vertex; v++) {
/* if connected **/
for (int v = 0; v < this.V; v++) {
/** if connected **/
if (this.graph[vertex][v] == 1) {
/* add to path **/
/** add to path **/
this.cycle[this.pathCount++] = v;
/* remove connection **/
/** remove connection **/
this.graph[vertex][v] = 0;
this.graph[v][vertex] = 0;
/* if vertex not already selected solve recursively **/
/** if vertex not already selected solve recursively **/
if (!isPresent(v)) {
return isPathFound(v);
}
/* restore connection **/
/** restore connection **/
this.graph[vertex][v] = 1;
this.graph[v][vertex] = 1;
/* remove path **/
/** remove path **/
this.cycle[--this.pathCount] = -1;
}
}

View File

@ -8,6 +8,9 @@ import java.util.Map;
import java.util.Queue;
import java.util.Set;
/**
* An algorithm that sorts a graph in toplogical order.
*/
/**
* A class that represents the adjaceny list of a graph
*/
@ -51,6 +54,19 @@ class AdjacencyList<E extends Comparable<E>> {
Set<E> getVertices() {
return adj.keySet();
}
/**
* Prints the adjacency list
*/
void printGraph() {
for (E vertex : adj.keySet()) {
System.out.print(vertex + " : ");
for (E adjacent : adj.get(vertex)) {
System.out.print(adjacent + " ");
}
System.out.println();
}
}
}
class TopologicalSort<E extends Comparable<E>> {
@ -88,9 +104,9 @@ class TopologicalSort<E extends Comparable<E>> {
calculateInDegree();
Queue<E> q = new LinkedList<E>();
for (final var entry : inDegree.entrySet()) {
if (entry.getValue() == 0) {
q.add(entry.getKey());
for (E vertex : inDegree.keySet()) {
if (inDegree.get(vertex) == 0) {
q.add(vertex);
}
}
@ -114,9 +130,7 @@ class TopologicalSort<E extends Comparable<E>> {
/**
* A driver class that sorts a given graph in topological order.
*/
public final class KahnsAlgorithm {
private KahnsAlgorithm() {
}
public class KahnsAlgorithm {
public static void main(String[] args) {
// Graph definition and initialization

View File

@ -6,50 +6,53 @@ import java.util.Stack;
/**
* Java program that implements Kosaraju Algorithm.
* @author <a href="https://github.com/shivu2002a">Shivanagouda S A</a>
* <p>
* @author Shivanagouda S A (https://github.com/shivu2002a)
*
*/
/**
* Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
graph.
directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
graph.
* A graph is said to be strongly connected if every vertex is reachable from every other vertex.
The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
connected. Single node is always a SCC.
The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
connected. Single node is always a SCC.
* Example:
0 <--- 2 -------> 3 -------- > 4 ---- > 7
| ^ | ^ ^
| / | \ /
| / | \ /
v / v \ /
1 5 --> 6
0 <--- 2 -------> 3 -------- > 4 ---- > 7
| ^ | ^ ^
| / | \ /
| / | \ /
v / v \ /
1 5 --> 6
For the above graph, the SCC list goes as follows:
0, 1, 2
3
4, 5, 6
7
For the above graph, the SCC list goes as follows:
0, 1, 2
3
4, 5, 6
7
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
{@summary}
{@summary}
* Kosaraju Algorithm:
1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
sorted by lowest finish time.
2. Find the transpose graph by reversing the edges.
3. Pop nodes one by one from the stack and again to DFS on the modified graph.
1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
sorted by lowest finish time.
2. Find the transpose graph by reversing the edges.
3. Pop nodes one by one from the stack and again to DFS on the modified graph.
The transpose graph of the above graph:
0 ---> 2 <------- 3 <------- 4 <------ 7
^ / ^ \ /
| / | \ /
| / | \ /
| v | v v
1 5 <--- 6
The transpose graph of the above graph:
0 ---> 2 <------- 3 <------- 4 <------ 7
^ / ^ \ /
| / | \ /
| / | \ /
| v | v v
1 5 <--- 6
We can observe that this graph has the same SCC as that of original graph.
We can observe that this graph has the same SCC as that of original graph.
*/
@ -124,9 +127,7 @@ public class Kosaraju {
private void dfs(int node, int[] vis, List<List<Integer>> list) {
vis[node] = 1;
for (Integer neighbour : list.get(node)) {
if (vis[neighbour] == 0) {
dfs(neighbour, vis, list);
}
if (vis[neighbour] == 0) dfs(neighbour, vis, list);
}
stack.push(node);
}
@ -135,9 +136,7 @@ public class Kosaraju {
private void dfs2(int node, int[] vis, List<List<Integer>> list) {
vis[node] = 1;
for (Integer neighbour : list.get(node)) {
if (vis[neighbour] == 0) {
dfs2(neighbour, vis, list);
}
if (vis[neighbour] == 0) dfs2(neighbour, vis, list);
}
scc.add(node);
}

View File

@ -23,7 +23,7 @@ public class Kruskal {
private int to;
private int weight;
Edge(int from, int to, int weight) {
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;

View File

@ -12,9 +12,7 @@ import java.util.Queue;
*
* @author Unknown
*/
public final class MatrixGraphs {
private MatrixGraphs() {
}
public class MatrixGraphs {
public static void main(String[] args) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
@ -48,17 +46,17 @@ class AdjacencyMatrixGraph {
/**
* The number of vertices in the graph
*/
private int vertexCount;
private int _numberOfVertices;
/**
* The number of edges in the graph
*/
private int edgeCount;
private int _numberOfEdges;
/**
* The adjacency matrix for the graph
*/
private int[][] adjMatrix;
private int[][] _adjacency;
/**
* Static variables to define whether or not an edge exists in the adjacency
@ -70,7 +68,7 @@ class AdjacencyMatrixGraph {
/**
* Constructor
*/
AdjacencyMatrixGraph(int givenNumberOfVertices) {
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
@ -87,16 +85,16 @@ class AdjacencyMatrixGraph {
* @param newNumberOfVertices the new number of vertices
*/
private void setNumberOfVertices(int newNumberOfVertices) {
this.vertexCount = newNumberOfVertices;
this._numberOfVertices = newNumberOfVertices;
}
/**
* Getter for `this.vertexCount`
* Getter for `this._numberOfVertices`
*
* @return the number of vertices in the graph
*/
public int numberOfVertices() {
return this.vertexCount;
return this._numberOfVertices;
}
/**
@ -106,16 +104,16 @@ class AdjacencyMatrixGraph {
*
*/
private void setNumberOfEdges(int newNumberOfEdges) {
this.edgeCount = newNumberOfEdges;
this._numberOfEdges = newNumberOfEdges;
}
/**
* Getter for `this.edgeCount`
* Getter for `this._numberOfEdges`
*
* @return the number of edges
*/
public int numberOfEdges() {
return this.edgeCount;
return this._numberOfEdges;
}
/**
@ -124,7 +122,7 @@ class AdjacencyMatrixGraph {
* @param newAdjacency the new adjaceny matrix
*/
private void setAdjacency(int[][] newAdjacency) {
this.adjMatrix = newAdjacency;
this._adjacency = newAdjacency;
}
/**
@ -133,7 +131,7 @@ class AdjacencyMatrixGraph {
* @return the adjacency matrix
*/
private int[][] adjacency() {
return this.adjMatrix;
return this._adjacency;
}
/**
@ -222,12 +220,12 @@ class AdjacencyMatrixGraph {
*/
public List<Integer> depthFirstOrder(int startVertex) {
// If the startVertex is invalid, return an empty list
if (startVertex >= vertexCount || startVertex < 0) {
if (startVertex >= _numberOfVertices || startVertex < 0) {
return new ArrayList<Integer>();
}
// Create an array to track the visited vertices
boolean[] visited = new boolean[vertexCount];
boolean[] visited = new boolean[_numberOfVertices];
// Create a list to keep track of the order of our traversal
ArrayList<Integer> orderList = new ArrayList<Integer>();
@ -259,7 +257,7 @@ class AdjacencyMatrixGraph {
orderList.add(currentVertex);
// Get the adjacency array for this vertex
int[] adjacent = adjMatrix[currentVertex];
int[] adjacent = _adjacency[currentVertex];
for (int i = 0; i < adjacent.length; i++) { // we are considering exploring, recurse on it // If an edge exists between the
// currentVertex and the vertex
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
@ -277,12 +275,12 @@ class AdjacencyMatrixGraph {
*/
public List<Integer> breadthFirstOrder(int startVertex) {
// If the specified startVertex is invalid, return an empty list
if (startVertex >= vertexCount || startVertex < 0) {
if (startVertex >= _numberOfVertices || startVertex < 0) {
return new ArrayList<Integer>();
}
// Create an array to keep track of the visited vertices
boolean[] visited = new boolean[vertexCount];
boolean[] visited = new boolean[_numberOfVertices];
// Create a list to keep track of the ordered vertices
ArrayList<Integer> orderList = new ArrayList<Integer>();
@ -309,7 +307,7 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for the currentVertex and
// check each node
int[] adjacent = adjMatrix[currentVertex];
int[] adjacent = _adjacency[currentVertex];
for (int vertex = 0; vertex < adjacent.length; vertex++) { // vertex we are considering exploring, we add it to the queue // If an
// edge exists between the current vertex and the
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
@ -336,7 +334,7 @@ class AdjacencyMatrixGraph {
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + i + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + this.adjMatrix[i][j] + " ";
s = s + this._adjacency[i][j] + " ";
}
s = s + "\n";
}

View File

@ -14,17 +14,16 @@ class PrimMST {
// value, from the set of vertices not yet included in MST
int minKey(int[] key, Boolean[] mstSet) {
// Initialize min value
int min = Integer.MAX_VALUE;
int minIndex = -1;
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
min_index = v;
}
}
return minIndex;
return min_index;
}
// A utility function to print the constructed MST stored in
@ -51,7 +50,7 @@ class PrimMST {
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = Boolean.FALSE;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
@ -66,7 +65,7 @@ class PrimMST {
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = Boolean.TRUE;
mstSet[u] = true;
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those

View File

@ -6,58 +6,61 @@ import java.util.Stack;
/**
* Java program that implements Tarjan's Algorithm.
* @author <a href="https://github.com/shivu2002a">Shivanagouda S A</a>
* <p>
* @author Shivanagouda S A (https://github.com/shivu2002a)
*
*/
/**
* Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a
directed graph, which, from here onwards will be referred as SCC.
directed graph, which, from here onwards will be referred as SCC.
* A graph is said to be strongly connected if every vertex is reachable from every other vertex.
The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
connected. Single node is always a SCC.
The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
connected. Single node is always a SCC.
* Example:
0 --------> 1 -------> 3 --------> 4
^ /
| /
| /
| /
| /
| /
| /
| /
| /
| /
|V
2
0 --------> 1 -------> 3 --------> 4
^ /
| /
| /
| /
| /
| /
| /
| /
| /
| /
|V
2
For the above graph, the SCC list goes as follows:
1, 2, 0
3
4
For the above graph, the SCC list goes as follows:
1, 2, 0
3
4
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
{@summary}
Tarjan's Algorithm:
* DFS search produces a DFS tree
* Strongly Connected Components form subtrees of the DFS tree.
* If we can find the head of these subtrees, we can get all the nodes in that subtree (including
the head) and that will be one SCC.
* There is no back edge from one SCC to another (here can be cross edges, but they will not be
used).
{@summary}
Tarjan's Algorithm:
* DFS search produces a DFS tree
* Strongly Connected Components form subtrees of the DFS tree.
* If we can find the head of these subtrees, we can get all the nodes in that subtree (including
the head) and that will be one SCC.
* There is no back edge from one SCC to another (here can be cross edges, but they will not be
used).
* Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjans
algorithm does the same in a single DFS, which leads to much lower constant factors in the latter.
* Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjans
algorithm does the same in a single DFS, which leads to much lower constant factors in the latter.
*/
public class TarjansAlgorithm {
// Timer for tracking lowtime and insertion time
private int time;
private int Time;
private final List<List<Integer>> sccList = new ArrayList<List<Integer>>();
private List<List<Integer>> SCClist = new ArrayList<List<Integer>>();
public List<List<Integer>> stronglyConnectedComponents(int v, List<List<Integer>> graph) {
public List<List<Integer>> stronglyConnectedComponents(int V, List<List<Integer>> graph) {
// Initially all vertices as unvisited, insertion and low time are undefined
@ -65,34 +68,32 @@ public class TarjansAlgorithm {
// lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time)
// that can be reached from a subtree rooted with a particular node.
int[] lowTime = new int[v];
int[] insertionTime = new int[v];
for (int i = 0; i < v; i++) {
int[] lowTime = new int[V];
int[] insertionTime = new int[V];
for (int i = 0; i < V; i++) {
insertionTime[i] = -1;
lowTime[i] = -1;
}
// To check if element is present in stack
boolean[] isInStack = new boolean[v];
boolean[] isInStack = new boolean[V];
// Store nodes during DFS
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < v; i++) {
if (insertionTime[i] == -1) {
stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
}
for (int i = 0; i < V; i++) {
if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
}
return sccList;
return SCClist;
}
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
// Initialize insertion time and lowTime value of current node
insertionTime[u] = time;
lowTime[u] = time;
time += 1;
insertionTime[u] = Time;
lowTime[u] = Time;
Time += 1;
// Push current node into stack
isInStack[u] = true;
@ -122,7 +123,7 @@ public class TarjansAlgorithm {
scc.add(w);
isInStack[w] = false;
}
sccList.add(scc);
SCClist.add(scc);
}
}
}

View File

@ -17,7 +17,7 @@ public final class WelshPowell {
private WelshPowell() {
}
static final class Graph {
static class Graph {
private HashSet<Integer>[] adjacencyLists;
private Graph(int vertices) {

View File

@ -19,8 +19,8 @@ public class GenericHashMapUsingArray<K, V> {
// 75, then adding 76th item it will double the size, copy all elements
// & then add 76th item.
private void initBuckets(int n) {
buckets = new LinkedList[n];
private void initBuckets(int N) {
buckets = new LinkedList[N];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new LinkedList<>();
}
@ -47,7 +47,8 @@ public class GenericHashMapUsingArray<K, V> {
// tells which bucket to go to
private int hashFunction(K key) {
return Math.floorMod(key.hashCode(), buckets.length);
int hc = key.hashCode();
return Math.abs(hc) % buckets.length;
}
private void reHash() {

View File

@ -105,7 +105,7 @@ public class GenericHashMapUsingArrayList<K, V> {
K key;
V val;
Node(K key, V val) {
public Node(K key, V val) {
this.key = key;
this.val = val;
}

View File

@ -1,275 +1,142 @@
package com.thealgorithms.datastructures.hashmap.hashing;
/**
* A generic HashMap implementation that uses separate chaining with linked lists
* to handle collisions. The class supports basic operations such as insert, delete,
* and search, as well as displaying the contents of the hash map.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
public class HashMap<K, V> {
private final int hashSize;
private final LinkedList<K, V>[] buckets;
public class HashMap {
/**
* Constructs a HashMap with the specified hash size.
*
* @param hashSize the number of buckets in the hash map
*/
@SuppressWarnings("unchecked")
public HashMap(int hashSize) {
this.hashSize = hashSize;
// Safe to suppress warning because we are creating an array of generic type
this.buckets = new LinkedList[hashSize];
for (int i = 0; i < hashSize; i++) {
buckets[i] = new LinkedList<>();
private final int hsize;
private final LinkedList[] buckets;
public HashMap(int hsize) {
buckets = new LinkedList[hsize];
for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList();
// Java requires explicit initialization of each object
}
this.hsize = hsize;
}
/**
* Computes the hash code for the specified key.
* Null keys are hashed to bucket 0.
*
* @param key the key for which the hash code is to be computed
* @return the hash code corresponding to the key
*/
private int computeHash(K key) {
if (key == null) {
return 0; // Use a special bucket (e.g., bucket 0) for null keys
public int hashing(int key) {
int hash = key % hsize;
if (hash < 0) {
hash += hsize;
}
int hash = key.hashCode() % hashSize;
return hash < 0 ? hash + hashSize : hash;
return hash;
}
/**
* Inserts the specified key-value pair into the hash map.
* If the key already exists, the value is updated.
*
* @param key the key to be inserted
* @param value the value to be associated with the key
*/
public void insert(K key, V value) {
int hash = computeHash(key);
buckets[hash].insert(key, value);
public void insertHash(int key) {
int hash = hashing(key);
buckets[hash].insert(key);
}
/**
* Deletes the key-value pair associated with the specified key from the hash map.
*
* @param key the key whose key-value pair is to be deleted
*/
public void delete(K key) {
int hash = computeHash(key);
public void deleteHash(int key) {
int hash = hashing(key);
buckets[hash].delete(key);
}
/**
* Searches for the value associated with the specified key in the hash map.
*
* @param key the key whose associated value is to be returned
* @return the value associated with the specified key, or null if the key does not exist
*/
public V search(K key) {
int hash = computeHash(key);
Node<K, V> node = buckets[hash].findKey(key);
return node != null ? node.getValue() : null;
}
/**
* Displays the contents of the hash map, showing each bucket and its key-value pairs.
*/
public void display() {
for (int i = 0; i < hashSize; i++) {
System.out.printf("Bucket %d: %s%n", i, buckets[i].display());
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
System.out.printf("Bucket %d :", i);
System.out.println(buckets[i].display());
}
}
/**
* A nested static class that represents a linked list used for separate chaining in the hash map.
*
* @param <K> the type of keys maintained by this linked list
* @param <V> the type of mapped values
*/
public static class LinkedList<K, V> {
private Node<K, V> head;
public static class LinkedList {
/**
* Inserts the specified key-value pair into the linked list.
* If the linked list is empty, the pair becomes the head.
* Otherwise, the pair is added to the end of the list.
*
* @param key the key to be inserted
* @param value the value to be associated with the key
*/
public void insert(K key, V value) {
Node<K, V> existingNode = findKey(key);
if (existingNode != null) {
existingNode.setValue(value); // Update the value, even if it's null
} else {
if (isEmpty()) {
head = new Node<>(key, value);
} else {
Node<K, V> temp = findEnd(head);
temp.setNext(new Node<>(key, value));
}
}
private Node first;
public LinkedList() {
first = null;
}
/**
* Finds the last node in the linked list.
*
* @param node the starting node
* @return the last node in the linked list
*/
private Node<K, V> findEnd(Node<K, V> node) {
while (node.getNext() != null) {
node = node.getNext();
public void insert(int key) {
if (isEmpty()) {
first = new Node(key);
return;
}
return node;
Node temp = findEnd(first);
temp.setNext(new Node(key));
}
/**
* Finds the node associated with the specified key in the linked list.
*
* @param key the key to search for
* @return the node associated with the specified key, or null if not found
*/
public Node<K, V> findKey(K key) {
Node<K, V> temp = head;
while (temp != null) {
if ((key == null && temp.getKey() == null) || (temp.getKey() != null && temp.getKey().equals(key))) {
return temp;
private Node findEnd(Node n) {
while (n.getNext() != null) {
n = n.getNext();
}
return n;
}
public Node findKey(int key) {
if (!isEmpty()) {
Node temp = first;
if (temp.getKey() == key) return temp;
while ((temp = temp.getNext()) != null) {
if (temp.getKey() == key) return temp;
}
temp = temp.getNext();
}
return null;
}
/**
* Deletes the node associated with the specified key from the linked list.
* Handles the case where the key could be null.
*
* @param key the key whose associated node is to be deleted
*/
public void delete(K key) {
if (isEmpty()) {
return;
}
// Handle the case where the head node has the key to delete
if ((key == null && head.getKey() == null) || (head.getKey() != null && head.getKey().equals(key))) {
head = head.getNext();
return;
}
// Traverse the list to find and delete the node
Node<K, V> current = head;
while (current.getNext() != null) {
if ((key == null && current.getNext().getKey() == null) || (current.getNext().getKey() != null && current.getNext().getKey().equals(key))) {
current.setNext(current.getNext().getNext());
return;
public void delete(int key) {
if (!isEmpty()) {
if (first.getKey() == key) {
Node next = first.next;
first.next = null; // help GC
first = next;
} else {
delete(first, key);
}
current = current.getNext();
}
}
/**
* Displays the contents of the linked list as a string.
*
* @return a string representation of the linked list
*/
private void delete(Node n, int key) {
if (n.getNext().getKey() == key) {
if (n.getNext().getNext() == null) {
n.setNext(null);
} else {
n.setNext(n.getNext().getNext());
}
} else {
delete(n.getNext(), key);
}
}
public String display() {
return display(head);
return display(first);
}
/**
* Constructs a string representation of the linked list non-recursively.
*
* @param node the starting node
* @return a string representation of the linked list starting from the given node
*/
private String display(Node<K, V> node) {
StringBuilder sb = new StringBuilder();
while (node != null) {
sb.append(node.getKey()).append("=").append(node.getValue());
node = node.getNext();
if (node != null) {
sb.append(" -> ");
}
private String display(Node n) {
if (n == null) {
return "null";
} else {
return n.getKey() + "->" + display(n.getNext());
}
return sb.toString().isEmpty() ? "null" : sb.toString();
}
/**
* Checks if the linked list is empty.
*
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return head == null;
return first == null;
}
}
/**
* A nested static class representing a node in the linked list.
*
* @param <K> the type of key maintained by this node
* @param <V> the type of value maintained by this node
*/
public static class Node<K, V> {
private final K key;
private V value;
private Node<K, V> next;
public static class Node {
/**
* Constructs a Node with the specified key and value.
*
* @param key the key associated with this node
* @param value the value associated with this node
*/
public Node(K key, V value) {
private Node next;
private final int key;
public Node(int key) {
next = null;
this.key = key;
this.value = value;
}
/**
* Gets the key associated with this node.
*
* @return the key associated with this node
*/
public K getKey() {
return key;
}
/**
* Gets the value associated with this node.
*
* @return the value associated with this node
*/
public V getValue() {
return value;
}
public void setValue(V value) { // This method allows updating the value
this.value = value;
}
/**
* Gets the next node in the linked list.
*
* @return the next node in the linked list
*/
public Node<K, V> getNext() {
public Node getNext() {
return next;
}
/**
* Sets the next node in the linked list.
*
* @param next the next node to be linked
*/
public void setNext(Node<K, V> next) {
public int getKey() {
return key;
}
public void setNext(Node next) {
this.next = next;
}
}

View File

@ -12,21 +12,21 @@ public class HashMapCuckooHashing {
private int tableSize; // size of the hash table
private Integer[] buckets; // array representing the table
private final Integer emptySlot;
private final Integer AVAILABLE;
private int size; // number of elements in the hash table
private int thresh; // threshold for infinite loop checking
/**
* Constructor initializes buckets array, hsize, and creates dummy object
* for emptySlot
* for AVAILABLE
*
* @param tableSize the desired size of the hash map
*/
public HashMapCuckooHashing(int tableSize) {
this.buckets = new Integer[tableSize];
this.tableSize = tableSize;
this.emptySlot = Integer.MIN_VALUE;
this.AVAILABLE = Integer.MIN_VALUE;
this.size = 0;
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
}
@ -66,10 +66,8 @@ public class HashMapCuckooHashing {
*/
public void insertKey2HashTable(int key) {
Integer wrappedInt = key;
Integer temp;
int hash;
int loopCounter = 0;
Integer wrappedInt = key, temp;
int hash, loopCounter = 0;
if (isFull()) {
System.out.println("Hash table is full, lengthening & rehashing table");
@ -84,7 +82,7 @@ public class HashMapCuckooHashing {
loopCounter++;
hash = hashFunction1(key);
if ((buckets[hash] == null) || Objects.equals(buckets[hash], emptySlot)) {
if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
@ -95,7 +93,7 @@ public class HashMapCuckooHashing {
buckets[hash] = wrappedInt;
wrappedInt = temp;
hash = hashFunction2(temp);
if (Objects.equals(buckets[hash], emptySlot)) {
if (Objects.equals(buckets[hash], AVAILABLE)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
@ -124,7 +122,7 @@ public class HashMapCuckooHashing {
public void reHashTableIncreasesTableSize() {
HashMapCuckooHashing newT = new HashMapCuckooHashing(tableSize * 2);
for (int i = 0; i < tableSize; i++) {
if (buckets[i] != null && !Objects.equals(buckets[i], emptySlot)) {
if (buckets[i] != null && !Objects.equals(buckets[i], AVAILABLE)) {
newT.insertKey2HashTable(this.buckets[i]);
}
}
@ -146,14 +144,14 @@ public class HashMapCuckooHashing {
}
if (Objects.equals(buckets[hash], wrappedInt)) {
buckets[hash] = emptySlot;
buckets[hash] = AVAILABLE;
size--;
return;
}
hash = hashFunction2(key);
if (Objects.equals(buckets[hash], wrappedInt)) {
buckets[hash] = emptySlot;
buckets[hash] = AVAILABLE;
size--;
return;
}
@ -165,7 +163,7 @@ public class HashMapCuckooHashing {
*/
public void displayHashtable() {
for (int i = 0; i < tableSize; i++) {
if ((buckets[i] == null) || Objects.equals(buckets[i], emptySlot)) {
if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) {
System.out.println("Bucket " + i + ": Empty");
} else {
System.out.println("Bucket " + i + ": " + buckets[i].toString());
@ -188,14 +186,12 @@ public class HashMapCuckooHashing {
throw new IllegalArgumentException("Table is empty");
}
if (Objects.equals(buckets[hash], wrappedInt)) {
return hash;
}
if (Objects.equals(buckets[hash], wrappedInt)) return hash;
hash = hashFunction2(key);
if (!Objects.equals(buckets[hash], wrappedInt)) {
if (!Objects.equals(buckets[hash], wrappedInt))
throw new IllegalArgumentException("Key " + key + " not found in table");
} else {
else {
return hash;
}
}
@ -217,7 +213,7 @@ public class HashMapCuckooHashing {
public double checkLoadFactor() {
double factor = (double) size / tableSize;
if (factor > .7) {
System.out.printf("Load factor is %.2f , rehashing table%n", factor);
System.out.printf("Load factor is %.2f , rehashing table\n", factor);
reHashTableIncreasesTableSize();
}
return factor;
@ -231,7 +227,7 @@ public class HashMapCuckooHashing {
public boolean isFull() {
boolean response = true;
for (int i = 0; i < tableSize; i++) {
if (buckets[i] == null || Objects.equals(buckets[i], emptySlot)) {
if (buckets[i] == null || Objects.equals(buckets[i], AVAILABLE)) {
return false;
}
}

Some files were not shown because too many files have changed in this diff Show More