Compare commits
257 Commits
dependabot
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
648572a8c5 | ||
|
65e32641fc | ||
|
bded78f888 | ||
|
fa2231788f | ||
|
e0a1164cf5 | ||
|
175c84673a | ||
|
a5b083cab0 | ||
|
b396a9790e | ||
|
b0de93b3ce | ||
|
f8ff6af893 | ||
|
c5b72816f3 | ||
|
cd38531b0d | ||
|
14916e692f | ||
|
87cf89192b | ||
|
d189c3a719 | ||
|
9515d96ab6 | ||
|
c57e02dc85 | ||
|
e2aaefebd5 | ||
|
a23e9b0ba8 | ||
|
6b7a1fdbe8 | ||
|
203d544668 | ||
|
7d1847f51c | ||
|
0733075498 | ||
|
b2815db5cd | ||
|
c413f3c6b2 | ||
|
45563ccbde | ||
|
a9bc7c269d | ||
|
298333bf45 | ||
|
633b9d4112 | ||
|
fc5a70edc9 | ||
|
49d1c84cb7 | ||
|
e3ad3761fd | ||
|
af7c425010 | ||
|
0c8616e332 | ||
|
c8cf302d30 | ||
|
6fab70a91f | ||
|
c5b73ec742 | ||
|
d810a1d4da | ||
|
7674a84f5b | ||
|
4374a50fd7 | ||
|
4347f5b9f6 | ||
|
64ff9b2efe | ||
|
b70f077343 | ||
|
35f23d2ddc | ||
|
5f6510f0fa | ||
|
be6b0d835b | ||
|
cdb6412601 | ||
|
6edc009765 | ||
|
93e417544d | ||
|
7e9cdad3ee | ||
|
580aa0c9c5 | ||
|
a5f57fbfde | ||
|
3187b1f99c | ||
|
25b8010ea8 | ||
|
f3851e3adc | ||
|
101cb950ae | ||
|
69e1fe9cfb | ||
|
0b0b26e3fe | ||
|
e1d8b6f8a7 | ||
|
e5c0e4bff0 | ||
|
a8d3b6ad2d | ||
|
38688440ef | ||
|
b231a72d44 | ||
|
a7cd97d75e | ||
|
75355e87b6 | ||
|
4e72056527 | ||
|
84fb717509 | ||
|
aefc8fd4b8 | ||
|
44d7cbbaf4 | ||
|
ce4eb55e0e | ||
|
34089774f3 | ||
|
a6fcbf585f | ||
|
844aeaf701 | ||
|
d7b60be7d1 | ||
|
0301ecf1cb | ||
|
fb55552ebb | ||
|
56f97c48ac | ||
|
74b05ef7c2 | ||
|
622a3bf795 | ||
|
8a89b42cf8 | ||
|
3398c562a1 | ||
|
3ed8561a5f | ||
|
07dbc51e1b | ||
|
5149051e95 | ||
|
39ecf70857 | ||
|
4c65530722 | ||
|
a03353d3d3 | ||
|
e756a7d2d5 | ||
|
f5c0314111 | ||
|
8605220721 | ||
|
8712a7f405 | ||
|
04eae87512 | ||
|
33fd79ad55 | ||
|
a9f5b82708 | ||
|
2905ccbb20 | ||
|
404ad7272f | ||
|
e8985b3edb | ||
|
25b6aebe45 | ||
|
d80fd0c623 | ||
|
7c58b190c8 | ||
|
98bee26d51 | ||
|
e32cab3189 | ||
|
c20375ae0f | ||
|
ec30592fcb | ||
|
a84a4a29ed | ||
|
046f5a4728 | ||
|
134b42c7ff | ||
|
777de1da99 | ||
|
c4e0adbdd5 | ||
|
b8d0978e01 | ||
|
4fc646809c | ||
|
8d0dd3ef32 | ||
|
41f76e0e89 | ||
|
2837585705 | ||
|
66bfaff807 | ||
|
554b6cf006 | ||
|
197718842f | ||
|
7a5fe92b2a | ||
|
324a35a939 | ||
|
5fc26239eb | ||
|
cafea1ee52 | ||
|
6e23e198ab | ||
|
357e15addd | ||
|
365ede892f | ||
|
6f521145cc | ||
|
fccd141014 | ||
|
5113101e5d | ||
|
ebed8b38b8 | ||
|
76a450fb75 | ||
|
08db744240 | ||
|
97d416e64e | ||
|
94032148ca | ||
|
f1e26064a5 | ||
|
f584cd9a98 | ||
|
ff0eca3caa | ||
|
5840579885 | ||
|
57878cac55 | ||
|
2d6c39ce10 | ||
|
87e6184494 | ||
|
8ea90fdd42 | ||
|
f83bb659ba | ||
|
06927d3fda | ||
|
57f65808ad | ||
|
14264602de | ||
|
6b41c7d7a0 | ||
|
96e59e063a | ||
|
26b4b82949 | ||
|
5bc96cf789 | ||
|
e63c39ac88 | ||
|
ac31fba37a | ||
|
208e1e99f0 | ||
|
758df7dcc3 | ||
|
20e7a3aca4 | ||
|
0087444e9f | ||
|
224ee3d227 | ||
|
c2a5c91920 | ||
|
69f221683f | ||
|
cba28d31c5 | ||
|
7054535d36 | ||
|
971f5fc85b | ||
|
f279f9d589 | ||
|
cff3a59530 | ||
|
d36f54bd39 | ||
|
a710fe11c4 | ||
|
22f2abd94f | ||
|
7b17ead902 | ||
|
a5b4c6173f | ||
|
308bdcfc19 | ||
|
e8f1990c8c | ||
|
8ef69bc854 | ||
|
15d2e70673 | ||
|
91101ec424 | ||
|
a9db8428b2 | ||
|
bf4fc3f9c2 | ||
|
74e51990c1 | ||
|
39e065437c | ||
|
9973b8efc8 | ||
|
c7ee0e73c2 | ||
|
cdb3affdd9 | ||
|
87b17e0571 | ||
|
51fcc66345 | ||
|
31db1af345 | ||
|
a2af09cdfb | ||
|
f8698674b3 | ||
|
3ecd13508a | ||
|
0e8fed0dd6 | ||
|
a81fb32e6c | ||
|
be38886d43 | ||
|
41efe7fbbc | ||
|
732d5e06ae | ||
|
b315b7d578 | ||
|
440f3ce18b | ||
|
493942e319 | ||
|
f3db699083 | ||
|
2e387fe54e | ||
|
5e4db7baf1 | ||
|
c42b1c940c | ||
|
2568b96784 | ||
|
a6e873deef | ||
|
d2bfb100b2 | ||
|
2cda944643 | ||
|
1a98ebe36b | ||
|
25d711c5d8 | ||
|
81cb09b1f8 | ||
|
23ed1196c0 | ||
|
33a34841bb | ||
|
92887a10c2 | ||
|
70c1d97ab1 | ||
|
295e7436b1 | ||
|
ea4dc15a24 | ||
|
37c2a96fe2 | ||
|
9eaa2bb756 | ||
|
44ce6e7b0d | ||
|
160742104d | ||
|
8be8b953ab | ||
|
324969fc4e | ||
|
8466219685 | ||
|
5ee98eeb48 | ||
|
d77d9010a8 | ||
|
bf9d0ed66a | ||
|
0f42e995a4 | ||
|
f8e62fbb90 | ||
|
bbef89c885 | ||
|
5703be5953 | ||
|
319d5143cc | ||
|
cf6c87c35c | ||
|
cb401fed69 | ||
|
bbe4a025df | ||
|
52f15b2b08 | ||
|
27c0978851 | ||
|
7bff82f175 | ||
|
ee6924a2a0 | ||
|
d2ddec55e5 | ||
|
d3bb691f59 | ||
|
030bb91d05 | ||
|
ff5267d393 | ||
|
bfb27eeb59 | ||
|
414835db11 | ||
|
dc47e0aa42 | ||
|
5d00889291 | ||
|
6bde5d7ed5 | ||
|
dda3c9cb59 | ||
|
b3903f5768 | ||
|
1e2d7e9431 | ||
|
ede3e4651f | ||
|
032c288922 | ||
|
cdc320afaf | ||
|
f64bc3c65d | ||
|
06a284f811 | ||
|
fd65892415 | ||
|
2513ccd62b | ||
|
b075c19a54 | ||
|
4bb64559de | ||
|
de18d0df7e | ||
|
6de154d218 | ||
|
7a42f68b66 | ||
|
089b1f7c92 |
@ -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="17-bullseye"
|
||||
FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT}
|
||||
ARG VARIANT="21-bullseye"
|
||||
FROM mcr.microsoft.com/vscode/devcontainers/java:1.1.0-${VARIANT}
|
||||
|
||||
# [Option] Install Maven
|
||||
ARG INSTALL_MAVEN="false"
|
||||
|
@ -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": "17-bullseye",
|
||||
"VARIANT": "21-bullseye",
|
||||
// Options
|
||||
"INSTALL_MAVEN": "true",
|
||||
"INSTALL_GRADLE": "true",
|
||||
|
2
.github/CODEOWNERS
vendored
2
.github/CODEOWNERS
vendored
@ -1 +1 @@
|
||||
* @yanglbme @vil02 @BamaCharanChhandogi
|
||||
* @yanglbme @vil02 @BamaCharanChhandogi @alxkm @siriak
|
||||
|
5
.github/dependabot.yml
vendored
5
.github/dependabot.yml
vendored
@ -10,4 +10,9 @@ updates:
|
||||
directory: "/.github/workflows/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
- package-ecosystem: "maven"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
...
|
||||
|
10
.github/workflows/build.yml
vendored
10
.github/workflows/build.yml
vendored
@ -6,10 +6,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up JDK 17
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: 17
|
||||
java-version: 21
|
||||
distribution: 'adopt'
|
||||
- name: Build with Maven
|
||||
run: mvn --batch-mode --update-snapshots verify
|
||||
@ -29,3 +29,9 @@ jobs:
|
||||
with:
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
fail_ci_if_error: true
|
||||
- name: Checkstyle
|
||||
run: mvn checkstyle:check
|
||||
- name: SpotBugs
|
||||
run: mvn spotbugs:check
|
||||
- name: PMD
|
||||
run: mvn pmd:check
|
||||
|
2
.github/workflows/clang-format-lint.yml
vendored
2
.github/workflows/clang-format-lint.yml
vendored
@ -9,7 +9,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: DoozyX/clang-format-lint-action@v0.17
|
||||
- uses: DoozyX/clang-format-lint-action@v0.18
|
||||
with:
|
||||
source: './src'
|
||||
extensions: 'java'
|
||||
|
4
.github/workflows/codeql.yml
vendored
4
.github/workflows/codeql.yml
vendored
@ -26,10 +26,10 @@ jobs:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: 17
|
||||
java-version: 21
|
||||
distribution: 'adopt'
|
||||
|
||||
- name: Initialize CodeQL
|
||||
|
@ -1,4 +1,4 @@
|
||||
FROM gitpod/workspace-java-17:2024-04-15-14-41-42
|
||||
FROM gitpod/workspace-java-21:2024-07-14-17-19-51
|
||||
|
||||
ENV LLVM_SCRIPT="tmp_llvm.sh"
|
||||
|
||||
|
147
DIRECTORY.md
147
DIRECTORY.md
@ -18,6 +18,7 @@
|
||||
* [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)
|
||||
@ -52,6 +53,7 @@
|
||||
* [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)
|
||||
@ -60,7 +62,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)
|
||||
@ -72,6 +74,8 @@
|
||||
* [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)
|
||||
@ -96,14 +100,15 @@
|
||||
* dynamicarray
|
||||
* [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java)
|
||||
* graphs
|
||||
* [A Star](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java)
|
||||
* [AStar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/AStar.java)
|
||||
* [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java)
|
||||
* [BipartiteGrapfDFS](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java)
|
||||
* [BipartiteGraphDFS](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.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)
|
||||
* [DIJSKSTRAS ALGORITHM](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java)
|
||||
* [DijkstraAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.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)
|
||||
@ -121,7 +126,6 @@
|
||||
* [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)
|
||||
@ -141,7 +145,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)
|
||||
* [Merge K SortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java)
|
||||
* [MergeKSortedLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.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)
|
||||
@ -154,14 +158,15 @@
|
||||
* [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)
|
||||
* [Deques](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Deques.java)
|
||||
* [Deque](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Deque.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)
|
||||
* [Queues](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Queues.java)
|
||||
* [Queue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/queues/Queue.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)
|
||||
@ -192,6 +197,7 @@
|
||||
* [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)
|
||||
@ -225,7 +231,6 @@
|
||||
* [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)
|
||||
@ -290,6 +295,7 @@
|
||||
* [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)
|
||||
@ -355,6 +361,7 @@
|
||||
* [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)
|
||||
@ -376,7 +383,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)
|
||||
@ -389,7 +396,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)
|
||||
* [Sparcity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparcity.java)
|
||||
* [Sparsity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparsity.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)
|
||||
@ -403,22 +410,20 @@
|
||||
* [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)
|
||||
* [GuassLegendre](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/GuassLegendre.java)
|
||||
* [GaussLegendre](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/GaussLegendre.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)
|
||||
@ -434,17 +439,13 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* [RotateMatrixBy90Degrees](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RotateMatrixBy90Degrees.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)
|
||||
@ -479,7 +480,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)
|
||||
@ -490,7 +491,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)
|
||||
* [BubbleSortRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java)
|
||||
* [BubbleSortRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BubbleSortRecursive.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)
|
||||
@ -501,6 +502,7 @@
|
||||
* [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)
|
||||
@ -511,22 +513,26 @@
|
||||
* [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)
|
||||
@ -549,14 +555,16 @@
|
||||
* [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)
|
||||
* [longestNonRepeativeSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java)
|
||||
* [LongestNonRepetitiveSubstring](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/LongestNonRepetitiveSubstring.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)
|
||||
@ -566,7 +574,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
|
||||
@ -578,9 +586,11 @@
|
||||
* [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)
|
||||
@ -604,10 +614,14 @@
|
||||
* [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)
|
||||
* [DecimalToHexaDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/DecimalToHexaDecimalTest.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)
|
||||
* [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)
|
||||
@ -616,7 +630,11 @@
|
||||
* [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
|
||||
@ -634,8 +652,12 @@
|
||||
* [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)
|
||||
@ -644,6 +666,7 @@
|
||||
* 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)
|
||||
@ -652,14 +675,23 @@
|
||||
* [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)
|
||||
@ -677,6 +709,7 @@
|
||||
* [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)
|
||||
@ -684,17 +717,27 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -727,9 +770,12 @@
|
||||
* [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)
|
||||
@ -737,6 +783,7 @@
|
||||
* [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)
|
||||
@ -744,6 +791,7 @@
|
||||
* [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)
|
||||
@ -756,13 +804,17 @@
|
||||
* [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)
|
||||
@ -773,12 +825,14 @@
|
||||
* [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)
|
||||
@ -809,12 +863,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)
|
||||
@ -823,7 +877,11 @@
|
||||
* [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)
|
||||
* [SieveOfEratosthenesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/SieveOfEratosthenesTest.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)
|
||||
* [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)
|
||||
@ -845,28 +903,39 @@
|
||||
* [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)
|
||||
@ -874,12 +943,24 @@
|
||||
* [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)
|
||||
@ -892,11 +973,13 @@
|
||||
* [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)
|
||||
* [longestNonRepeativeSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.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)
|
||||
* [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)
|
||||
@ -906,4 +989,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)
|
||||
|
198
checkstyle.xml
Normal file
198
checkstyle.xml
Normal file
@ -0,0 +1,198 @@
|
||||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!--
|
||||
|
||||
Checkstyle configuration that checks the sun coding conventions from:
|
||||
|
||||
- the Java Language Specification at
|
||||
https://docs.oracle.com/javase/specs/jls/se11/html/index.html
|
||||
|
||||
- the Sun Code Conventions at https://www.oracle.com/java/technologies/javase/codeconventions-contents.html
|
||||
|
||||
- the Javadoc guidelines at
|
||||
https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html
|
||||
|
||||
- the JDK Api documentation https://docs.oracle.com/en/java/javase/11/
|
||||
|
||||
- some best practices
|
||||
|
||||
Checkstyle is very configurable. Be sure to read the documentation at
|
||||
https://checkstyle.org (or in your downloaded distribution).
|
||||
|
||||
Most Checks are configurable, be sure to consult the documentation.
|
||||
|
||||
To completely disable a check, just comment it out or delete it from the file.
|
||||
To suppress certain violations please review suppression filters.
|
||||
|
||||
Finally, it is worth reading the documentation.
|
||||
|
||||
-->
|
||||
|
||||
<module name="Checker">
|
||||
<!--
|
||||
If you set the basedir property below, then all reported file
|
||||
names will be relative to the specified directory. See
|
||||
https://checkstyle.org/config.html#Checker
|
||||
|
||||
<property name="basedir" value="${basedir}"/>
|
||||
-->
|
||||
<property name="severity" value="error"/>
|
||||
|
||||
<property name="fileExtensions" value="java, properties, xml"/>
|
||||
|
||||
<!-- Excludes all 'module-info.java' files -->
|
||||
<!-- See https://checkstyle.org/filefilters/index.html -->
|
||||
<module name="BeforeExecutionExclusionFileFilter">
|
||||
<property name="fileNamePattern" value="module\-info\.java$"/>
|
||||
</module>
|
||||
|
||||
<!-- https://checkstyle.org/filters/suppressionfilter.html -->
|
||||
<module name="SuppressionFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionfilter.config}"
|
||||
default="checkstyle-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks that a package-info.java file exists for each package. -->
|
||||
<!-- See https://checkstyle.org/checks/javadoc/javadocpackage.html#JavadocPackage -->
|
||||
<!-- TODO <module name="JavadocPackage"/> -->
|
||||
|
||||
<!-- Checks whether files end with a new line. -->
|
||||
<!-- See https://checkstyle.org/checks/misc/newlineatendoffile.html -->
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<!-- Checks that property files contain the same keys. -->
|
||||
<!-- See https://checkstyle.org/checks/misc/translation.html -->
|
||||
<module name="Translation"/>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/checks/sizes/index.html -->
|
||||
<!-- TODO <module name="FileLength"/> -->
|
||||
<!-- TODO <module name="LineLength">
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module> -->
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/checks/whitespace/index.html -->
|
||||
<!-- TODO <module name="FileTabCharacter"/> -->
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/checks/misc/index.html -->
|
||||
<module name="RegexpSingleline">
|
||||
<property name="format" value="\s+$"/>
|
||||
<property name="minimum" value="0"/>
|
||||
<property name="maximum" value="0"/>
|
||||
<property name="message" value="Line has trailing spaces."/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Headers -->
|
||||
<!-- See https://checkstyle.org/checks/header/index.html -->
|
||||
<!-- <module name="Header"> -->
|
||||
<!-- <property name="headerFile" value="${checkstyle.header.file}"/> -->
|
||||
<!-- <property name="fileExtensions" value="java"/> -->
|
||||
<!-- </module> -->
|
||||
|
||||
<module name="TreeWalker">
|
||||
|
||||
<!-- Checks for Javadoc comments. -->
|
||||
<!-- See https://checkstyle.org/checks/javadoc/index.html -->
|
||||
<module name="InvalidJavadocPosition"/>
|
||||
<!-- TODO <module name="JavadocMethod"/> -->
|
||||
<!-- TODO <module name="JavadocType"/> -->
|
||||
<!-- TODO <module name="JavadocVariable"/> -->
|
||||
<!-- TODO <module name="JavadocStyle"/> -->
|
||||
<!-- TODO <module name="MissingJavadocMethod"/> -->
|
||||
|
||||
<!-- 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"/>
|
||||
<module name="PackageName"/>
|
||||
<module name="ParameterName"/>
|
||||
<module name="StaticVariableName"/>
|
||||
<module name="TypeName"/>
|
||||
|
||||
<!-- Checks for imports -->
|
||||
<!-- See https://checkstyle.org/checks/imports/index.html -->
|
||||
<module name="AvoidStarImport"/>
|
||||
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
|
||||
<module name="RedundantImport"/>
|
||||
<module name="UnusedImports">
|
||||
<property name="processJavadoc" value="false"/>
|
||||
</module>
|
||||
|
||||
<!-- Checks for Size Violations. -->
|
||||
<!-- See https://checkstyle.org/checks/sizes/index.html -->
|
||||
<module name="MethodLength"/>
|
||||
<module name="ParameterNumber"/>
|
||||
|
||||
<!-- Checks for whitespace -->
|
||||
<!-- See https://checkstyle.org/checks/whitespace/index.html -->
|
||||
<module name="EmptyForIteratorPad"/>
|
||||
<!-- TODO <module name="GenericWhitespace"/> -->
|
||||
<module name="MethodParamPad"/>
|
||||
<!-- TODO <module name="NoWhitespaceAfter"/> -->
|
||||
<module name="NoWhitespaceBefore"/>
|
||||
<module name="OperatorWrap"/>
|
||||
<module name="ParenPad"/>
|
||||
<module name="TypecastParenPad"/>
|
||||
<module name="WhitespaceAfter"/>
|
||||
<module name="WhitespaceAround"/>
|
||||
|
||||
<!-- Modifier Checks -->
|
||||
<!-- See https://checkstyle.org/checks/modifier/index.html -->
|
||||
<module name="ModifierOrder"/>
|
||||
<module name="RedundantModifier"/>
|
||||
|
||||
<!-- Checks for blocks. You know, those {}'s -->
|
||||
<!-- See https://checkstyle.org/checks/blocks/index.html -->
|
||||
<module name="AvoidNestedBlocks"/>
|
||||
<!-- TODO <module name="EmptyBlock"/> -->
|
||||
<!-- TODO <module name="LeftCurly"/> -->
|
||||
<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="HiddenField"/> -->
|
||||
<module name="IllegalInstantiation"/>
|
||||
<module name="InnerAssignment"/>
|
||||
<!-- TODO <module name="MagicNumber"/> -->
|
||||
<module name="MissingSwitchDefault"/>
|
||||
<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"/>
|
||||
<module name="InterfaceIsType"/>
|
||||
<!-- TODO <module name="VisibilityModifier"/> -->
|
||||
|
||||
<!-- Miscellaneous other checks. -->
|
||||
<!-- See https://checkstyle.org/checks/misc/index.html -->
|
||||
<module name="ArrayTypeStyle"/>
|
||||
<!-- TODO <module name="FinalParameters"/> -->
|
||||
<!-- TODO <module name="TodoComment"/> -->
|
||||
<module name="UpperEll"/>
|
||||
|
||||
<!-- https://checkstyle.org/filters/suppressionxpathfilter.html -->
|
||||
<module name="SuppressionXpathFilter">
|
||||
<property name="file" value="${org.checkstyle.sun.suppressionxpathfilter.config}"
|
||||
default="checkstyle-xpath-suppressions.xml" />
|
||||
<property name="optional" value="true"/>
|
||||
</module>
|
||||
|
||||
</module>
|
||||
|
||||
</module>
|
90
pmd-exclude.properties
Normal file
90
pmd-exclude.properties
Normal file
@ -0,0 +1,90 @@
|
||||
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
|
82
pom.xml
82
pom.xml
@ -10,9 +10,9 @@
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<assertj.version>3.25.3</assertj.version>
|
||||
<maven.compiler.source>21</maven.compiler.source>
|
||||
<maven.compiler.target>21</maven.compiler.target>
|
||||
<assertj.version>3.26.3</assertj.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
@ -20,7 +20,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit</groupId>
|
||||
<artifactId>junit-bom</artifactId>
|
||||
<version>5.10.2</version>
|
||||
<version>5.11.0</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@ -31,7 +31,7 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>5.10.2</version>
|
||||
<version>5.11.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@ -44,18 +44,18 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.10.2</version>
|
||||
<version>5.11.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<version>3.17.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.5.0-M1</version>
|
||||
<version>4.5.0-M2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@ -63,7 +63,7 @@
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.2.5</version>
|
||||
<version>3.5.0</version>
|
||||
<configuration>
|
||||
<forkNode implementation="org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"/>
|
||||
</configuration>
|
||||
@ -71,10 +71,18 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.10.1</version>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<source>17</source>
|
||||
<target>17</target>
|
||||
<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>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@ -96,6 +104,56 @@
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-checkstyle-plugin</artifactId>
|
||||
<version>3.5.0</version>
|
||||
<configuration>
|
||||
<configLocation>checkstyle.xml</configLocation>
|
||||
<consoleOutput>true</consoleOutput>
|
||||
<includeTestSourceDirectory>true</includeTestSourceDirectory>
|
||||
<violationSeverity>warning</violationSeverity>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.puppycrawl.tools</groupId>
|
||||
<artifactId>checkstyle</artifactId>
|
||||
<version>10.18.1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.github.spotbugs</groupId>
|
||||
<artifactId>spotbugs-maven-plugin</artifactId>
|
||||
<version>4.8.6.3</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>
|
||||
</build>
|
||||
</project>
|
||||
|
217
spotbugs-exclude.xml
Normal file
217
spotbugs-exclude.xml
Normal file
@ -0,0 +1,217 @@
|
||||
<FindBugsFilter>
|
||||
<Match>
|
||||
<Bug pattern="DM_DEFAULT_ENCODING" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="EI_EXPOSE_REP2" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="DMI_RANDOM_USED_ONLY_ONCE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="SF_SWITCH_NO_DEFAULT" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="DM_NEXTINT_VIA_NEXTDOUBLE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="SIC_INNER_SHOULD_BE_STATIC" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="EI_EXPOSE_REP" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="EI_EXPOSE_REP" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="SBSC_USE_STRINGBUFFER_CONCATENATION" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="PA_PUBLIC_PRIMITIVE_ATTRIBUTE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="MS_PKGPROTECT" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="SE_COMPARATOR_SHOULD_BE_SERIALIZABLE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="INT_BAD_REM_BY_1" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="ICAST_IDIV_CAST_TO_DOUBLE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="FE_FLOATING_POINT_EQUALITY" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="CT_CONSTRUCTOR_THROW" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="URF_UNREAD_FIELD" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="RC_REF_COMPARISON" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="MS_EXPOSE_REP" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="DM_BOXED_PRIMITIVE_FOR_PARSING" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="UWF_UNWRITTEN_FIELD" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="UWF_NULL_FIELD" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="NP_UNWRITTEN_FIELD" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="NP_IMMEDIATE_DEREFERENCE_OF_READLINE" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="EQ_COMPARETO_USE_OBJECT_EQUALS" />
|
||||
</Match>
|
||||
<Match>
|
||||
<Bug pattern="SA_FIELD_SELF_ASSIGNMENT" />
|
||||
</Match>
|
||||
<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" />
|
||||
</Match>
|
||||
</FindBugsFilter>
|
@ -1,15 +1,14 @@
|
||||
/**
|
||||
* 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.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
@ -1,29 +1,42 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Finds all permutations of 1...n of length k
|
||||
* @author TheClerici (<a href="https://github.com/TheClerici">git-TheClerici</a>)
|
||||
* Finds all combinations of 0...n-1 of length k
|
||||
*/
|
||||
public class ArrayCombination {
|
||||
private static int length;
|
||||
public final class ArrayCombination {
|
||||
private ArrayCombination() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
public static List<TreeSet<Integer>> combination(int n, int k) {
|
||||
if (n <= 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.");
|
||||
}
|
||||
length = k;
|
||||
Integer[] arr = new Integer[n];
|
||||
for (int i = 1; i <= n; i++) {
|
||||
arr[i - 1] = i;
|
||||
|
||||
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
|
||||
}
|
||||
return Combination.combination(arr, length);
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,17 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* Finds all permutations of given array
|
||||
* @author Alan Piao (<a href="https://github.com/cpiao3">git-Alan Piao</a>)
|
||||
*/
|
||||
public class Combination {
|
||||
public final class Combination {
|
||||
private Combination() {
|
||||
}
|
||||
|
||||
private static int length;
|
||||
|
||||
@ -38,7 +43,9 @@ public 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]);
|
||||
|
@ -1,6 +1,8 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/*
|
||||
* Problem Statement: -
|
||||
@ -24,10 +26,12 @@ import java.util.*;
|
||||
51 46 55 44 53 4 21 12
|
||||
|
||||
*/
|
||||
public class KnightsTour {
|
||||
public final class KnightsTour {
|
||||
private 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},
|
||||
@ -41,19 +45,19 @@ public 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;
|
||||
|
||||
@ -95,7 +99,7 @@ public 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) {
|
||||
@ -109,7 +113,7 @@ public 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++;
|
||||
}
|
||||
|
@ -1,6 +1,10 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
@ -10,7 +14,9 @@ class Node {
|
||||
Set<Integer> edges = new HashSet<Integer>();
|
||||
}
|
||||
|
||||
public class MColoring {
|
||||
public final class MColoring {
|
||||
private MColoring() {
|
||||
}
|
||||
static int possiblePaint(ArrayList<Node> nodes, int n, int m) {
|
||||
|
||||
// Create a visited array of n nodes
|
||||
@ -53,7 +59,9 @@ public 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
|
||||
|
@ -1,6 +1,8 @@
|
||||
package com.thealgorithms.backtracking;
|
||||
|
||||
public class MazeRecursion {
|
||||
public final class MazeRecursion {
|
||||
private MazeRecursion() {
|
||||
}
|
||||
|
||||
public static void mazeRecursion() {
|
||||
// First create a 2 dimensions array to mimic a maze map
|
||||
|
@ -32,15 +32,14 @@ import java.util.List;
|
||||
* queen is not placed safely. If there is no such way then return an empty list
|
||||
* as solution
|
||||
*/
|
||||
public class NQueens {
|
||||
public final class NQueens {
|
||||
private NQueens() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
placeQueens(1);
|
||||
placeQueens(2);
|
||||
placeQueens(3);
|
||||
placeQueens(4);
|
||||
placeQueens(5);
|
||||
placeQueens(6);
|
||||
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 placeQueens(final int queens) {
|
||||
|
@ -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 nagative");
|
||||
throw new IllegalArgumentException("The number of pairs of parentheses cannot be negative");
|
||||
}
|
||||
List<String> result = new ArrayList<>();
|
||||
generateParenthesesHelper(result, "", 0, 0, n);
|
||||
|
@ -7,7 +7,9 @@ import java.util.List;
|
||||
* Finds all permutations of given array
|
||||
* @author Alan Piao (<a href="https://github.com/cpiao3">Git-Alan Piao</a>)
|
||||
*/
|
||||
public class Permutation {
|
||||
public final class Permutation {
|
||||
private Permutation() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all permutations of given array using backtracking
|
||||
|
@ -8,32 +8,33 @@ package com.thealgorithms.backtracking;
|
||||
*/
|
||||
public class PowerSum {
|
||||
|
||||
private int count = 0, sum = 0;
|
||||
private int count = 0;
|
||||
private int 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,54 @@
|
||||
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();
|
||||
}
|
||||
}
|
@ -51,7 +51,9 @@ 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;
|
||||
@ -66,7 +68,9 @@ 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ public final class HighestSetBit {
|
||||
private HighestSetBit() {
|
||||
}
|
||||
|
||||
public final static Optional<Integer> findHighestSetBit(int num) {
|
||||
public static Optional<Integer> findHighestSetBit(int num) {
|
||||
if (num < 0) {
|
||||
throw new IllegalArgumentException("Input cannot be negative");
|
||||
}
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public class IndexOfRightMostSetBit {
|
||||
public final class IndexOfRightMostSetBit {
|
||||
private IndexOfRightMostSetBit() {
|
||||
}
|
||||
public static int indexOfRightMostSetBit(int n) {
|
||||
if (n == 0) {
|
||||
return -1; // No set bits
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public class IsEven {
|
||||
public final class IsEven {
|
||||
private IsEven() {
|
||||
}
|
||||
public static boolean isEven(int number) {
|
||||
return (number & 1) == 0;
|
||||
}
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public class IsPowerTwo {
|
||||
public final class IsPowerTwo {
|
||||
private IsPowerTwo() {
|
||||
}
|
||||
public static boolean isPowerTwo(int number) {
|
||||
if (number <= 0) {
|
||||
return false;
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public class NonRepeatingNumberFinder {
|
||||
public final class NonRepeatingNumberFinder {
|
||||
private NonRepeatingNumberFinder() {
|
||||
}
|
||||
|
||||
public static int findNonRepeatingNumber(int[] arr) {
|
||||
int result = 0;
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi
|
||||
*/
|
||||
|
||||
public class NumbersDifferentSigns {
|
||||
public final class NumbersDifferentSigns {
|
||||
private NumbersDifferentSigns() {
|
||||
}
|
||||
|
||||
public static boolean differentSigns(int num1, int num2) {
|
||||
return (num1 ^ num2) < 0;
|
||||
|
@ -5,7 +5,9 @@ package com.thealgorithms.bitmanipulation;
|
||||
* @author Bama Charan Chhandogi
|
||||
*/
|
||||
|
||||
public class ReverseBits {
|
||||
public final class ReverseBits {
|
||||
private ReverseBits() {
|
||||
}
|
||||
|
||||
public static int reverseBits(int n) {
|
||||
int result = 0;
|
||||
|
@ -7,7 +7,9 @@ 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 class AES {
|
||||
public final class AES {
|
||||
private AES() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Precalculated values for x to the power of 2 in Rijndaels galois field.
|
||||
@ -2754,8 +2756,8 @@ public 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' -> {
|
||||
@ -2770,8 +2772,8 @@ public 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 **");
|
||||
|
@ -3,7 +3,12 @@ package com.thealgorithms.ciphers;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import javax.crypto.*;
|
||||
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.spec.GCMParameterSpec;
|
||||
|
||||
/**
|
||||
@ -12,7 +17,9 @@ import javax.crypto.spec.GCMParameterSpec;
|
||||
* hence in the following program we display it in hexadecimal format of the
|
||||
* underlying bytes.
|
||||
*/
|
||||
public class AESEncryption {
|
||||
public final class AESEncryption {
|
||||
private AESEncryption() {
|
||||
}
|
||||
|
||||
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
|
||||
private static Cipher aesCipher;
|
||||
|
@ -1,6 +1,8 @@
|
||||
package com.thealgorithms.ciphers;
|
||||
|
||||
class AffineCipher {
|
||||
final class AffineCipher {
|
||||
private AffineCipher() {
|
||||
}
|
||||
|
||||
// Key values of a and b
|
||||
static int a = 17;
|
||||
@ -25,7 +27,7 @@ class AffineCipher {
|
||||
|
||||
static String decryptCipher(String cipher) {
|
||||
String msg = "";
|
||||
int a_inv = 0;
|
||||
int aInv = 0;
|
||||
int flag = 0;
|
||||
|
||||
// Find a^-1 (the multiplicative inverse of a
|
||||
@ -36,7 +38,7 @@ class AffineCipher {
|
||||
// Check if (a*i)%26 == 1,
|
||||
// then i will be the multiplicative inverse of a
|
||||
if (flag == 1) {
|
||||
a_inv = i;
|
||||
aInv = i;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < cipher.length(); i++) {
|
||||
@ -44,7 +46,7 @@ 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) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
|
||||
msg = msg + (char) (((aInv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
|
||||
} else { // else simply append space character
|
||||
msg += cipher.charAt(i);
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ package com.thealgorithms.ciphers;
|
||||
public class Blowfish {
|
||||
|
||||
// Initializing substitution boxes
|
||||
String[][] S = {
|
||||
String[][] sBox = {
|
||||
{
|
||||
"d1310ba6",
|
||||
"98dfb5ac",
|
||||
@ -1047,7 +1047,7 @@ public class Blowfish {
|
||||
};
|
||||
|
||||
// Initializing subkeys with digits of pi
|
||||
String[] P = {
|
||||
String[] subKeys = {
|
||||
"243f6a88",
|
||||
"85a308d3",
|
||||
"13198a2e",
|
||||
@ -1104,7 +1104,9 @@ 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;
|
||||
}
|
||||
@ -1120,7 +1122,9 @@ 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;
|
||||
}
|
||||
@ -1154,7 +1158,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] = S[i / 2][(int) col];
|
||||
a[i / 2] = sBox[i / 2][(int) col];
|
||||
}
|
||||
ans = addBin(a[0], a[1]);
|
||||
ans = xor(ans, a[2]);
|
||||
@ -1165,9 +1169,9 @@ public class Blowfish {
|
||||
// generate subkeys
|
||||
private void keyGenerate(String key) {
|
||||
int j = 0;
|
||||
for (int i = 0; i < P.length; i++) {
|
||||
for (int i = 0; i < subKeys.length; i++) {
|
||||
// XOR-ing 32-bit parts of the key with initial subkeys
|
||||
P[i] = xor(P[i], key.substring(j, j + 8));
|
||||
subKeys[i] = xor(subKeys[i], key.substring(j, j + 8));
|
||||
|
||||
j = (j + 8) % key.length();
|
||||
}
|
||||
@ -1175,10 +1179,11 @@ public class Blowfish {
|
||||
|
||||
// round function
|
||||
private String round(int time, String plainText) {
|
||||
String left, right;
|
||||
String left;
|
||||
String right;
|
||||
left = plainText.substring(0, 8);
|
||||
right = plainText.substring(8, 16);
|
||||
left = xor(left, P[time]);
|
||||
left = xor(left, subKeys[time]);
|
||||
|
||||
// output from F function
|
||||
String fOut = f(left);
|
||||
@ -1201,13 +1206,15 @@ 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, P[16]);
|
||||
left = xor(left, P[17]);
|
||||
right = xor(right, subKeys[16]);
|
||||
left = xor(left, subKeys[17]);
|
||||
return left + right;
|
||||
}
|
||||
|
||||
@ -1223,13 +1230,15 @@ 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, P[1]);
|
||||
left = xor(left, P[0]);
|
||||
right = xor(right, subKeys[1]);
|
||||
left = xor(left, subKeys[0]);
|
||||
return left + right;
|
||||
}
|
||||
}
|
||||
|
@ -7,7 +7,9 @@ import java.util.Objects;
|
||||
*
|
||||
* @author <a href="https://github.com/freitzzz">freitzzz</a>
|
||||
*/
|
||||
public class ColumnarTranspositionCipher {
|
||||
public final class ColumnarTranspositionCipher {
|
||||
private ColumnarTranspositionCipher() {
|
||||
}
|
||||
|
||||
private static String keyword;
|
||||
private static Object[][] table;
|
||||
|
@ -8,7 +8,7 @@ package com.thealgorithms.ciphers;
|
||||
public class DES {
|
||||
|
||||
private String key;
|
||||
private String subKeys[];
|
||||
private final String[] subKeys;
|
||||
|
||||
private void sanitize(String key) {
|
||||
int length = key.length();
|
||||
@ -32,66 +32,68 @@ public class DES {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
// 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};
|
||||
// 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};
|
||||
|
||||
// Lookup table used to shift the initial key, in order to generate the subkeys
|
||||
private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
|
||||
private static final 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 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 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};
|
||||
|
||||
// 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};
|
||||
// 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};
|
||||
|
||||
// Expansion table to convert right half of message blocks from 32 bits to 48 bits
|
||||
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};
|
||||
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};
|
||||
|
||||
// The eight substitution boxes are defined below
|
||||
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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][] 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[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
|
||||
private static final int[][][] S = {S1, S2, S3, S4, S5, S6, S7, S8};
|
||||
|
||||
// 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};
|
||||
// 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};
|
||||
|
||||
// Table used for final inversion of the message box after 16 rounds of Feistel Function
|
||||
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};
|
||||
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};
|
||||
|
||||
private String[] getSubkeys(String originalKey) {
|
||||
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
|
||||
int i, j;
|
||||
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via pc1
|
||||
int i;
|
||||
int 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), D0 = initialPermutedKey.substring(28);
|
||||
String c0 = initialPermutedKey.substring(0, 28);
|
||||
String 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);
|
||||
@ -104,8 +106,9 @@ public class DES {
|
||||
return subKeys;
|
||||
}
|
||||
|
||||
private String XOR(String a, String b) {
|
||||
int i, l = a.length();
|
||||
private String xOR(String a, String b) {
|
||||
int i;
|
||||
int l = a.length();
|
||||
StringBuilder xor = new StringBuilder();
|
||||
for (i = 0; i < l; i++) {
|
||||
int firstBit = a.charAt(i) - 48; // 48 is '0' in ascii
|
||||
@ -116,7 +119,8 @@ public class DES {
|
||||
}
|
||||
|
||||
private String createPaddedString(String s, int desiredLength, char pad) {
|
||||
int i, l = s.length();
|
||||
int i;
|
||||
int l = s.length();
|
||||
StringBuilder paddedString = new StringBuilder();
|
||||
int diff = desiredLength - l;
|
||||
for (i = 0; i < diff; i++) {
|
||||
@ -137,9 +141,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
|
||||
@ -147,45 +151,46 @@ 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 L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32);
|
||||
String e0 = permutedMessage.substring(0, 32);
|
||||
String f0 = permutedMessage.substring(32);
|
||||
|
||||
// Iterate 16 times
|
||||
for (i = 0; i < 16; i++) {
|
||||
String Ln = R0; // Previous Right block
|
||||
String Rn = XOR(L0, feistel(R0, keys[i]));
|
||||
L0 = Ln;
|
||||
R0 = Rn;
|
||||
String eN = f0; // Previous Right block
|
||||
String fN = xOR(e0, feistel(f0, keys[i]));
|
||||
e0 = eN;
|
||||
f0 = fN;
|
||||
}
|
||||
|
||||
String combinedBlock = R0 + L0; // Reverse the 16th block
|
||||
String combinedBlock = f0 + e0; // Reverse the 16th block
|
||||
permutedMessage.setLength(0);
|
||||
for (i = 0; i < 64; i++) {
|
||||
permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1));
|
||||
permutedMessage.append(combinedBlock.charAt(IP_INVERSE[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];
|
||||
}
|
||||
@ -198,7 +203,9 @@ public class DES {
|
||||
*/
|
||||
public String encrypt(String message) {
|
||||
StringBuilder encryptedMessage = new StringBuilder();
|
||||
int l = message.length(), i, j;
|
||||
int l = message.length();
|
||||
int i;
|
||||
int j;
|
||||
if (l % 8 != 0) {
|
||||
int desiredLength = (l / 8 + 1) * 8;
|
||||
l = desiredLength;
|
||||
@ -223,14 +230,16 @@ public class DES {
|
||||
*/
|
||||
public String decrypt(String message) {
|
||||
StringBuilder decryptedMessage = new StringBuilder();
|
||||
int l = message.length(), i, j;
|
||||
int l = message.length();
|
||||
int i;
|
||||
int 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.toString(), subKeys);
|
||||
byte res[] = new byte[8];
|
||||
String result = decryptBlock(block, 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);
|
||||
}
|
||||
|
@ -11,7 +11,9 @@ import java.util.Scanner;
|
||||
* for encryption. The cipher key and plaintext/ciphertext are user inputs.
|
||||
* @author Ojasva Jain
|
||||
*/
|
||||
public class HillCipher {
|
||||
public final class HillCipher {
|
||||
private HillCipher() {
|
||||
}
|
||||
|
||||
static Scanner userInput = new Scanner(System.in);
|
||||
|
||||
@ -33,7 +35,7 @@ public 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()) {
|
||||
@ -46,7 +48,8 @@ public class HillCipher {
|
||||
System.out.println(messageVector[i][0]);
|
||||
j++;
|
||||
}
|
||||
int x, i;
|
||||
int x;
|
||||
int i;
|
||||
for (i = 0; i < matrixSize; i++) {
|
||||
cipherMatrix[i][0] = 0;
|
||||
|
||||
@ -57,10 +60,10 @@ public 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
|
||||
@ -81,7 +84,7 @@ public 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()) {
|
||||
@ -94,7 +97,8 @@ public class HillCipher {
|
||||
System.out.println(messageVector[i][0]);
|
||||
j++;
|
||||
}
|
||||
int x, i;
|
||||
int x;
|
||||
int i;
|
||||
for (i = 0; i < n; i++) {
|
||||
plainMatrix[i][0] = 0;
|
||||
|
||||
@ -105,15 +109,18 @@ public 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, sign = 1, p = 0, q = 0;
|
||||
int det = 0;
|
||||
int sign = 1;
|
||||
int p = 0;
|
||||
int q = 0;
|
||||
|
||||
if (n == 1) {
|
||||
det = a[0][0];
|
||||
@ -142,7 +149,6 @@ public 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");
|
||||
|
@ -13,9 +13,11 @@ package com.thealgorithms.ciphers;
|
||||
* @author Hikmet ÇAKIR
|
||||
* @since 08-07-2022+03:00
|
||||
*/
|
||||
public class Polybius {
|
||||
public final class Polybius {
|
||||
private 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'},
|
||||
@ -26,9 +28,9 @@ public 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;
|
||||
}
|
||||
@ -53,7 +55,7 @@ public 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();
|
||||
}
|
||||
|
@ -2,7 +2,9 @@ package com.thealgorithms.ciphers;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
class ProductCipher {
|
||||
final class ProductCipher {
|
||||
private ProductCipher() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (Scanner sc = new Scanner(System.in)) {
|
||||
@ -24,8 +26,8 @@ class ProductCipher {
|
||||
|
||||
// Transposition encryption
|
||||
String transpositionInput = substitutionOutput.toString();
|
||||
int modulus;
|
||||
if ((modulus = transpositionInput.length() % n) != 0) {
|
||||
int modulus = transpositionInput.length() % n;
|
||||
if (modulus != 0) {
|
||||
modulus = n - modulus;
|
||||
|
||||
for (; modulus != 0; modulus--) {
|
||||
@ -66,7 +68,6 @@ class ProductCipher {
|
||||
|
||||
System.out.println("Plaintext: ");
|
||||
System.out.println(plaintext);
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -47,7 +47,7 @@ public class RSA {
|
||||
/**
|
||||
* Generate a new public and private key set.
|
||||
*/
|
||||
public synchronized void generateKeys(int bits) {
|
||||
public final 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);
|
||||
|
@ -31,7 +31,9 @@ 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) {
|
||||
|
@ -19,17 +19,19 @@ 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(false, 0);
|
||||
bitCount.put(true, 0);
|
||||
bitCount.put(Boolean.FALSE, 0);
|
||||
bitCount.put(Boolean.TRUE, 0);
|
||||
|
||||
registers.forEach(lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
|
||||
return bitCount.get(false) <= bitCount.get(true);
|
||||
return bitCount.get(Boolean.FALSE) <= bitCount.get(Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
|
@ -7,7 +7,9 @@ package com.thealgorithms.ciphers.a5;
|
||||
|
||||
import java.util.BitSet;
|
||||
|
||||
public class Utils {
|
||||
public final class Utils {
|
||||
private Utils() {
|
||||
}
|
||||
|
||||
public static boolean increment(BitSet bits, int size) {
|
||||
int i = size - 1;
|
||||
|
@ -0,0 +1,23 @@
|
||||
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);
|
||||
}
|
||||
}
|
@ -13,7 +13,9 @@ import java.util.Scanner;
|
||||
* @author Michael Rolland
|
||||
* @version 2017.10.10
|
||||
*/
|
||||
public class AnyBaseToAnyBase {
|
||||
public final class AnyBaseToAnyBase {
|
||||
private AnyBaseToAnyBase() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Smallest and largest base you want to accept as valid input
|
||||
@ -25,7 +27,8 @@ public class AnyBaseToAnyBase {
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
String n;
|
||||
int b1, b2;
|
||||
int b1;
|
||||
int b2;
|
||||
while (true) {
|
||||
try {
|
||||
System.out.print("Enter number: ");
|
||||
@ -130,7 +133,8 @@ public 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, charB2;
|
||||
int decimalValue = 0;
|
||||
int charB2;
|
||||
char charB1;
|
||||
String output = "";
|
||||
// Go through every character of n
|
||||
|
@ -3,52 +3,50 @@ package com.thealgorithms.conversions;
|
||||
/**
|
||||
* @author Varun Upadhyay (<a href="https://github.com/varunu28">...</a>)
|
||||
*/
|
||||
// Driver program
|
||||
public class AnyBaseToDecimal {
|
||||
public final class AnyBaseToDecimal {
|
||||
private static final int CHAR_OFFSET_FOR_DIGIT = '0';
|
||||
private static final int CHAR_OFFSET_FOR_UPPERCASE = 'A' - 10;
|
||||
|
||||
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);
|
||||
private AnyBaseToDecimal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert any radix to decimal number
|
||||
* Convert any radix to a decimal number.
|
||||
*
|
||||
* @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
|
||||
* @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
|
||||
*/
|
||||
public static int convertToDecimal(String s, int radix) {
|
||||
int num = 0;
|
||||
int pow = 1;
|
||||
public static int convertToDecimal(String input, int radix) {
|
||||
int result = 0;
|
||||
int power = 1;
|
||||
|
||||
for (int i = s.length() - 1; i >= 0; i--) {
|
||||
int digit = valOfChar(s.charAt(i));
|
||||
for (int i = input.length() - 1; i >= 0; i--) {
|
||||
int digit = valOfChar(input.charAt(i));
|
||||
if (digit >= radix) {
|
||||
throw new NumberFormatException("For input string " + s);
|
||||
throw new NumberFormatException("For input string: " + input);
|
||||
}
|
||||
num += valOfChar(s.charAt(i)) * pow;
|
||||
pow *= radix;
|
||||
result += digit * power;
|
||||
power *= radix;
|
||||
}
|
||||
return num;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert character to integer
|
||||
* Convert a character to its integer value.
|
||||
*
|
||||
* @param c the character
|
||||
* @return represented digit of given character
|
||||
* @throws NumberFormatException if {@code ch} is not UpperCase or Digit
|
||||
* character.
|
||||
* @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
|
||||
*/
|
||||
public static int valOfChar(char c) {
|
||||
if (!(Character.isUpperCase(c) || Character.isDigit(c))) {
|
||||
throw new NumberFormatException("invalid character :" + c);
|
||||
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);
|
||||
}
|
||||
return Character.isDigit(c) ? c - '0' : c - 'A' + 10;
|
||||
}
|
||||
}
|
||||
|
@ -6,14 +6,18 @@ import java.util.Scanner;
|
||||
// number.
|
||||
// sn ,sb,db ---> ()dn . this is what we have to do .
|
||||
|
||||
public class AnytoAny {
|
||||
public final class AnytoAny {
|
||||
private 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, dec = 0, dn = 0;
|
||||
int m = 1;
|
||||
int dec = 0;
|
||||
int dn = 0;
|
||||
while (sn != 0) {
|
||||
dec = dec + (sn % 10) * m;
|
||||
m *= sb;
|
||||
|
@ -1,32 +1,33 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Binary number to a Decimal number
|
||||
*/
|
||||
class BinaryToDecimal {
|
||||
final class BinaryToDecimal {
|
||||
private static final int BINARY_BASE = 2;
|
||||
|
||||
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;
|
||||
private BinaryToDecimal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
* Converts a binary number to its decimal equivalent.
|
||||
*
|
||||
* @param args Command line arguments
|
||||
* @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.
|
||||
*/
|
||||
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();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,57 +1,63 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Converts any Binary Number to a Hexadecimal Number
|
||||
*
|
||||
* @author Nishita Aggarwal
|
||||
*/
|
||||
public class BinaryToHexadecimal {
|
||||
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;
|
||||
|
||||
/**
|
||||
* This method converts a binary number to a hexadecimal number.
|
||||
*
|
||||
* @param binary The binary number
|
||||
* @return The hexadecimal number
|
||||
*/
|
||||
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 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 = hm.get(code4) + hex;
|
||||
}
|
||||
return hex;
|
||||
private BinaryToHexadecimal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
* Converts a binary number to a hexadecimal number.
|
||||
*
|
||||
* @param args Command line arguments
|
||||
* @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.
|
||||
*/
|
||||
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();
|
||||
public static String binToHex(int binary) {
|
||||
Map<Integer, String> hexMap = initializeHexMap();
|
||||
StringBuilder hex = new StringBuilder();
|
||||
|
||||
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));
|
||||
}
|
||||
hex.insert(0, hexMap.get(decimalValue));
|
||||
}
|
||||
|
||||
return !hex.isEmpty() ? hex.toString() : "0";
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the hexadecimal map with decimal to hexadecimal mappings.
|
||||
*
|
||||
* @return The initialized map containing mappings from decimal numbers to hexadecimal digits.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,25 +1,11 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
private BinaryToOctal() {
|
||||
}
|
||||
|
||||
/**
|
||||
@ -27,21 +13,33 @@ public 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) {
|
||||
String octal = "";
|
||||
int currBit = 0, j = 1;
|
||||
while (binary != 0) {
|
||||
int code3 = 0;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
currBit = binary % 10;
|
||||
binary = binary / 10;
|
||||
code3 += currBit * j;
|
||||
j *= 2;
|
||||
}
|
||||
octal = code3 + octal;
|
||||
j = 1;
|
||||
if (binary == 0) {
|
||||
return "0";
|
||||
}
|
||||
return octal;
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
octal.insert(0, octalDigit);
|
||||
bitValueMultiplier = 1; // Reset multiplier for the next group
|
||||
}
|
||||
|
||||
return octal.toString();
|
||||
}
|
||||
}
|
||||
|
@ -1,67 +1,69 @@
|
||||
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>)
|
||||
*/
|
||||
// Driver Program
|
||||
public class DecimalToAnyBase {
|
||||
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;
|
||||
|
||||
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();
|
||||
private DecimalToAnyBase() {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces a String value of any given input decimal in any
|
||||
* base
|
||||
* 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".
|
||||
*
|
||||
* @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
|
||||
* @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
|
||||
*/
|
||||
public static String convertToAnyBase(int inp, int base) {
|
||||
ArrayList<Character> charArr = new ArrayList<>();
|
||||
|
||||
while (inp > 0) {
|
||||
charArr.add(reVal(inp % base));
|
||||
inp /= 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);
|
||||
}
|
||||
|
||||
StringBuilder str = new StringBuilder(charArr.size());
|
||||
|
||||
for (Character ch : charArr) {
|
||||
str.append(ch);
|
||||
if (decimal == 0) {
|
||||
return String.valueOf(ZERO_CHAR);
|
||||
}
|
||||
|
||||
return str.reverse().toString();
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method produces character value of the input integer and returns it
|
||||
* 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'.
|
||||
*
|
||||
* @param num integer of which we need the character value of
|
||||
* @return character value of input integer
|
||||
* @param value the integer value to convert (should be less than the base value)
|
||||
* @return the character representing the value in the specified base
|
||||
*/
|
||||
public static char reVal(int num) {
|
||||
if (num >= 0 && num <= 9) {
|
||||
return (char) (num + '0');
|
||||
private static char convertToChar(int value) {
|
||||
if (value >= 0 && value <= 9) {
|
||||
return (char) (ZERO_CHAR + value);
|
||||
} else {
|
||||
return (char) (num - 10 + 'A');
|
||||
return (char) (A_CHAR + value - DIGIT_OFFSET);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,55 +1,49 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts a Decimal number to a Binary number
|
||||
* This class provides methods to convert a decimal number to a binary number.
|
||||
*/
|
||||
class DecimalToBinary {
|
||||
final class DecimalToBinary {
|
||||
private static final int BINARY_BASE = 2;
|
||||
private static final int DECIMAL_MULTIPLIER = 10;
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
*
|
||||
* @param args Command Line Arguments
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
conventionalConversion();
|
||||
bitwiseConversion();
|
||||
private DecimalToBinary() {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a decimal number to a binary number using a
|
||||
* conventional algorithm.
|
||||
* 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
|
||||
*/
|
||||
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();
|
||||
}
|
||||
public static int convertUsingConventionalAlgorithm(int decimalNumber) {
|
||||
int binaryNumber = 0;
|
||||
int position = 1;
|
||||
|
||||
/**
|
||||
* This method converts a decimal number to a binary number using a bitwise
|
||||
* algorithm
|
||||
*/
|
||||
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;
|
||||
while (decimalNumber > 0) {
|
||||
int remainder = decimalNumber % BINARY_BASE;
|
||||
binaryNumber += remainder * position;
|
||||
position *= DECIMAL_MULTIPLIER;
|
||||
decimalNumber /= BINARY_BASE;
|
||||
}
|
||||
System.out.println("\tBinary number: " + b);
|
||||
input.close();
|
||||
|
||||
return binaryNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
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;
|
||||
}
|
||||
return binaryNumber;
|
||||
}
|
||||
}
|
||||
|
@ -1,49 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
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);
|
||||
}
|
||||
}
|
@ -1,32 +1,38 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* This class converts Decimal numbers to Octal Numbers
|
||||
*/
|
||||
public class DecimalToOctal {
|
||||
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() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Main Method
|
||||
* Converts a decimal number to its octal equivalent.
|
||||
*
|
||||
* @param args Command line Arguments
|
||||
* @param decimal The decimal number to convert.
|
||||
* @return The octal equivalent as an integer.
|
||||
* @throws IllegalArgumentException if the decimal number is 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;
|
||||
public static int convertToOctal(int decimal) {
|
||||
if (decimal < 0) {
|
||||
throw new IllegalArgumentException("Decimal number cannot be negative.");
|
||||
}
|
||||
|
||||
System.out.println("Octal equivalent:" + s);
|
||||
sc.close();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,72 +1,62 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Hexadecimal Number to Octal
|
||||
*
|
||||
* @author Tanmay Joshi
|
||||
*/
|
||||
public class HexToOct {
|
||||
|
||||
/**
|
||||
* This method converts a Hexadecimal number to a decimal number
|
||||
*
|
||||
* @param s The Hexadecimal Number
|
||||
* @return The Decimal number
|
||||
*/
|
||||
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 val;
|
||||
public final class HexToOct {
|
||||
private HexToOct() {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a Decimal number to a octal number
|
||||
* Converts a Hexadecimal number to a Decimal number.
|
||||
*
|
||||
* @param q The Decimal Number
|
||||
* @return The Octal number
|
||||
* @param hex The Hexadecimal number as a String.
|
||||
* @return The Decimal equivalent as an integer.
|
||||
*/
|
||||
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++;
|
||||
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;
|
||||
}
|
||||
octnum /= 10;
|
||||
return octnum;
|
||||
|
||||
return decimalValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method that gets the hex input from user and converts it into octal.
|
||||
* Converts a Decimal number to an Octal number.
|
||||
*
|
||||
* @param args arguments
|
||||
* @param decimal The Decimal number as an integer.
|
||||
* @return The Octal equivalent as an integer.
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
String hexadecnum;
|
||||
int decnum, octalnum;
|
||||
Scanner scan = new Scanner(System.in);
|
||||
public static int decimalToOctal(int decimal) {
|
||||
int octalValue = 0;
|
||||
int placeValue = 1;
|
||||
|
||||
System.out.print("Enter Hexadecimal Number : ");
|
||||
hexadecnum = scan.nextLine();
|
||||
while (decimal > 0) {
|
||||
int remainder = decimal % 8;
|
||||
octalValue += remainder * placeValue;
|
||||
decimal /= 8;
|
||||
placeValue *= 10;
|
||||
}
|
||||
|
||||
// first convert hexadecimal to decimal
|
||||
decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
|
||||
// variable decnum
|
||||
return octalValue;
|
||||
}
|
||||
|
||||
// convert decimal to octal
|
||||
octalnum = decimal2octal(decnum);
|
||||
System.out.println("Number in octal: " + octalnum);
|
||||
scan.close();
|
||||
/**
|
||||
* Converts a Hexadecimal number to an Octal number.
|
||||
*
|
||||
* @param hex The Hexadecimal number as a String.
|
||||
* @return The Octal equivalent as an integer.
|
||||
*/
|
||||
public static int hexToOctal(String hex) {
|
||||
int decimalValue = hexToDecimal(hex);
|
||||
return decimalToOctal(decimalValue);
|
||||
}
|
||||
}
|
||||
|
@ -2,9 +2,6 @@ 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);
|
||||
@ -15,7 +12,8 @@ public class HexaDecimalToBinary {
|
||||
}
|
||||
|
||||
public String completeDigits(String binNum) {
|
||||
for (int i = binNum.length(); i < LONG_BITS; i++) {
|
||||
final int longBits = 8;
|
||||
for (int i = binNum.length(); i < longBits; i++) {
|
||||
binNum = "0" + binNum;
|
||||
}
|
||||
return binNum;
|
||||
|
@ -2,7 +2,9 @@ package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class HexaDecimalToDecimal {
|
||||
public final class HexaDecimalToDecimal {
|
||||
private HexaDecimalToDecimal() {
|
||||
}
|
||||
|
||||
// convert hexadecimal to decimal
|
||||
public static int getHexaToDec(String hex) {
|
||||
@ -18,20 +20,20 @@ public class HexaDecimalToDecimal {
|
||||
|
||||
// Main method gets the hexadecimal input from user and converts it into Decimal output.
|
||||
public static void main(String[] args) {
|
||||
String hexa_Input;
|
||||
int dec_output;
|
||||
String hexaInput;
|
||||
int decOutput;
|
||||
Scanner scan = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter Hexadecimal Number : ");
|
||||
hexa_Input = scan.nextLine();
|
||||
hexaInput = scan.nextLine();
|
||||
|
||||
// convert hexadecimal to decimal
|
||||
dec_output = getHexaToDec(hexa_Input);
|
||||
decOutput = getHexaToDec(hexaInput);
|
||||
/*
|
||||
Pass the string to the getHexaToDec function
|
||||
and it returns the decimal form in the variable dec_output.
|
||||
and it returns the decimal form in the variable decOutput.
|
||||
*/
|
||||
System.out.println("Number in Decimal: " + dec_output);
|
||||
System.out.println("Number in Decimal: " + decOutput);
|
||||
scan.close();
|
||||
}
|
||||
}
|
||||
|
@ -7,9 +7,11 @@ 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 class IntegerToRoman {
|
||||
public final class IntegerToRoman {
|
||||
private IntegerToRoman() {
|
||||
}
|
||||
|
||||
private static final int[] allArabianRomanNumbers = new int[] {
|
||||
private static final int[] ALL_ROMAN_NUMBERS_IN_ARABIC = new int[] {
|
||||
1000,
|
||||
900,
|
||||
500,
|
||||
@ -24,7 +26,7 @@ public class IntegerToRoman {
|
||||
4,
|
||||
1,
|
||||
};
|
||||
private static final String[] allRomanNumbers = new String[] {
|
||||
private static final String[] ALL_ROMAN_NUMBERS = new String[] {
|
||||
"M",
|
||||
"CM",
|
||||
"D",
|
||||
@ -48,13 +50,13 @@ public class IntegerToRoman {
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
for (int a = 0; a < allArabianRomanNumbers.length; a++) {
|
||||
int times = num / allArabianRomanNumbers[a];
|
||||
for (int a = 0; a < ALL_ROMAN_NUMBERS_IN_ARABIC.length; a++) {
|
||||
int times = num / ALL_ROMAN_NUMBERS_IN_ARABIC[a];
|
||||
for (int b = 0; b < times; b++) {
|
||||
builder.append(allRomanNumbers[a]);
|
||||
builder.append(ALL_ROMAN_NUMBERS[a]);
|
||||
}
|
||||
|
||||
num -= times * allArabianRomanNumbers[a];
|
||||
num -= times * ALL_ROMAN_NUMBERS_IN_ARABIC[a];
|
||||
}
|
||||
|
||||
return builder.toString();
|
||||
|
@ -6,7 +6,9 @@ package com.thealgorithms.conversions;
|
||||
* @author Bama Charan Chhandogi
|
||||
*/
|
||||
|
||||
public class OctalToBinary {
|
||||
public final class OctalToBinary {
|
||||
private OctalToBinary() {
|
||||
}
|
||||
public static long convertOctalToBinary(int octalNumber) {
|
||||
long binaryNumber = 0;
|
||||
int digitPosition = 1;
|
||||
|
@ -1,45 +1,42 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal Number to a Decimal Number
|
||||
* Class for converting an octal number to a decimal number. Octal numbers are based on 8, using digits from 0 to 7.
|
||||
*
|
||||
* @author Zachary Jones
|
||||
*/
|
||||
public class OctalToDecimal {
|
||||
public final class OctalToDecimal {
|
||||
private static final int OCTAL_BASE = 8;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
private OctalToDecimal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts an octal number to a decimal number.
|
||||
* 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.
|
||||
*
|
||||
* @param inputOctal The octal number
|
||||
* @return The 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
|
||||
*/
|
||||
public static int convertOctalToDecimal(String inputOctal) {
|
||||
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;
|
||||
if (inputOctal == null || inputOctal.isEmpty()) {
|
||||
throw new IllegalArgumentException("Input cannot be null or empty");
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
@ -1,63 +1,61 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
/**
|
||||
* Converts any Octal Number to HexaDecimal
|
||||
* Class for converting an Octal number to its Hexadecimal equivalent.
|
||||
*
|
||||
* @author Tanmay Joshi
|
||||
*/
|
||||
public class OctalToHexadecimal {
|
||||
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";
|
||||
|
||||
/**
|
||||
* 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;
|
||||
private OctalToHexadecimal() {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method converts a Decimal number to a Hexadecimal number
|
||||
* Converts an Octal number (as a string) to its Decimal equivalent.
|
||||
*
|
||||
* @param d The Decimal Number
|
||||
* @return The 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
|
||||
*/
|
||||
public static String decimalToHex(int d) {
|
||||
String digits = "0123456789ABCDEF";
|
||||
if (d <= 0) {
|
||||
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) {
|
||||
return "0";
|
||||
}
|
||||
String hex = "";
|
||||
while (d > 0) {
|
||||
int digit = d % 16;
|
||||
hex = digits.charAt(digit) + hex;
|
||||
d = d / 16;
|
||||
|
||||
StringBuilder hexValue = new StringBuilder();
|
||||
while (decimalNumber > 0) {
|
||||
int digit = decimalNumber % HEX_BASE;
|
||||
hexValue.insert(0, HEX_DIGITS.charAt(digit));
|
||||
decimalNumber /= HEX_BASE;
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
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();
|
||||
return hexValue.toString();
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,9 @@ 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 class RgbHsvConversion {
|
||||
public final class RgbHsvConversion {
|
||||
private RgbHsvConversion() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
|
||||
|
@ -1,12 +1,13 @@
|
||||
package com.thealgorithms.conversions;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class RomanToInteger {
|
||||
|
||||
private static final Map<Character, Integer> map = new HashMap<>() {
|
||||
private static final long serialVersionUID = 87605733047260530L;
|
||||
public final class RomanToInteger {
|
||||
private RomanToInteger() {
|
||||
}
|
||||
|
||||
private static final Map<Character, Integer> ROMAN_TO_INT = new HashMap<>() {
|
||||
{
|
||||
put('I', 1);
|
||||
put('V', 5);
|
||||
@ -23,31 +24,31 @@ public 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 then previous or not
|
||||
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
|
||||
// checking current Number greater than previous or not
|
||||
newPrev = ROMAN_TO_INT.get(prev) > newPrev ? ROMAN_TO_INT.get(prev) : newPrev;
|
||||
}
|
||||
|
||||
int currentNum = map.get(c);
|
||||
int currentNum = ROMAN_TO_INT.get(c);
|
||||
|
||||
// if current number greater then prev max previous then add
|
||||
// if current number greater than prev max previous then add
|
||||
if (currentNum >= newPrev) {
|
||||
sum += currentNum;
|
||||
} else {
|
||||
// subtract upcoming number until upcoming number not greater then prev max
|
||||
// subtract upcoming number until upcoming number not greater than prev max
|
||||
sum -= currentNum;
|
||||
}
|
||||
|
||||
|
@ -7,7 +7,9 @@ import java.util.Scanner;
|
||||
*
|
||||
* @author Özgün Gökşenli
|
||||
*/
|
||||
public class TurkishToLatinConversion {
|
||||
public final class TurkishToLatinConversion {
|
||||
private TurkishToLatinConversion() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Main method
|
||||
|
@ -0,0 +1,14 @@
|
||||
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))));
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -4,23 +4,23 @@ import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* Collection which does not allow removing elements (only collect and iterate)
|
||||
* A collection that allows adding and iterating over elements but does not support element removal.
|
||||
*
|
||||
* @param <Element> - the generic type of an element in this bag
|
||||
* @param <E> the type of elements in this bag
|
||||
*/
|
||||
public class Bag<Element> implements Iterable<Element> {
|
||||
public class Bag<E> implements Iterable<E> {
|
||||
|
||||
private Node<Element> firstElement; // first element of the bag
|
||||
private int size; // size of bag
|
||||
private Node<E> firstElement; // First element in the bag
|
||||
private int size; // Number of elements in the bag
|
||||
|
||||
private static class Node<Element> {
|
||||
|
||||
private Element content;
|
||||
private Node<Element> nextElement;
|
||||
// Node class representing each element in the bag
|
||||
private static final class Node<E> {
|
||||
private E content;
|
||||
private Node<E> nextElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an empty bag
|
||||
* Constructs an empty bag.
|
||||
*/
|
||||
public Bag() {
|
||||
firstElement = null;
|
||||
@ -28,13 +28,17 @@ public class Bag<Element> implements Iterable<Element> {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if this bag is empty, false otherwise
|
||||
* Checks if the bag is empty.
|
||||
*
|
||||
* @return true if the bag is empty, false otherwise
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return firstElement == null;
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of elements in the bag.
|
||||
*
|
||||
* @return the number of elements
|
||||
*/
|
||||
public int size() {
|
||||
@ -42,24 +46,26 @@ public class Bag<Element> implements Iterable<Element> {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param element - the element to add
|
||||
* Adds an element to the bag.
|
||||
*
|
||||
* @param element the element to add
|
||||
*/
|
||||
public void add(Element element) {
|
||||
Node<Element> oldfirst = firstElement;
|
||||
firstElement = new Node<>();
|
||||
firstElement.content = element;
|
||||
firstElement.nextElement = oldfirst;
|
||||
public void add(E element) {
|
||||
Node<E> newNode = new Node<>();
|
||||
newNode.content = element;
|
||||
newNode.nextElement = firstElement;
|
||||
firstElement = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the bag contains a specific element
|
||||
* Checks if the bag contains a specific element.
|
||||
*
|
||||
* @param element which you want to look for
|
||||
* @return true if bag contains element, otherwise false
|
||||
* @param element the element to check for
|
||||
* @return true if the bag contains the element, false otherwise
|
||||
*/
|
||||
public boolean contains(Element element) {
|
||||
for (Element value : this) {
|
||||
public boolean contains(E element) {
|
||||
for (E value : this) {
|
||||
if (value.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
@ -68,61 +74,37 @@ public class Bag<Element> implements Iterable<Element> {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return an iterator that iterates over the elements in this bag in
|
||||
* arbitrary order
|
||||
* Returns an iterator over the elements in this bag.
|
||||
*
|
||||
* @return an iterator that iterates over the elements in the bag
|
||||
*/
|
||||
public Iterator<Element> iterator() {
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new ListIterator<>(firstElement);
|
||||
}
|
||||
|
||||
@SuppressWarnings("hiding")
|
||||
private class ListIterator<Element> implements Iterator<Element> {
|
||||
// Private class for iterating over elements
|
||||
private static class ListIterator<E> implements Iterator<E> {
|
||||
|
||||
private Node<Element> currentElement;
|
||||
private Node<E> currentElement;
|
||||
|
||||
public ListIterator(Node<Element> firstElement) {
|
||||
currentElement = firstElement;
|
||||
ListIterator(Node<E> firstElement) {
|
||||
this.currentElement = firstElement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return currentElement != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* remove is not allowed in a bag
|
||||
*/
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Element next() {
|
||||
public E next() {
|
||||
if (!hasNext()) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
Element element = currentElement.content;
|
||||
E 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"));
|
||||
}
|
||||
}
|
||||
|
@ -2,35 +2,61 @@ 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 int numberOfHashFunctions;
|
||||
private BitSet bitArray;
|
||||
private Hash<T>[] hashFunctions;
|
||||
private final int numberOfHashFunctions;
|
||||
private final BitSet bitArray;
|
||||
private final Hash<T>[] hashFunctions;
|
||||
|
||||
public BloomFilter(int numberOfHashFunctions, int n) {
|
||||
/**
|
||||
* 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) {
|
||||
this.numberOfHashFunctions = numberOfHashFunctions;
|
||||
hashFunctions = new Hash[numberOfHashFunctions];
|
||||
bitArray = new BitSet(n);
|
||||
insertHash();
|
||||
this.bitArray = new BitSet(bitArraySize);
|
||||
this.hashFunctions = new Hash[numberOfHashFunctions];
|
||||
initializeHashFunctions();
|
||||
}
|
||||
|
||||
private void insertHash() {
|
||||
/**
|
||||
* Initializes the hash functions with unique indices.
|
||||
*/
|
||||
private void initializeHashFunctions() {
|
||||
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 = hash.compute(key) % bitArray.size();
|
||||
int position = Math.abs(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 = hash.compute(key) % bitArray.size();
|
||||
int position = Math.abs(hash.compute(key) % bitArray.size());
|
||||
if (!bitArray.get(position)) {
|
||||
return false;
|
||||
}
|
||||
@ -38,24 +64,46 @@ public class BloomFilter<T> {
|
||||
return true;
|
||||
}
|
||||
|
||||
private class Hash<T> {
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
int index;
|
||||
private final int index;
|
||||
|
||||
public Hash(int index) {
|
||||
/**
|
||||
* Constructs a Hash function with a specified index.
|
||||
*
|
||||
* @param index the index of this hash function
|
||||
*/
|
||||
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 number = 0;
|
||||
for (int i = 0; i < word.length(); i++) {
|
||||
number += word.charAt(i);
|
||||
int sum = 0;
|
||||
for (char c : word.toCharArray()) {
|
||||
sum += c;
|
||||
}
|
||||
return number;
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -24,7 +24,9 @@ public class CircularBuffer<Item> {
|
||||
}
|
||||
|
||||
public Item get() {
|
||||
if (isEmpty()) return null;
|
||||
if (isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Item item = buffer[getPointer.getAndIncrement()];
|
||||
size.decrementAndGet();
|
||||
@ -32,7 +34,9 @@ public class CircularBuffer<Item> {
|
||||
}
|
||||
|
||||
public boolean put(Item item) {
|
||||
if (isFull()) return false;
|
||||
if (isFull()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
buffer[putPointer.getAndIncrement()] = item;
|
||||
size.incrementAndGet();
|
||||
@ -43,13 +47,15 @@ public class CircularBuffer<Item> {
|
||||
private int pointer;
|
||||
private final int max;
|
||||
|
||||
public CircularPointer(int pointer, int max) {
|
||||
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;
|
||||
|
@ -10,14 +10,13 @@ import java.util.Map;
|
||||
public class LFUCache<K, V> {
|
||||
|
||||
private class Node {
|
||||
|
||||
private K key;
|
||||
private final K key;
|
||||
private V value;
|
||||
private int frequency;
|
||||
private Node previous;
|
||||
private Node next;
|
||||
|
||||
public Node(K key, V value, int frequency) {
|
||||
Node(K key, V value, int frequency) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.frequency = frequency;
|
||||
@ -26,67 +25,67 @@ public class LFUCache<K, V> {
|
||||
|
||||
private Node head;
|
||||
private Node tail;
|
||||
private Map<K, Node> map = null;
|
||||
private Integer capacity;
|
||||
private final Map<K, Node> cache;
|
||||
private final int capacity;
|
||||
private static final int DEFAULT_CAPACITY = 100;
|
||||
|
||||
public LFUCache() {
|
||||
this.capacity = DEFAULT_CAPACITY;
|
||||
this(DEFAULT_CAPACITY);
|
||||
}
|
||||
|
||||
public LFUCache(Integer capacity) {
|
||||
public LFUCache(int capacity) {
|
||||
if (capacity <= 0) {
|
||||
throw new IllegalArgumentException("Capacity must be greater than zero.");
|
||||
}
|
||||
this.capacity = capacity;
|
||||
this.map = new HashMap<>();
|
||||
this.cache = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* This method returns value present in the cache corresponding to the key passed as parameter
|
||||
* Retrieves the value for the given key from the cache. Increases the frequency of the node.
|
||||
*
|
||||
* @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
|
||||
* @param key The key to look up.
|
||||
* @return The value associated with the key, or null if the key is not present.
|
||||
*/
|
||||
public V get(K key) {
|
||||
if (this.map.get(key) == null) {
|
||||
Node node = cache.get(key);
|
||||
if (node == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Node node = map.get(key);
|
||||
removeNode(node);
|
||||
node.frequency += 1;
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
|
||||
return node.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method stores <K> key and <V> value in the cache
|
||||
* Adds or updates a key-value pair in the cache. If the cache is full, the least frequently used item is evicted.
|
||||
*
|
||||
* @param <K> key which is to be stored in the cache
|
||||
* @param <V> value which is to be stored in the cache
|
||||
* @param key The key to insert or update.
|
||||
* @param value The value to insert or update.
|
||||
*/
|
||||
public void put(K key, V value) {
|
||||
if (map.containsKey(key)) {
|
||||
Node node = map.get(key);
|
||||
if (cache.containsKey(key)) {
|
||||
Node node = cache.get(key);
|
||||
node.value = value;
|
||||
node.frequency += 1;
|
||||
removeNode(node);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
} else {
|
||||
if (map.size() >= capacity) {
|
||||
map.remove(this.head.key);
|
||||
if (cache.size() >= capacity) {
|
||||
cache.remove(this.head.key);
|
||||
removeNode(head);
|
||||
}
|
||||
Node node = new Node(key, value, 1);
|
||||
addNodeWithUpdatedFrequency(node);
|
||||
map.put(key, node);
|
||||
cache.put(key, node);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method stores the node in the cache with updated frequency
|
||||
* Adds a node to the linked list in the correct position based on its frequency.
|
||||
*
|
||||
* @param Node node which is to be updated in the cache
|
||||
* @param node The node to add.
|
||||
*/
|
||||
private void addNodeWithUpdatedFrequency(Node node) {
|
||||
if (tail != null && head != null) {
|
||||
@ -123,9 +122,9 @@ public class LFUCache<K, V> {
|
||||
}
|
||||
|
||||
/**
|
||||
* This method removes node from the cache
|
||||
* Removes a node from the linked list.
|
||||
*
|
||||
* @param Node node which is to be removed in the cache
|
||||
* @param node The node to remove.
|
||||
*/
|
||||
private void removeNode(Node node) {
|
||||
if (node.previous != null) {
|
||||
|
@ -126,10 +126,10 @@ public class LRUCache<K, V> {
|
||||
private I key;
|
||||
private J value;
|
||||
|
||||
public Entry() {
|
||||
Entry() {
|
||||
}
|
||||
|
||||
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
|
||||
Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
|
||||
this.preEntry = preEntry;
|
||||
this.nextEntry = nextEntry;
|
||||
this.key = key;
|
||||
|
@ -124,10 +124,10 @@ public class MRUCache<K, V> {
|
||||
private I key;
|
||||
private J value;
|
||||
|
||||
public Entry() {
|
||||
Entry() {
|
||||
}
|
||||
|
||||
public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
|
||||
Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) {
|
||||
this.preEntry = preEntry;
|
||||
this.nextEntry = nextEntry;
|
||||
this.key = key;
|
||||
|
@ -17,7 +17,7 @@ import java.util.Map;
|
||||
*/
|
||||
|
||||
class GCounter {
|
||||
private final Map<Integer, Integer> P;
|
||||
private final Map<Integer, Integer> counterMap;
|
||||
private final int myId;
|
||||
private final int n;
|
||||
|
||||
@ -26,13 +26,13 @@ class GCounter {
|
||||
*
|
||||
* @param n The number of nodes in the cluster.
|
||||
*/
|
||||
public GCounter(int myId, int n) {
|
||||
GCounter(int myId, int n) {
|
||||
this.myId = myId;
|
||||
this.n = n;
|
||||
this.P = new HashMap<>();
|
||||
this.counterMap = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
P.put(i, 0);
|
||||
counterMap.put(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@ -40,7 +40,7 @@ class GCounter {
|
||||
* Increments the counter for the current node.
|
||||
*/
|
||||
public void increment() {
|
||||
P.put(myId, P.get(myId) + 1);
|
||||
counterMap.put(myId, counterMap.get(myId) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -50,7 +50,7 @@ class GCounter {
|
||||
*/
|
||||
public int value() {
|
||||
int sum = 0;
|
||||
for (int v : P.values()) {
|
||||
for (int v : counterMap.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.P.get(i) > other.P.get(i)) {
|
||||
if (this.counterMap.get(i) > other.counterMap.get(i)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -78,7 +78,7 @@ class GCounter {
|
||||
*/
|
||||
public void merge(GCounter other) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
this.P.put(i, Math.max(this.P.get(i), other.P.get(i)));
|
||||
this.counterMap.put(i, Math.max(this.counterMap.get(i), other.counterMap.get(i)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ class Element {
|
||||
* @param timestamp The timestamp associated with the element.
|
||||
* @param bias The bias of the element (ADDS or REMOVALS).
|
||||
*/
|
||||
public Element(String key, int timestamp, Bias bias) {
|
||||
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.
|
||||
*/
|
||||
public LWWElementSet() {
|
||||
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.equals(other.bias)) {
|
||||
if (e.bias != 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.equals(Bias.ADDS);
|
||||
return bias != Bias.ADDS;
|
||||
}
|
||||
return timestampComparison < 0;
|
||||
}
|
||||
|
@ -17,8 +17,8 @@ import java.util.Map;
|
||||
*/
|
||||
|
||||
class PNCounter {
|
||||
private final Map<Integer, Integer> P;
|
||||
private final Map<Integer, Integer> N;
|
||||
private final Map<Integer, Integer> pCounter;
|
||||
private final Map<Integer, Integer> nCounter;
|
||||
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.
|
||||
*/
|
||||
public PNCounter(int myId, int n) {
|
||||
PNCounter(int myId, int n) {
|
||||
this.myId = myId;
|
||||
this.n = n;
|
||||
this.P = new HashMap<>();
|
||||
this.N = new HashMap<>();
|
||||
this.pCounter = new HashMap<>();
|
||||
this.nCounter = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
P.put(i, 0);
|
||||
N.put(i, 0);
|
||||
pCounter.put(i, 0);
|
||||
nCounter.put(i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@ -44,14 +44,14 @@ class PNCounter {
|
||||
* Increments the increment counter for the current node.
|
||||
*/
|
||||
public void increment() {
|
||||
P.put(myId, P.get(myId) + 1);
|
||||
pCounter.put(myId, pCounter.get(myId) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Increments the decrement counter for the current node.
|
||||
*/
|
||||
public void decrement() {
|
||||
N.put(myId, N.get(myId) + 1);
|
||||
nCounter.put(myId, nCounter.get(myId) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -60,8 +60,8 @@ class PNCounter {
|
||||
* @return The total value of the counter.
|
||||
*/
|
||||
public int value() {
|
||||
int sumP = P.values().stream().mapToInt(Integer::intValue).sum();
|
||||
int sumN = N.values().stream().mapToInt(Integer::intValue).sum();
|
||||
int sumP = pCounter.values().stream().mapToInt(Integer::intValue).sum();
|
||||
int sumN = nCounter.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.P.get(i) > other.P.get(i) && this.N.get(i) > other.N.get(i)) {
|
||||
if (this.pCounter.get(i) > other.pCounter.get(i) && this.nCounter.get(i) > other.nCounter.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.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)));
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,222 +1,204 @@
|
||||
package com.thealgorithms.datastructures.dynamicarray;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Objects;
|
||||
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
|
||||
* Constructor with initial capacity.
|
||||
*
|
||||
* @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.capacity = capacity;
|
||||
this.elements = new Object[this.capacity];
|
||||
this.modCount = 0;
|
||||
this.elements = new Object[capacity];
|
||||
}
|
||||
|
||||
/**
|
||||
* No-args constructor
|
||||
* No-args constructor with default capacity.
|
||||
*/
|
||||
public DynamicArray() {
|
||||
this(DEFAULT_CAPACITY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an element to the array If full, creates a copy array twice the size
|
||||
* of the current one
|
||||
* Adds an element to the array. If full, creates a new array with double the size.
|
||||
*
|
||||
* @param element the element of type <E> to be added to the array
|
||||
* @param element the element to be added to the array
|
||||
*/
|
||||
public void add(final E element) {
|
||||
if (this.size == this.elements.length) {
|
||||
this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
|
||||
}
|
||||
|
||||
this.elements[this.size] = element;
|
||||
size++;
|
||||
ensureCapacity(size + 1);
|
||||
elements[size++] = element;
|
||||
modCount++; // Increment modification count
|
||||
}
|
||||
|
||||
/**
|
||||
* Places element of type <E> at the desired index
|
||||
* Places an element at the desired index, expanding capacity if necessary.
|
||||
*
|
||||
* @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) {
|
||||
this.elements[index] = 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
|
||||
}
|
||||
|
||||
/**
|
||||
* get method for element at a given index returns null if the index is
|
||||
* empty
|
||||
* Gets the element at a given index.
|
||||
*
|
||||
* @param index the desired index of the element
|
||||
* @return <E> the element at the specified index
|
||||
* @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
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public E get(final int index) {
|
||||
return getElement(index);
|
||||
if (index < 0 || index >= size) {
|
||||
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
|
||||
}
|
||||
return (E) elements[index];
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes an element from the array
|
||||
* Removes an element from the array.
|
||||
*
|
||||
* @param index the index of the element to be removed
|
||||
* @return <E> the element 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
|
||||
*/
|
||||
public E remove(final int index) {
|
||||
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));
|
||||
if (index < 0 || index >= size) {
|
||||
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
|
||||
}
|
||||
@SuppressWarnings("unchecked") E oldElement = (E) elements[index];
|
||||
fastRemove(index);
|
||||
modCount++; // Increment modification count
|
||||
return oldElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* get method for size field
|
||||
* Gets the size of the array.
|
||||
*
|
||||
* @return int size
|
||||
* @return the size
|
||||
*/
|
||||
public int getSize() {
|
||||
return this.size;
|
||||
return size;
|
||||
}
|
||||
|
||||
/**
|
||||
* isEmpty helper method
|
||||
* Checks if the array is empty.
|
||||
*
|
||||
* @return boolean true if the array contains no elements, false otherwise
|
||||
* @return true if the array contains no elements, false otherwise
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return this.size == 0;
|
||||
return size == 0;
|
||||
}
|
||||
|
||||
public Stream<E> stream() {
|
||||
return StreamSupport.stream(spliterator(), false);
|
||||
}
|
||||
|
||||
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);
|
||||
private void ensureCapacity(int minCapacity) {
|
||||
if (minCapacity > elements.length) {
|
||||
int newCapacity = Math.max(elements.length * 2, minCapacity);
|
||||
elements = Arrays.copyOf(elements, newCapacity);
|
||||
}
|
||||
|
||||
elements[this.size = newSize] = null;
|
||||
}
|
||||
|
||||
private E getElement(final int index) {
|
||||
return (E) this.elements[index];
|
||||
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 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.stream(this.elements).filter(Objects::nonNull).toArray());
|
||||
return Arrays.toString(Arrays.copyOf(elements, size));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a new Dynamic Array Iterator
|
||||
*
|
||||
* @return Iterator a Dynamic Array Iterator
|
||||
*/
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new DynamicArrayIterator();
|
||||
}
|
||||
|
||||
private class DynamicArrayIterator implements Iterator<E> {
|
||||
private final class DynamicArrayIterator implements Iterator<E> {
|
||||
|
||||
private int cursor;
|
||||
private int expectedModCount;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return this.cursor != size;
|
||||
DynamicArrayIterator() {
|
||||
this.expectedModCount = modCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
checkForComodification();
|
||||
return cursor < size;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public E next() {
|
||||
if (this.cursor > DynamicArray.this.size) {
|
||||
checkForComodification();
|
||||
if (cursor >= size) {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
|
||||
if (this.cursor > DynamicArray.this.elements.length) {
|
||||
throw new ConcurrentModificationException();
|
||||
}
|
||||
|
||||
final E element = DynamicArray.this.getElement(this.cursor);
|
||||
this.cursor++;
|
||||
|
||||
return element;
|
||||
return (E) elements[cursor++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
if (this.cursor < 0) {
|
||||
if (cursor <= 0) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
checkForComodification();
|
||||
DynamicArray.this.remove(--cursor);
|
||||
expectedModCount = ++modCount;
|
||||
}
|
||||
|
||||
DynamicArray.this.remove(this.cursor);
|
||||
this.cursor--;
|
||||
private void checkForComodification() {
|
||||
if (modCount != expectedModCount) {
|
||||
throw new ConcurrentModificationException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEachRemaining(Consumer<? super E> action) {
|
||||
Objects.requireNonNull(action);
|
||||
|
||||
for (int i = 0; i < DynamicArray.this.size; i++) {
|
||||
action.accept(DynamicArray.this.getElement(i));
|
||||
while (hasNext()) {
|
||||
action.accept(next());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,9 +3,15 @@
|
||||
*/
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
public class A_Star {
|
||||
public final class AStar {
|
||||
private AStar() {
|
||||
}
|
||||
|
||||
private static class Graph {
|
||||
|
||||
@ -14,7 +20,7 @@ public class A_Star {
|
||||
private ArrayList<ArrayList<Edge>> graph;
|
||||
|
||||
// Initialise ArrayLists in Constructor
|
||||
public Graph(int size) {
|
||||
Graph(int size) {
|
||||
this.graph = new ArrayList<>();
|
||||
for (int i = 0; i < size; i++) {
|
||||
this.graph.add(new ArrayList<>());
|
||||
@ -38,7 +44,7 @@ public class A_Star {
|
||||
private int to;
|
||||
private int weight;
|
||||
|
||||
public Edge(int from, int to, int weight) {
|
||||
Edge(int from, int to, int weight) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.weight = weight;
|
||||
@ -64,7 +70,7 @@ public class A_Star {
|
||||
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).
|
||||
|
||||
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
|
||||
PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
|
||||
this.distance = distance;
|
||||
this.path = path;
|
||||
this.estimated = estimated;
|
@ -1,6 +1,6 @@
|
||||
package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Scanner;
|
||||
|
||||
class BellmanFord /*
|
||||
* Implementation of Bellman ford to detect negative cycles. Graph accepts
|
||||
@ -11,7 +11,8 @@ class BellmanFord /*
|
||||
*/
|
||||
{
|
||||
|
||||
int vertex, edge;
|
||||
int vertex;
|
||||
int edge;
|
||||
private Edge[] edges;
|
||||
private int index = 0;
|
||||
|
||||
@ -23,7 +24,8 @@ class BellmanFord /*
|
||||
|
||||
class Edge {
|
||||
|
||||
int u, v;
|
||||
int u;
|
||||
int v;
|
||||
int w;
|
||||
|
||||
/**
|
||||
@ -31,7 +33,7 @@ class BellmanFord /*
|
||||
* @param v End vertex
|
||||
* @param c Weight
|
||||
*/
|
||||
public Edge(int a, int b, int c) {
|
||||
Edge(int a, int b, int c) {
|
||||
u = a;
|
||||
v = b;
|
||||
w = c;
|
||||
@ -55,10 +57,19 @@ class BellmanFord /*
|
||||
obj.go();
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
System.out.println("Enter no. of vertices and edges please");
|
||||
v = sc.nextInt();
|
||||
e = sc.nextInt();
|
||||
@ -107,7 +118,6 @@ class BellmanFord /*
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
sc.close();
|
||||
}
|
||||
}
|
||||
|
||||
@ -120,7 +130,11 @@ 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, j, v = vertex, e = edge, neg = 0;
|
||||
int i;
|
||||
int j;
|
||||
int v = vertex;
|
||||
int e = edge;
|
||||
int neg = 0;
|
||||
double[] dist = new double[v]; // Distance array for holding the finalized shortest path
|
||||
// distance between source
|
||||
// and all vertices
|
||||
|
@ -14,16 +14,18 @@ import java.util.Arrays;
|
||||
*
|
||||
* Output : YES
|
||||
*/
|
||||
public class BipartiteGrapfDFS {
|
||||
public final class BipartiteGraphDFS {
|
||||
private BipartiteGraphDFS() {
|
||||
}
|
||||
|
||||
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]) {
|
||||
@ -33,14 +35,14 @@ public class BipartiteGrapfDFS {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@ -52,23 +54,23 @@ public class BipartiteGrapfDFS {
|
||||
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
|
||||
int t = Integer.parseInt(read.readLine().trim());
|
||||
while (t-- > 0) {
|
||||
String[] S = read.readLine().trim().split(" ");
|
||||
int V = Integer.parseInt(S[0]);
|
||||
int E = Integer.parseInt(S[1]);
|
||||
String[] str1 = read.readLine().trim().split(" ");
|
||||
int numVertices = Integer.parseInt(str1[0]);
|
||||
int numEdges = Integer.parseInt(str1[1]);
|
||||
|
||||
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
|
||||
for (int i = 0; i < V; i++) {
|
||||
for (int i = 0; i < numVertices; i++) {
|
||||
adj.add(new ArrayList<>());
|
||||
}
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
boolean ans = isBipartite(V, adj);
|
||||
boolean ans = isBipartite(numVertices, adj);
|
||||
if (ans) {
|
||||
System.out.println("YES");
|
||||
} else {
|
@ -15,16 +15,17 @@ class Graph<E extends Comparable<E>> {
|
||||
|
||||
E name;
|
||||
|
||||
public Node(E name) {
|
||||
Node(E name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
class Edge {
|
||||
|
||||
Node startNode, endNode;
|
||||
Node startNode;
|
||||
Node endNode;
|
||||
|
||||
public Edge(Node startNode, Node endNode) {
|
||||
Edge(Node startNode, Node endNode) {
|
||||
this.startNode = startNode;
|
||||
this.endNode = endNode;
|
||||
}
|
||||
@ -33,7 +34,7 @@ class Graph<E extends Comparable<E>> {
|
||||
ArrayList<Edge> edgeList;
|
||||
ArrayList<Node> nodeList;
|
||||
|
||||
public Graph() {
|
||||
Graph() {
|
||||
edgeList = new ArrayList<Edge>();
|
||||
nodeList = new ArrayList<Node>();
|
||||
}
|
||||
@ -46,7 +47,8 @@ class Graph<E extends Comparable<E>> {
|
||||
* @param endNode the ending Node from the edge
|
||||
*/
|
||||
public void addEdge(E startNode, E endNode) {
|
||||
Node start = null, end = null;
|
||||
Node start = null;
|
||||
Node end = null;
|
||||
for (Node node : nodeList) {
|
||||
if (startNode.compareTo(node.name) == 0) {
|
||||
start = node;
|
||||
@ -79,8 +81,7 @@ class Graph<E extends Comparable<E>> {
|
||||
Set<Node> markedNodes = new HashSet<Node>();
|
||||
|
||||
for (Node n : nodeList) {
|
||||
if (!markedNodes.contains(n)) {
|
||||
markedNodes.add(n);
|
||||
if (markedNodes.add(n)) {
|
||||
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
|
||||
count++;
|
||||
}
|
||||
@ -107,7 +108,9 @@ class Graph<E extends Comparable<E>> {
|
||||
}
|
||||
}
|
||||
|
||||
public class ConnectedComponent {
|
||||
public final class ConnectedComponent {
|
||||
private ConnectedComponent() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Graph<Character> graphChars = new Graph<>();
|
||||
|
@ -5,12 +5,13 @@ import java.util.Scanner;
|
||||
|
||||
class Cycle {
|
||||
|
||||
private int nodes, edges;
|
||||
private final int nodes;
|
||||
private final int edges;
|
||||
private int[][] adjacencyMatrix;
|
||||
private boolean[] visited;
|
||||
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
|
||||
|
||||
public Cycle() {
|
||||
Cycle() {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.print("Enter the no. of nodes: ");
|
||||
nodes = in.nextInt();
|
||||
@ -27,7 +28,8 @@ class Cycle {
|
||||
System.out.println("Enter the details of each edges <Start Node> <End Node>");
|
||||
|
||||
for (int i = 0; i < edges; i++) {
|
||||
int start, end;
|
||||
int start;
|
||||
int end;
|
||||
start = in.nextInt();
|
||||
end = in.nextInt();
|
||||
adjacencyMatrix[start][end] = 1;
|
||||
@ -78,7 +80,9 @@ class Cycle {
|
||||
}
|
||||
}
|
||||
|
||||
public class Cycles {
|
||||
public final class Cycles {
|
||||
private Cycles() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Cycle c = new Cycle();
|
||||
|
@ -1,85 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
@ -0,0 +1,91 @@
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
|
@ -0,0 +1,57 @@
|
||||
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;
|
||||
}
|
||||
}
|
@ -6,7 +6,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
|
||||
ArrayList<Vertex> vertices;
|
||||
|
||||
public AdjacencyListGraph() {
|
||||
AdjacencyListGraph() {
|
||||
vertices = new ArrayList<>();
|
||||
}
|
||||
|
||||
@ -15,7 +15,7 @@ class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
E data;
|
||||
ArrayList<Vertex> adjacentVertices;
|
||||
|
||||
public Vertex(E data) {
|
||||
Vertex(E data) {
|
||||
adjacentVertices = new ArrayList<>();
|
||||
this.data = data;
|
||||
}
|
||||
@ -75,7 +75,8 @@ class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
* already did
|
||||
*/
|
||||
public boolean addEdge(E from, E to) {
|
||||
Vertex fromV = null, toV = null;
|
||||
Vertex fromV = null;
|
||||
Vertex toV = null;
|
||||
for (Vertex v : vertices) {
|
||||
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
|
||||
fromV = v;
|
||||
@ -120,7 +121,9 @@ class AdjacencyListGraph<E extends Comparable<E>> {
|
||||
}
|
||||
}
|
||||
|
||||
public class Graphs {
|
||||
public final class Graphs {
|
||||
private Graphs() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
|
||||
|
@ -2,13 +2,14 @@ package com.thealgorithms.datastructures.graphs;
|
||||
|
||||
/**
|
||||
* Java program for Hamiltonian Cycle
|
||||
* (https://en.wikipedia.org/wiki/Hamiltonian_path)
|
||||
* <a href="https://en.wikipedia.org/wiki/Hamiltonian_path">wikipedia</a>
|
||||
*
|
||||
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
|
||||
* @author <a href="https://github.com/itsAkshayDubey">Akshay Dubey</a>
|
||||
*/
|
||||
public class HamiltonianCycle {
|
||||
|
||||
private int V, pathCount;
|
||||
private int vertex;
|
||||
private int pathCount;
|
||||
private int[] cycle;
|
||||
private int[][] graph;
|
||||
|
||||
@ -21,8 +22,8 @@ public class HamiltonianCycle {
|
||||
* else returns 1D array with value -1.
|
||||
*/
|
||||
public int[] findHamiltonianCycle(int[][] graph) {
|
||||
this.V = graph.length;
|
||||
this.cycle = new int[this.V + 1];
|
||||
this.vertex = graph.length;
|
||||
this.cycle = new int[this.vertex + 1];
|
||||
|
||||
// Initialize path array with -1 value
|
||||
for (int i = 0; i < this.cycle.length; i++) {
|
||||
@ -52,36 +53,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.V;
|
||||
boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.vertex;
|
||||
if (isLastVertexConnectedToStart) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** all vertices selected but last vertex not linked to 0 **/
|
||||
if (this.pathCount == this.V) {
|
||||
/* all vertices selected but last vertex not linked to 0 **/
|
||||
if (this.pathCount == this.vertex) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int v = 0; v < this.V; v++) {
|
||||
/** if connected **/
|
||||
for (int v = 0; v < this.vertex; 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;
|
||||
}
|
||||
}
|
||||
|
@ -8,9 +8,6 @@ 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
|
||||
*/
|
||||
@ -54,19 +51,6 @@ 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>> {
|
||||
@ -104,9 +88,9 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
calculateInDegree();
|
||||
Queue<E> q = new LinkedList<E>();
|
||||
|
||||
for (E vertex : inDegree.keySet()) {
|
||||
if (inDegree.get(vertex) == 0) {
|
||||
q.add(vertex);
|
||||
for (final var entry : inDegree.entrySet()) {
|
||||
if (entry.getValue() == 0) {
|
||||
q.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
@ -130,7 +114,9 @@ class TopologicalSort<E extends Comparable<E>> {
|
||||
/**
|
||||
* A driver class that sorts a given graph in topological order.
|
||||
*/
|
||||
public class KahnsAlgorithm {
|
||||
public final class KahnsAlgorithm {
|
||||
private KahnsAlgorithm() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Graph definition and initialization
|
||||
|
@ -6,53 +6,50 @@ import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Java program that implements Kosaraju Algorithm.
|
||||
* @author Shivanagouda S A (https://github.com/shivu2002a)
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author <a href="https://github.com/shivu2002a">Shivanagouda S A</a>
|
||||
* <p>
|
||||
* 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.
|
||||
|
||||
*/
|
||||
|
||||
@ -127,7 +124,9 @@ 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);
|
||||
}
|
||||
@ -136,7 +135,9 @@ 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);
|
||||
}
|
||||
|
@ -23,7 +23,7 @@ public class Kruskal {
|
||||
private int to;
|
||||
private int weight;
|
||||
|
||||
public Edge(int from, int to, int weight) {
|
||||
Edge(int from, int to, int weight) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.weight = weight;
|
||||
|
@ -12,7 +12,9 @@ import java.util.Queue;
|
||||
*
|
||||
* @author Unknown
|
||||
*/
|
||||
public class MatrixGraphs {
|
||||
public final class MatrixGraphs {
|
||||
private MatrixGraphs() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
|
||||
@ -46,17 +48,17 @@ class AdjacencyMatrixGraph {
|
||||
/**
|
||||
* The number of vertices in the graph
|
||||
*/
|
||||
private int _numberOfVertices;
|
||||
private int vertexCount;
|
||||
|
||||
/**
|
||||
* The number of edges in the graph
|
||||
*/
|
||||
private int _numberOfEdges;
|
||||
private int edgeCount;
|
||||
|
||||
/**
|
||||
* The adjacency matrix for the graph
|
||||
*/
|
||||
private int[][] _adjacency;
|
||||
private int[][] adjMatrix;
|
||||
|
||||
/**
|
||||
* Static variables to define whether or not an edge exists in the adjacency
|
||||
@ -68,7 +70,7 @@ class AdjacencyMatrixGraph {
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
|
||||
AdjacencyMatrixGraph(int givenNumberOfVertices) {
|
||||
this.setNumberOfVertices(givenNumberOfVertices);
|
||||
this.setNumberOfEdges(0);
|
||||
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
|
||||
@ -85,16 +87,16 @@ class AdjacencyMatrixGraph {
|
||||
* @param newNumberOfVertices the new number of vertices
|
||||
*/
|
||||
private void setNumberOfVertices(int newNumberOfVertices) {
|
||||
this._numberOfVertices = newNumberOfVertices;
|
||||
this.vertexCount = newNumberOfVertices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for `this._numberOfVertices`
|
||||
* Getter for `this.vertexCount`
|
||||
*
|
||||
* @return the number of vertices in the graph
|
||||
*/
|
||||
public int numberOfVertices() {
|
||||
return this._numberOfVertices;
|
||||
return this.vertexCount;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -104,16 +106,16 @@ class AdjacencyMatrixGraph {
|
||||
*
|
||||
*/
|
||||
private void setNumberOfEdges(int newNumberOfEdges) {
|
||||
this._numberOfEdges = newNumberOfEdges;
|
||||
this.edgeCount = newNumberOfEdges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter for `this._numberOfEdges`
|
||||
* Getter for `this.edgeCount`
|
||||
*
|
||||
* @return the number of edges
|
||||
*/
|
||||
public int numberOfEdges() {
|
||||
return this._numberOfEdges;
|
||||
return this.edgeCount;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -122,7 +124,7 @@ class AdjacencyMatrixGraph {
|
||||
* @param newAdjacency the new adjaceny matrix
|
||||
*/
|
||||
private void setAdjacency(int[][] newAdjacency) {
|
||||
this._adjacency = newAdjacency;
|
||||
this.adjMatrix = newAdjacency;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -131,7 +133,7 @@ class AdjacencyMatrixGraph {
|
||||
* @return the adjacency matrix
|
||||
*/
|
||||
private int[][] adjacency() {
|
||||
return this._adjacency;
|
||||
return this.adjMatrix;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -220,12 +222,12 @@ class AdjacencyMatrixGraph {
|
||||
*/
|
||||
public List<Integer> depthFirstOrder(int startVertex) {
|
||||
// If the startVertex is invalid, return an empty list
|
||||
if (startVertex >= _numberOfVertices || startVertex < 0) {
|
||||
if (startVertex >= vertexCount || startVertex < 0) {
|
||||
return new ArrayList<Integer>();
|
||||
}
|
||||
|
||||
// Create an array to track the visited vertices
|
||||
boolean[] visited = new boolean[_numberOfVertices];
|
||||
boolean[] visited = new boolean[vertexCount];
|
||||
|
||||
// Create a list to keep track of the order of our traversal
|
||||
ArrayList<Integer> orderList = new ArrayList<Integer>();
|
||||
@ -257,7 +259,7 @@ class AdjacencyMatrixGraph {
|
||||
orderList.add(currentVertex);
|
||||
|
||||
// Get the adjacency array for this vertex
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
int[] adjacent = adjMatrix[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) {
|
||||
@ -275,12 +277,12 @@ class AdjacencyMatrixGraph {
|
||||
*/
|
||||
public List<Integer> breadthFirstOrder(int startVertex) {
|
||||
// If the specified startVertex is invalid, return an empty list
|
||||
if (startVertex >= _numberOfVertices || startVertex < 0) {
|
||||
if (startVertex >= vertexCount || startVertex < 0) {
|
||||
return new ArrayList<Integer>();
|
||||
}
|
||||
|
||||
// Create an array to keep track of the visited vertices
|
||||
boolean[] visited = new boolean[_numberOfVertices];
|
||||
boolean[] visited = new boolean[vertexCount];
|
||||
|
||||
// Create a list to keep track of the ordered vertices
|
||||
ArrayList<Integer> orderList = new ArrayList<Integer>();
|
||||
@ -307,7 +309,7 @@ class AdjacencyMatrixGraph {
|
||||
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// check each node
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
int[] adjacent = adjMatrix[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) {
|
||||
@ -334,7 +336,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._adjacency[i][j] + " ";
|
||||
s = s + this.adjMatrix[i][j] + " ";
|
||||
}
|
||||
s = s + "\n";
|
||||
}
|
||||
|
@ -14,16 +14,17 @@ 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, min_index = -1;
|
||||
int min = Integer.MAX_VALUE;
|
||||
int minIndex = -1;
|
||||
|
||||
for (int v = 0; v < V; v++) {
|
||||
if (!mstSet[v] && key[v] < min) {
|
||||
min = key[v];
|
||||
min_index = v;
|
||||
minIndex = v;
|
||||
}
|
||||
}
|
||||
|
||||
return min_index;
|
||||
return minIndex;
|
||||
}
|
||||
|
||||
// A utility function to print the constructed MST stored in
|
||||
@ -50,7 +51,7 @@ class PrimMST {
|
||||
// Initialize all keys as INFINITE
|
||||
for (int i = 0; i < V; i++) {
|
||||
key[i] = Integer.MAX_VALUE;
|
||||
mstSet[i] = false;
|
||||
mstSet[i] = Boolean.FALSE;
|
||||
}
|
||||
|
||||
// Always include first 1st vertex in MST.
|
||||
@ -65,7 +66,7 @@ class PrimMST {
|
||||
int u = minKey(key, mstSet);
|
||||
|
||||
// Add the picked vertex to the MST Set
|
||||
mstSet[u] = true;
|
||||
mstSet[u] = Boolean.TRUE;
|
||||
|
||||
// Update key value and parent index of the adjacent
|
||||
// vertices of the picked vertex. Consider only those
|
||||
|
@ -6,61 +6,58 @@ import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Java program that implements Tarjan's Algorithm.
|
||||
* @author Shivanagouda S A (https://github.com/shivu2002a)
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @author <a href="https://github.com/shivu2002a">Shivanagouda S A</a>
|
||||
* <p>
|
||||
* 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 Tarjan’s
|
||||
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 Tarjan’s
|
||||
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 List<List<Integer>> SCClist = new ArrayList<List<Integer>>();
|
||||
private final 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
|
||||
|
||||
@ -68,32 +65,34 @@ 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;
|
||||
@ -123,7 +122,7 @@ public class TarjansAlgorithm {
|
||||
scc.add(w);
|
||||
isInStack[w] = false;
|
||||
}
|
||||
SCClist.add(scc);
|
||||
sccList.add(scc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ public final class WelshPowell {
|
||||
private WelshPowell() {
|
||||
}
|
||||
|
||||
static class Graph {
|
||||
static final class Graph {
|
||||
private HashSet<Integer>[] adjacencyLists;
|
||||
|
||||
private Graph(int vertices) {
|
||||
|
@ -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,8 +47,7 @@ public class GenericHashMapUsingArray<K, V> {
|
||||
|
||||
// tells which bucket to go to
|
||||
private int hashFunction(K key) {
|
||||
int hc = key.hashCode();
|
||||
return Math.abs(hc) % buckets.length;
|
||||
return Math.floorMod(key.hashCode(), buckets.length);
|
||||
}
|
||||
|
||||
private void reHash() {
|
||||
|
@ -105,7 +105,7 @@ public class GenericHashMapUsingArrayList<K, V> {
|
||||
K key;
|
||||
V val;
|
||||
|
||||
public Node(K key, V val) {
|
||||
Node(K key, V val) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
|
@ -1,142 +1,275 @@
|
||||
package com.thealgorithms.datastructures.hashmap.hashing;
|
||||
|
||||
public class HashMap {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
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
|
||||
/**
|
||||
* 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<>();
|
||||
}
|
||||
this.hsize = hsize;
|
||||
}
|
||||
|
||||
public int hashing(int key) {
|
||||
int hash = key % hsize;
|
||||
if (hash < 0) {
|
||||
hash += 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
|
||||
}
|
||||
return hash;
|
||||
int hash = key.hashCode() % hashSize;
|
||||
return hash < 0 ? hash + hashSize : hash;
|
||||
}
|
||||
|
||||
public void insertHash(int key) {
|
||||
int hash = hashing(key);
|
||||
buckets[hash].insert(key);
|
||||
/**
|
||||
* 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 deleteHash(int key) {
|
||||
int hash = hashing(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);
|
||||
buckets[hash].delete(key);
|
||||
}
|
||||
|
||||
public void displayHashtable() {
|
||||
for (int i = 0; i < hsize; i++) {
|
||||
System.out.printf("Bucket %d :", i);
|
||||
System.out.println(buckets[i].display());
|
||||
/**
|
||||
* 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 static class LinkedList {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
private Node first;
|
||||
|
||||
public LinkedList() {
|
||||
first = null;
|
||||
}
|
||||
|
||||
public void insert(int key) {
|
||||
if (isEmpty()) {
|
||||
first = new Node(key);
|
||||
return;
|
||||
}
|
||||
|
||||
Node temp = findEnd(first);
|
||||
temp.setNext(new Node(key));
|
||||
}
|
||||
|
||||
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;
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
temp = temp.getNext();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
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);
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
current = current.getNext();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays the contents of the linked list as a string.
|
||||
*
|
||||
* @return a string representation of the linked list
|
||||
*/
|
||||
public String display() {
|
||||
return display(first);
|
||||
return display(head);
|
||||
}
|
||||
|
||||
private String display(Node n) {
|
||||
if (n == null) {
|
||||
return "null";
|
||||
} else {
|
||||
return n.getKey() + "->" + display(n.getNext());
|
||||
/**
|
||||
* 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(" -> ");
|
||||
}
|
||||
}
|
||||
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 first == null;
|
||||
return head == null;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Node {
|
||||
/**
|
||||
* 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;
|
||||
|
||||
private Node next;
|
||||
private final int key;
|
||||
|
||||
public Node(int key) {
|
||||
next = null;
|
||||
/**
|
||||
* 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) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Node getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
public int getKey() {
|
||||
/**
|
||||
* Gets the key associated with this node.
|
||||
*
|
||||
* @return the key associated with this node
|
||||
*/
|
||||
public K getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setNext(Node next) {
|
||||
/**
|
||||
* 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() {
|
||||
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) {
|
||||
this.next = next;
|
||||
}
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user