Compare commits

...

820 Commits

Author SHA1 Message Date
doxxx
648572a8c5
Refactor ProcessDetails and PreemptivePriorityScheduling (#5448)
* Refactor ProcessDetails and PreemptivePriorityScheduling for consistency

* fix formatting

* fix formatting

* Improve test readability and maintainability
2024-09-11 15:49:36 +03:00
Alex Klymenko
65e32641fc
refactor: InverseOfMatrix (#5446)
refactor: InverseOfMatrix
2024-09-09 10:15:41 +03:00
Alex Klymenko
bded78f888
refactor: BFPRT (#5445)
refactor: adding javadocs and tests for BFPRT
2024-09-09 10:07:30 +03:00
Alex Klymenko
fa2231788f
fix: FindKthNumberTest (#5444)
refactor: fix FindKthNumberTest
2024-09-08 22:25:13 +02:00
dependabot[bot]
e0a1164cf5
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.6.2 to 4.8.6.3 (#5443)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin

Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.6.2 to 4.8.6.3.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.6.2...spotbugs-maven-plugin-4.8.6.3)

---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-06 00:35:47 +02:00
Wole Jr.
175c84673a
Added an edge case for AbsoluteMax (#5441)
* Added an edge case to test

* Fixed linting on added test
2024-09-03 20:41:30 +05:30
SOZEL
a5b083cab0
Add SplayTree (#5142) 2024-09-01 23:25:34 +03:00
dependabot[bot]
b396a9790e
Chore(deps): bump com.puppycrawl.tools:checkstyle from 10.18.0 to 10.18.1 (#5438)
Chore(deps): bump com.puppycrawl.tools:checkstyle

Bumps [com.puppycrawl.tools:checkstyle](https://github.com/checkstyle/checkstyle) from 10.18.0 to 10.18.1.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-10.18.0...checkstyle-10.18.1)

---
updated-dependencies:
- dependency-name: com.puppycrawl.tools:checkstyle
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-30 23:47:39 +02:00
Alex Klymenko
b0de93b3ce
refactor: change packages (#5430)
* refactor: change package

* refactor: fix name

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 11:58:24 +02:00
Alex Klymenko
f8ff6af893
refactor: BoardPath (#5431)
refactor: BoardPath

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 10:12:31 +02:00
Alex Klymenko
c5b72816f3
refactor: MaximumSumOfDistinctSubarraysWithLengthK (#5433)
* refactor: MaximumSumOfDistinctSubarraysWithLengthK

* checkstyle: fix formatting

* checkstyle: fix formatting

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 10:03:43 +02:00
Alex Klymenko
cd38531b0d
refactor: SubsetSum (#5432)
* refactor: SubsetSum

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 09:55:18 +02:00
Alex Klymenko
14916e692f
refactor: WordLadder (#5434)
* refactor: WordLadder

* refactor: fix redundant check

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 09:49:55 +02:00
Alex Klymenko
87cf89192b
style: use proper spelling (#5436)
checkstyle: fix typos, style

Co-authored-by: alxkm <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-08-30 08:50:14 +02:00
Alex Klymenko
d189c3a719
refactor: LeastCommonMultiple (#5435)
* refactor: LeastCommonMultiple

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-30 08:43:45 +02:00
dependabot[bot]
9515d96ab6
Chore(deps): bump org.apache.commons:commons-lang3 from 3.16.0 to 3.17.0 (#5437)
Bumps org.apache.commons:commons-lang3 from 3.16.0 to 3.17.0.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-lang3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-30 00:13:30 +02:00
Alex Klymenko
c57e02dc85
refactor: DuplicateBrackets (#5424)
refactor: DuplicateBrackets

Co-authored-by: alxkm <alx@alx.com>
2024-08-29 19:21:05 +05:30
Alex Klymenko
e2aaefebd5
refactor: CountWords (#5428)
* refactor: CountWords

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 22:34:46 +02:00
Alex Klymenko
a23e9b0ba8
refactor: HashMap (#5426)
* refactor: HashMap

* checkstyle: fix formatting

* refactor: remove redundant comments

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 22:29:24 +02:00
Alex Klymenko
6b7a1fdbe8
refactor: QueueUsingTwoStacks (#5427)
refactor: QueueUsingTwoStacks

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 22:25:46 +02:00
Alex Klymenko
203d544668
test: LongestValidParenthesesTest (#5416)
* test: LongestValidParenthesesTest

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 20:56:58 +02:00
Alex Klymenko
7d1847f51c
refactor: PalindromicPartitioning (#5419)
refactor: PalindromicPartitioning

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 20:53:00 +02:00
Alex Klymenko
0733075498
test: CountCharTest (#5423)
test: CountCharTest

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 18:45:23 +02:00
Alex Klymenko
b2815db5cd
refactor: LongestNonRepetitiveSubstring (#5421)
* refactor: LongestNonRepetitiveSubstring

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 18:40:27 +02:00
Alex Klymenko
c413f3c6b2
refactor: LongestPalindromicSubstring (#5420)
* refactor: LongestPalindromicSubstring

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 18:35:21 +02:00
Alex Klymenko
45563ccbde
test: CircleLinkedListTest (#5422)
* test: CircleLinkedListTest

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-28 18:31:39 +02:00
dependabot[bot]
a9bc7c269d
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin from 3.24.0 to 3.25.0 (#5418)
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin

Bumps [org.apache.maven.plugins:maven-pmd-plugin](https://github.com/apache/maven-pmd-plugin) from 3.24.0 to 3.25.0.
- [Release notes](https://github.com/apache/maven-pmd-plugin/releases)
- [Commits](https://github.com/apache/maven-pmd-plugin/compare/maven-pmd-plugin-3.24.0...maven-pmd-plugin-3.25.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-pmd-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alex Klymenko <alexanderklmn@gmail.com>
2024-08-27 23:39:36 +02:00
dependabot[bot]
298333bf45
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.4.0 to 3.5.0 (#5417)
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin

Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.4.0 to 3.5.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.4.0...surefire-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-27 23:36:15 +02:00
Alex Klymenko
633b9d4112
refactor: PostfixToInfix (#5409)
* refactor: PostfixToInfix

* checkstyle: fix formatting

* refactor: add support for one character

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 15:03:26 +02:00
Alex Klymenko
fc5a70edc9
refactor: ReturnSubsequence (#5408)
* refactor: ReturnSubsequence

* checkstyle: fix formatting

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 13:12:49 +02:00
Alex Klymenko
49d1c84cb7
refactor: ReverseString, test improvements (#5406)
* refactor: ReverseString

* refactor: refactor testing into two methods

* checkstyle: fix formatting

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 13:00:11 +02:00
Alex Klymenko
e3ad3761fd
refactor: StringCompression (#5410)
refactor: StringCompression

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 12:02:50 +02:00
Alex Klymenko
af7c425010
refactor: NextSmallerElement (#5412)
* refactor: NextSmallerElement

* checkstyle: fix formatting

* checkstyle: fix formatting

* checkstyle: remove redundant new line

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 11:31:47 +02:00
Alex Klymenko
0c8616e332
test: ReverseStringRecursiveTest (#5407)
* test: ReverseStringRecursiveTest

* checkstyle: fix formatting

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 10:49:20 +02:00
Alex Klymenko
c8cf302d30
refactor: NextGreaterElement (#5405)
* refactor: NextGreaterElement

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-27 10:39:40 +02:00
dependabot[bot]
6fab70a91f
Chore(deps): bump com.puppycrawl.tools:checkstyle from 10.17.0 to 10.18.0 (#5411)
Chore(deps): bump com.puppycrawl.tools:checkstyle

Bumps [com.puppycrawl.tools:checkstyle](https://github.com/checkstyle/checkstyle) from 10.17.0 to 10.18.0.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-10.17.0...checkstyle-10.18.0)

---
updated-dependencies:
- dependency-name: com.puppycrawl.tools:checkstyle
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-27 00:01:27 +02:00
Alex Klymenko
c5b73ec742
refactor: HammingDistance (#5404)
* refactor: HammingDistance

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-26 16:37:17 +02:00
Alex Klymenko
d810a1d4da
test: LongestPalindromicSubstring (#5402)
* LongestPalindromicSubstring

* fix Rule:CollapsibleIfStatements

---------

Co-authored-by: alxkm <alx@alx.com>
2024-08-26 16:29:16 +02:00
Alex Klymenko
7674a84f5b
test: RegexMatchingTest (#5403)
* test: RegexMatchingTest

* checkstyle: fix formatting

---------

Co-authored-by: alxkm <alx@alx.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2024-08-26 17:22:39 +03:00
Andrii Siriak
4374a50fd7
Update CODEOWNERS 2024-08-26 17:06:41 +03:00
Alex Klymenko
4347f5b9f6
refactor: InfixToPostfix (#5401) 2024-08-26 16:43:13 +03:00
Alex Klymenko
64ff9b2efe
refactor: StackPostfixNotation (#5400) 2024-08-26 16:38:33 +03:00
Alex Klymenko
b70f077343
refactor: ShortestCommonSuperSequenceLength (#5394) 2024-08-26 11:50:12 +03:00
Alex Klymenko
35f23d2ddc
refactor: BoyerMoore (#5395) 2024-08-26 10:33:24 +03:00
Alex Klymenko
5f6510f0fa
refactor: CharactersSame (#5396) 2024-08-26 09:55:50 +03:00
Alex Klymenko
be6b0d835b
test: EditDistanceTest (#5397) 2024-08-26 09:48:30 +03:00
Alex Klymenko
cdb6412601
refactor: LineSweep (#5398) 2024-08-26 09:45:07 +03:00
Alex Klymenko
6edc009765
test: LongestAlternatingSubsequenceTest (#5399) 2024-08-26 09:37:00 +03:00
Alex Klymenko
93e417544d
refactor: Anagrams (#5390) 2024-08-26 08:26:01 +03:00
Alex Klymenko
7e9cdad3ee
refactor: BalancedBrackets (#5391) 2024-08-25 23:21:30 +03:00
Alex Klymenko
580aa0c9c5
refactor: CheckVowels (#5393) 2024-08-25 23:14:33 +03:00
Alex Klymenko
a5f57fbfde
refactor: ArrayLeftRotationTest (#5389) 2024-08-25 23:08:10 +03:00
Alex Klymenko
3187b1f99c
refactor: DecimalToAnyUsingStack (#5392) 2024-08-25 23:01:52 +03:00
Alex Klymenko
25b8010ea8
refactor: cleanup EulersFunction (#5388) 2024-08-25 22:44:55 +03:00
Alex Klymenko
f3851e3adc
refactor: RemoveDuplicateFromString (#5387) 2024-08-25 22:33:41 +03:00
Alex Klymenko
101cb950ae
refactor: RootPrecision (#5383) 2024-08-25 11:34:12 +03:00
Alex Klymenko
69e1fe9cfb
refactor: LowestBasePalindrome (#5385) 2024-08-25 10:16:14 +03:00
Alex Klymenko
0b0b26e3fe
refactor: ReverseStackUsingRecursion (#5386) 2024-08-25 10:12:17 +03:00
Alex Klymenko
e1d8b6f8a7
refactor: FordFulkerson (#5384) 2024-08-25 10:07:02 +03:00
Alex Klymenko
e5c0e4bff0
test: cleanup PrimeFactorizationTest (#5382) 2024-08-25 09:56:02 +03:00
Alex Klymenko
a8d3b6ad2d
test: cleanup ReverseNumberTest (#5381) 2024-08-25 09:43:39 +03:00
Alex Klymenko
38688440ef
refactor: TwoPointers (#5380) 2024-08-25 09:29:17 +03:00
Alex Klymenko
b231a72d44
refactor: NonRepeatingElement (#5375) 2024-08-24 16:08:22 +03:00
Alex Klymenko
a7cd97d75e
refactor: fix typo (#5372) 2024-08-24 11:57:54 +03:00
Alex Klymenko
75355e87b6
refactor: PasswordGen (#5373) 2024-08-24 11:57:40 +03:00
Alex Klymenko
4e72056527
refactor: FindKthNumber (#5374) 2024-08-24 11:53:35 +03:00
Alex Klymenko
84fb717509
test: DeterminantOfMatrix (#5376) 2024-08-24 11:38:16 +03:00
Alex Klymenko
aefc8fd4b8
refactor: HexToOct (#5377) 2024-08-24 11:32:50 +03:00
Alex Klymenko
44d7cbbaf4
test: NQueensTest (#5378) 2024-08-24 11:27:39 +03:00
Alex Klymenko
ce4eb55e0e
refactor: FloydTriangle (#5367) 2024-08-23 15:55:13 +03:00
Alex Klymenko
34089774f3
test: refactor PalindromeTest (#5365) 2024-08-23 14:37:44 +03:00
Alex Klymenko
a6fcbf585f
test: LinkedListStackTest (#5366) 2024-08-23 14:28:47 +03:00
Alex Klymenko
844aeaf701
refactor: LFUCache (#5369) 2024-08-23 14:23:16 +03:00
Alex Klymenko
d7b60be7d1
refactor: PermuteString (#5362) 2024-08-23 12:33:41 +03:00
Alex Klymenko
0301ecf1cb
refactor: Pow (#5364) 2024-08-23 11:59:20 +03:00
Alex Klymenko
fb55552ebb
refactor: fix typo (#5363) 2024-08-23 10:58:08 +03:00
dependabot[bot]
56f97c48ac
Chore(deps): bump org.apache.maven.plugins:maven-checkstyle-plugin from 3.4.0 to 3.5.0 (#5368)
Chore(deps): bump org.apache.maven.plugins:maven-checkstyle-plugin

Bumps [org.apache.maven.plugins:maven-checkstyle-plugin](https://github.com/apache/maven-checkstyle-plugin) from 3.4.0 to 3.5.0.
- [Commits](https://github.com/apache/maven-checkstyle-plugin/compare/maven-checkstyle-plugin-3.4.0...maven-checkstyle-plugin-3.5.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-checkstyle-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-23 00:42:44 +02:00
Alex Klymenko
74b05ef7c2
refactor: fix typo in class name LongestNonRepetitiveSubstring (#5359) 2024-08-22 12:37:52 +03:00
Alex Klymenko
622a3bf795
refactor: cleanup AhoCorasick (#5358) 2024-08-22 11:08:17 +03:00
Alex Klymenko
8a89b42cf8
refactor: AnyBaseToDecimal (#5357) 2024-08-22 10:50:56 +03:00
Alex Klymenko
3398c562a1
test: LargestRectangle (#5360) 2024-08-22 10:44:01 +03:00
Alex Klymenko
3ed8561a5f
test: GCDRecursion (#5361) 2024-08-22 10:12:44 +03:00
Piotr Idzik
07dbc51e1b
feat: add temperature unit conversions (#5315)
Co-authored-by: Bama Charan Chhandogi <b.c.chhandogi@gmail.com>
2024-08-22 06:43:52 +00:00
Alex Klymenko
5149051e95
refactor: LinkedQueue (#5352) 2024-08-21 20:39:09 +03:00
Alex Klymenko
39ecf70857
refactor: GenericArrayListQueue (#5355) 2024-08-21 16:55:36 +03:00
Alex Klymenko
4c65530722
refactor: StackArrayList (#5356) 2024-08-21 14:00:05 +03:00
Alex Klymenko
a03353d3d3
refactor: Deque (#5353) 2024-08-21 13:39:01 +03:00
Alex Klymenko
e756a7d2d5
refactor: CircularQueue (#5354) 2024-08-21 13:26:21 +03:00
Alex Klymenko
f5c0314111
refactor: StackArray (#5349) 2024-08-20 13:10:18 +03:00
dependabot[bot]
8605220721
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.3.1 to 3.4.0 (#5350)
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin

Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.3.1 to 3.4.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.3.1...surefire-3.4.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-20 00:19:40 +02:00
Alex Klymenko
8712a7f405
refactor: Queue (#5348) 2024-08-20 00:03:19 +03:00
Alex Klymenko
04eae87512
refactor: DynamicArray (#5346) 2024-08-19 11:15:47 +03:00
Alex Klymenko
33fd79ad55
refactor: OctalToHexadecimal (#5345) 2024-08-18 22:03:28 +03:00
Alex Klymenko
a9f5b82708
refactor: OctalToDecimal (#5344) 2024-08-18 21:58:57 +03:00
Alex Klymenko
2905ccbb20
refactor: DecimalToAnyBase (#5343) 2024-08-18 21:45:30 +03:00
Alex Klymenko
404ad7272f
refactor: Bag data structure (#5340) 2024-08-17 22:31:29 +03:00
Alex Klymenko
e8985b3edb
refactor: BinaryToOctal (#5338)
* refactor: BinaryToOctal

* checkstyle: fix formatting

* refactor: adding input correctness case, cover by tests. Renaming variable

---------

Co-authored-by: alxkm <alx@alx.com>
Co-authored-by: Bama Charan Chhandogi <b.c.chhandogi@gmail.com>
2024-08-17 19:06:45 +00:00
Alex Klymenko
25b6aebe45
refactor: DecimalToHexadecimal (#5337) 2024-08-17 21:58:50 +03:00
Alex Klymenko
d80fd0c623
refactor: DecimalToBinary (#5339) 2024-08-17 21:35:36 +03:00
mountdisk
7c58b190c8
chore: fix some comments (#5333) 2024-08-16 20:19:15 +03:00
Alex Klymenko
98bee26d51
refactor: Dijkstra algorithm (#5329) 2024-08-16 17:55:42 +03:00
Alex Klymenko
e32cab3189
refactor: BinaryToDecimal (#5330) 2024-08-16 17:48:47 +03:00
Alex Klymenko
c20375ae0f
refactor: BinaryToHexadecimal (#5331) 2024-08-16 17:43:54 +03:00
Alex Klymenko
ec30592fcb
refactor: DecimalToOctal (#5332) 2024-08-16 10:07:27 +03:00
Alex Klymenko
a84a4a29ed
refactor: cleanup InsertionSort (#5322) 2024-08-15 11:48:23 +03:00
Alex Klymenko
046f5a4728
refactor: atoi (#5324) 2024-08-15 11:43:47 +03:00
Alex Klymenko
134b42c7ff
refactor: BloomFilter (#5325) 2024-08-15 11:30:53 +03:00
Alex Klymenko
777de1da99
refactor: cleanup CycleSort (#5321) 2024-08-15 11:25:23 +03:00
dependabot[bot]
c4e0adbdd5
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter from 5.10.3 to 5.11.0 (#5328)
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter

Bumps [org.junit.jupiter:junit-jupiter](https://github.com/junit-team/junit5) from 5.10.3 to 5.11.0.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.3...r5.11.0)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Alex Klymenko <alexanderklmn@gmail.com>
2024-08-15 09:30:46 +03:00
dependabot[bot]
b8d0978e01
Chore(deps): bump org.junit:junit-bom from 5.10.3 to 5.11.0 (#5327)
Bumps [org.junit:junit-bom](https://github.com/junit-team/junit5) from 5.10.3 to 5.11.0.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.3...r5.11.0)

---
updated-dependencies:
- dependency-name: org.junit:junit-bom
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-15 09:23:37 +03:00
dependabot[bot]
4fc646809c
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter-api from 5.10.3 to 5.11.0 (#5326)
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter-api

Bumps [org.junit.jupiter:junit-jupiter-api](https://github.com/junit-team/junit5) from 5.10.3 to 5.11.0.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.3...r5.11.0)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter-api
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-15 00:20:47 +02:00
Alex Klymenko
8d0dd3ef32
refactor: cleanup DualPivotQuickSort (#5319) 2024-08-13 19:30:35 +03:00
Alex Klymenko
41f76e0e89
refactor: simple improvements and cleanup for different sorts (#5320) 2024-08-13 19:26:48 +03:00
Alex Klymenko
2837585705
refactor: IntrospectiveSort (#5316) 2024-08-11 21:00:47 +03:00
Alex Klymenko
66bfaff807
refactor: cleanup CocktailShakerSort (#5317) 2024-08-11 20:55:11 +03:00
Alex Klymenko
554b6cf006
refactor: simple improvements and cleanup for different sorts (#5318) 2024-08-11 20:44:22 +03:00
Alex Klymenko
197718842f
refactor: cleanup BucketSort (#5314) 2024-08-10 14:21:44 +03:00
Alex Klymenko
7a5fe92b2a
feat: FlashSort implementation (#5305) 2024-08-10 10:25:46 +03:00
Bayram Turgut
324a35a939
Update GrahamScan.java (#5310)
* Update GrahamScan.java

improved the Javadoc comments, clarified some methods in the Point class, and corrected some text.

* Minor adjustment to GrahamScan.java

* revised GrahamScan.java

* Update-2 GrahamScan.java

* clang format GrahamScan.java

* reverted GrahamScan.java

* minor updates.java

* minor updates

* Spc.java

* clang format

---------

Co-authored-by: Alex Klymenko <alexanderklmn@gmail.com>
2024-08-09 15:03:54 +03:00
dependabot[bot]
5fc26239eb
Chore(deps): bump DoozyX/clang-format-lint-action from 0.17 to 0.18 in /.github/workflows (#5313)
Chore(deps): bump DoozyX/clang-format-lint-action in /.github/workflows

Bumps [DoozyX/clang-format-lint-action](https://github.com/doozyx/clang-format-lint-action) from 0.17 to 0.18.
- [Release notes](https://github.com/doozyx/clang-format-lint-action/releases)
- [Commits](https://github.com/doozyx/clang-format-lint-action/compare/v0.17...v0.18)

---
updated-dependencies:
- dependency-name: DoozyX/clang-format-lint-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-09 07:42:26 +02:00
congyuluo
cafea1ee52
Refactored Identifiers (#5306)
Co-authored-by: Bama Charan Chhandogi <b.c.chhandogi@gmail.com>
2024-08-08 19:39:00 +05:30
Alex Klymenko
6e23e198ab
feat: SpreadSort implementation (#5308) 2024-08-08 10:45:33 +03:00
Andrii Siriak
357e15addd
Update CODEOWNERS 2024-08-08 09:55:11 +03:00
dependabot[bot]
365ede892f
Chore(deps): bump org.apache.commons:commons-lang3 from 3.15.0 to 3.16.0 (#5312)
Bumps org.apache.commons:commons-lang3 from 3.15.0 to 3.16.0.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-lang3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-08 07:38:58 +02:00
Bayram Turgut
6f521145cc
Update Average.java (#5309)
* Update Average.java

- Made the constructor throw an UnsupportedOperationException to prevent instantiation, making it explicit that this is a utility class.
- Added a private validateInput method to handle validation, reducing code duplication and improving readability.
- Consistent exception messages and handling for both methods.
- Improved comments to be more descriptive and follow JavaDoc conventions.
- Enhanced code readability and maintained consistent formatting.

* Minor Update Average.java

* Change To Average.java

* Mnr Average.java

* Update_Average.java

* Fix Average.java

1. throw new IllegalArgumentException("Numbers array cannot be empty or null");

2. int --> double

* fix2.java

return(double)..
2024-08-04 23:45:54 +05:30
Alex Klymenko
fccd141014
refactor: cleanup CombSort (#5303)
refactor: cleanup CombSort

Co-authored-by: Alex Klymenko <alx@alx.com>
2024-08-02 09:06:45 +02:00
Alex Klymenko
5113101e5d
refactor: cleanup ShellSort (#5302) 2024-07-26 09:55:11 +03:00
Alex Klymenko
ebed8b38b8
refactor: cleanup PigeonholeSort (#5298)
* refactor: PigeonholeSort

* checkstyle: fix formatting

* checkstyle: make class final

* refactor: changing negative numbers check first, fix typo, adding one more test for negative numbers

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-07-25 21:55:27 +02:00
Alex Klymenko
76a450fb75
feat: add PatienceSort (#5288)
* feat: PatienceSort

* refactor: fix readability issues,a and redundant check

---------

Co-authored-by: alxklm <alx@alx.com>
2024-07-24 17:32:47 +02:00
Alex Klymenko
08db744240
refactor: cleanup PancakeSort (#5295)
* refactor: PancakeSort cleanup, changing test to standard

* checkstyle: fix formatting

---------

Co-authored-by: alxklm <alx@alx.com>
2024-07-22 09:20:59 +02:00
Alex Klymenko
97d416e64e
refactor: cleanup StoogeSort (#5283)
* refactor: cleanup StoogeSort

* refactor: update DIRECTORY.md for StoogeSortTest

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
2024-07-20 19:28:06 +00:00
Alex Klymenko
94032148ca
refactor: cleanup RadixSort (#5280)
* refactor: refactoring RadixSort, adding test, update DIRECTORY.md

* checkstyle: fix formatting for test

* refactor: adding possibility to sort negative numbers. Improve tests. Improving code readability

* checkstyle: fix formatting

* refactor: resolve conflicts with master branch

* refactor: remove negative integers support

* checkstyle: fix formatting

* checkstyle: fix formatting, revert test

* refactor: adding return array to countDigits and buildOutput method, adding more specific description to javadocs

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-07-19 18:24:55 +02:00
dependabot[bot]
f1e26064a5
Chore(deps): bump org.apache.commons:commons-lang3 from 3.14.0 to 3.15.0 (#5296)
Bumps org.apache.commons:commons-lang3 from 3.14.0 to 3.15.0.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-lang3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-18 08:27:37 +02:00
dependabot[bot]
f584cd9a98
Chore(deps): bump gitpod/workspace-java-21 from 2024-07-02-14-18-47 to 2024-07-14-17-19-51 (#5293)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-07-02-14-18-47 to 2024-07-14-17-19-51.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-07-16 11:05:17 +02:00
dependabot[bot]
ff0eca3caa
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin from 3.23.0 to 3.24.0 (#5292) 2024-07-16 11:57:28 +03:00
Piotr Idzik
5840579885
style: include BigIntegerInstantiation (#5294) 2024-07-16 11:39:11 +03:00
Alex Klymenko
57878cac55
refactor: cleanup CycleSort (#5271)
* refactor: cleanup CycleSort. Adding test for it. Simplify code

* refactor: CycleSortTest to directory file

* tests: Adding more various tests cases for testing sorting algorithms

* checkstyle: imports and whitespaces fixes

* tests: removing boolean sorting

* checkstyle: fix "eedBraces: 'if' construct must use '{}'s"

* checkstyle: reduce "Too many static imports"

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
2024-07-13 22:44:49 +05:30
Alex Klymenko
2d6c39ce10
feat: CountingSort implementation (#5287)
* feat: CountingSort

* checkstyle: fix formatting

* refactor: adding additional final modifiers

* refactor: restructure sorting, update docs and tests

* docs: typo fix

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-07-12 20:03:54 +02:00
Alex Klymenko
87e6184494
cleanup: removing wrong CountingSort implementation (#5284)
cleanup: removing CountingSort

Co-authored-by: Alex Klymenko <alx@alx.com>
2024-07-12 08:49:11 +02:00
dependabot[bot]
8ea90fdd42
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.3.0 to 3.3.1 (#5282)
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin

Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.3.0 to 3.3.1.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.3.0...surefire-3.3.1)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-11 08:41:44 +02:00
yuvashreenarayanan3
f83bb659ba
refactor: redesign ArrayCombination (#5181)
* Related to #5164 (Redesign of ArrayCombination)

* Checkstyle fix

* Clang_format

* refactor: cleanup

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: vil02 <vil02@o2.pl>
2024-07-10 19:20:32 +02:00
dependabot[bot]
06927d3fda
Chore(deps-dev): bump org.assertj:assertj-core from 3.26.0 to 3.26.3 (#5281)
Bumps [org.assertj:assertj-core](https://github.com/assertj/assertj) from 3.26.0 to 3.26.3.
- [Release notes](https://github.com/assertj/assertj/releases)
- [Commits](https://github.com/assertj/assertj/compare/assertj-build-3.26.0...assertj-build-3.26.3)

---
updated-dependencies:
- dependency-name: org.assertj:assertj-core
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-10 09:00:01 +02:00
Alex Klymenko
57f65808ad
refactor: MergeSortNoExtraSpace (#5277)
* refactor: MergeSortNoExtraSpace, change naming, adding test

* checkstyle: fix import ordering, and formatting

* fix: adding negative numbers check, fix possible overflow

* checkstyle: remove newline

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-07-09 22:44:42 +02:00
dependabot[bot]
14264602de
Chore(deps): bump gitpod/workspace-java-21 from 2024-06-26-08-49-45 to 2024-07-02-14-18-47 (#5279)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-06-26-08-49-45 to 2024-07-02-14-18-47.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 09:09:03 +02:00
dependabot[bot]
6b41c7d7a0
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.6.1 to 4.8.6.2 (#5278)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin

Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.6.1 to 4.8.6.2.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.6.1...spotbugs-maven-plugin-4.8.6.2)

---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-09 09:01:00 +02:00
Piotr Idzik
96e59e063a
style: include DLS_DEAD_LOCAL_STORE (#5276) 2024-07-05 22:52:54 +03:00
Piotr Idzik
26b4b82949
style: include OI_OPTIONAL_ISSUES_USES_IMMEDIATE_EXECUTION (#5274) 2024-07-03 19:55:09 +03:00
Piotr Idzik
5bc96cf789
style: include RV_ABSOLUTE_VALUE_OF_HASHCODE (#5273) 2024-07-02 22:47:35 +03:00
dependabot[bot]
e63c39ac88
Chore(deps): bump gitpod/workspace-java-21 from 2024-06-24-08-46-07 to 2024-06-26-08-49-45 (#5272)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-06-24-08-46-07 to 2024-06-26-08-49-45.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-02 08:55:03 +02:00
Alex Klymenko
ac31fba37a
refactor: cleanup BeadSort (#5269)
* cleanup: BeadSort and BeadSortTest, adding javadocs

* checkstyle: fix formatting

* checkstyle: fix import order

* cleanup: improving code readability

* cleanup: improving code readability using enum to represent beads

* checkstyle: fix enum formatting

* fix: enum should be compared using ==, according to maven bugs finder plugin

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-07-01 22:26:15 +02:00
Alex Klymenko
208e1e99f0
refactor: BubbleSortRecursion: improving naming, adding standard test (#5267)
* refactor: improving naming, adding standard test

* style: remove `BubbleSortRecursive` from pmd exclude list

* docs: typo fix

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-30 17:51:11 +00:00
Alex Klymenko
758df7dcc3
feat: optimize SortUtils.swap by skipping operations for equal indices (#5266)
* Refactor: adding check to swap method in SortUtils

* Checkstyle: fix formatting

* Checkstyle: fix formatting, and redundant braces

* fix: adding flipped tests, removed messages from tests

* checkstyle: fix indent

* style: mark `temp` as `final`

* tests: remove test case with empty array

Such calls should be excluded.

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-29 22:33:40 +02:00
Alex Klymenko
20e7a3aca4
refactor: SelectionSort like classes and their tests (#5265)
* Refactor: Adding test common approach, adding javadocs, renaming variables

* Refactor: Fix failed build, when generated test case for recursion is too big. To avoid stackoverflow

* Checkstyle: Adding newline to end of class

* refactor: simplify assign minIndex in recursiveSelectionSort, and improving SelectionSort

* checkstyle: adding newline to SelectionSort

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-29 10:04:58 +02:00
Alex Klymenko
0087444e9f
feat: add SelectionSortRecursive (#5255)
* Implementation: SelectionSort using recursion

* Documentation: adding links

* Fix issue with findMinIndex

* Fix: change findMinIndex method to recursive

* Fix: improve variable change scope

* Fix: Replacing recursive method findMinIndex with iterative. To fix StackOverFlow on huge arrays

* refactor: remove `null` check

* Fix: Removing redundant null check

---------

Co-authored-by: alxklm <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-28 09:18:06 +02:00
dependabot[bot]
224ee3d227
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter from 5.10.2 to 5.10.3 (#5262)
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter

Bumps [org.junit.jupiter:junit-jupiter](https://github.com/junit-team/junit5) from 5.10.2 to 5.10.3.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.2...r5.10.3)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 07:01:39 +00:00
dependabot[bot]
c2a5c91920
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter-api from 5.10.2 to 5.10.3 (#5263)
Chore(deps-dev): bump org.junit.jupiter:junit-jupiter-api

Bumps [org.junit.jupiter:junit-jupiter-api](https://github.com/junit-team/junit5) from 5.10.2 to 5.10.3.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.2...r5.10.3)

---
updated-dependencies:
- dependency-name: org.junit.jupiter:junit-jupiter-api
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 06:59:21 +00:00
dependabot[bot]
69f221683f
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.6.0 to 4.8.6.1 (#5261)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin

Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.6.0 to 4.8.6.1.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.6.0...spotbugs-maven-plugin-4.8.6.1)

---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 08:56:46 +02:00
dependabot[bot]
cba28d31c5
Chore(deps): bump org.junit:junit-bom from 5.10.2 to 5.10.3 (#5260)
Bumps [org.junit:junit-bom](https://github.com/junit-team/junit5) from 5.10.2 to 5.10.3.
- [Release notes](https://github.com/junit-team/junit5/releases)
- [Commits](https://github.com/junit-team/junit5/compare/r5.10.2...r5.10.3)

---
updated-dependencies:
- dependency-name: org.junit:junit-bom
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-28 08:52:27 +02:00
Alex Klymenko
7054535d36
feat: add WaveSort (#5252)
* Implementing WaveSort Algorithm

* Refactor: Tests to ParameterizedTest

* Checkstyle: Fix wrong align

* Checkstyle: Fix wrong align for second line

* Checkstyle: Remove redundant line

* Naming: fix method name

* Documentation: adding links

* Fix: adding test for isWaveSorted method

* Documentation: adding description for WaveSort

* Testing: test wave sort assert

* Checkstyle: remove redundant whitespace

* Checkstyle: remove redundant newline

* Testing: improving tests

---------

Co-authored-by: alxklm <alx@alx.com>
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-06-26 22:41:54 +02:00
dependabot[bot]
971f5fc85b
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.5.0 to 4.8.6.0 (#5256)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin

Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.5.0 to 4.8.6.0.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.5.0...spotbugs-maven-plugin-4.8.6.0)

---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-26 08:48:20 +02:00
dependabot[bot]
f279f9d589
Chore(deps): bump gitpod/workspace-java-21 from 2024-06-17-10-03-09 to 2024-06-24-08-46-07 (#5253)
Dependabot couldn't find the original pull request head commit, a1d54164dac1d97b56d75099b00f7db58bf8fb48.

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-25 07:01:32 +00:00
Piotr Idzik
cff3a59530
style: include BED_BOGUS_EXCEPTION_DECLARATION (#5233) 2024-06-25 06:51:24 +00:00
Piotr Idzik
d36f54bd39
style: include NM_CLASS_NAMING_CONVENTION and NM_METHOD_NAMING_CONVENTION (#5231) 2024-06-25 10:37:07 +05:30
Piotr Idzik
a710fe11c4
style: include SPP_USE_ISEMPTY (#5238) 2024-06-24 08:49:50 +00:00
Piotr Idzik
22f2abd94f
style: enable WhitespaceAround in checktyle (#5241) 2024-06-24 16:47:33 +08:00
abdala-elgendy
7b17ead902
chore: improve FibonacciHeap (#5251) 2024-06-24 16:42:29 +08:00
Alex Klymenko
a5b4c6173f
fix: avoid infinite loop in SwapSort (#5248)
---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-06-24 08:49:01 +02:00
Alex Klymenko
308bdcfc19
Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods (#5246)
* Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods

* Rename parameter unsorted to array

---------

Co-authored-by: Alex Klymenko <alx@alx.com>
2024-06-22 22:29:17 +02:00
Alex Klymenko
e8f1990c8c
Replace the various swap method variants with SortUtils.swap (#5245)
Fix different variants of swap methods to SortUtils.swap

Co-authored-by: AlexKlm <alx@alx.com>
2024-06-22 10:18:39 +02:00
Alex Klymenko
8ef69bc854
Improving BitonicSort (#5244)
* Improving BitonicSort

* Moving max method to SortingUtils

* Adding Javadoc to merge method

* Fix for test and code improvements

* Improving code readability

* Renaming method parameters

---------

Co-authored-by: alx <alx@alx.com>
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-06-21 19:37:58 +00:00
Alex K
15d2e70673
Refactoring and code improving for StrandSort (#5243)
* Refactoring and code improving for StrandSort

* Fix java checkstyle

* Fix "Each variable declaration must be in its own statement"

* Fix "uses integer based for loops to iterate over a List"

---------

Co-authored-by: alx <alx@alx.com>
2024-06-20 17:47:43 +02:00
Alex K
91101ec424
Refactoring and code improving for OddEvenSort (#5242)
* Refactoring and code improving for OddEvenSort, changing it according to SortAlgorithm approach, also applying SortUtils

* Fix checkstyle

* Remove redundant main, remove redundant tests.

---------

Co-authored-by: alx <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-20 08:26:09 +02:00
Alex K
a9db8428b2
Refactoring BinaryInsertionSort according to common SortAlgorithm approach (#5239)
* Refactoring BinaryInsertionSort according to common SortAlgorithm approach

* Formatting has been fixed

* Refactoring tests for BinaryInsertionSort according to SortingAlgorithmTest

* Removing redundant tests and improving variable readability

---------

Co-authored-by: alx <alx@alx.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-19 18:57:54 +02:00
dependabot[bot]
bf4fc3f9c2
Chore(deps): bump org.apache.commons:commons-collections4 from 4.5.0-M1 to 4.5.0-M2 (#5240)
Chore(deps): bump org.apache.commons:commons-collections4

Bumps org.apache.commons:commons-collections4 from 4.5.0-M1 to 4.5.0-M2.

---
updated-dependencies:
- dependency-name: org.apache.commons:commons-collections4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-19 07:18:53 +02:00
Samuel Facchinello
74e51990c1
style: enable InvalidJavadocPosition in checkstyle (#5237)
enable style InvalidJavadocPosition

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
2024-06-18 19:34:22 +02:00
dependabot[bot]
39e065437c
Chore(deps): bump gitpod/workspace-java-21 from 2024-06-10-10-39-01 to 2024-06-17-10-03-09 (#5235)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-06-10-10-39-01 to 2024-06-17-10-03-09.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-18 08:40:46 +02:00
Samuel Facchinello
9973b8efc8
refactor: redesign StringMatchFiniteAutomata (#5222)
* refactor

* add test

* fix clang

* fix pmd

* remove main method

* refactor searchPattern with private class

* fix checkstyle

* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* fix clang

* tests: add more test cases

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-17 20:55:20 +00:00
dependabot[bot]
c7ee0e73c2
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin from 3.2.5 to 3.3.0 (#5234)
Chore(deps): bump org.apache.maven.plugins:maven-surefire-plugin

Bumps [org.apache.maven.plugins:maven-surefire-plugin](https://github.com/apache/maven-surefire) from 3.2.5 to 3.3.0.
- [Release notes](https://github.com/apache/maven-surefire/releases)
- [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.2.5...surefire-3.3.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-surefire-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-15 11:02:09 +02:00
Samuel Facchinello
cdb3affdd9
style: enable AvoidNestedBlocks in checkstyle (#5228)
* enable style AvoidNestedBlocks

* refactor after enable style AvoidNestedBlocks

* fix clang

* fix checkstyle

* fix pmd

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-14 16:57:30 +02:00
Samuel Facchinello
87b17e0571
style: enable NeedBraces in checkstyle (#5227)
* enable style NeedBraces

* style: enable NeedBraces in checkstyle

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
2024-06-13 21:00:16 +02:00
Samuel Facchinello
51fcc66345
refactor: redesign LetterCombinationsOfPhoneNumber (#5221)
* Refactor

* fix clang

* fix clang

* fix clang tests

* fix pattern

* add test case null

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* rename MAP_OF_CHARS to KEYPAD

* fix clang

* remove main

* add tests

* feat: throw for wrong inputs

* change keypad to list

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* fix with number 1 (empty value), and add tests

* style: avoid concatenation while populating `KEYPAD`

* change to assertEquals

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-13 19:40:12 +02:00
Piotr Idzik
31db1af345
style: include SUI_CONTAINS_BEFORE_ADD (#5216) 2024-06-13 17:27:49 +00:00
Samuel Facchinello
a2af09cdfb
style: enable ParenPad in checkstyle (#5226)
* enable ParenPad

* style: enable ParenPad in checkstyle

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
2024-06-13 19:25:43 +02:00
Piotr Idzik
f8698674b3
style: include IM_BAD_CHECK_FOR_ODD (#5213) 2024-06-13 10:07:14 +05:30
dependabot[bot]
3ecd13508a
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin from 3.22.0 to 3.23.0 (#5220)
Chore(deps): bump org.apache.maven.plugins:maven-pmd-plugin

Bumps [org.apache.maven.plugins:maven-pmd-plugin](https://github.com/apache/maven-pmd-plugin) from 3.22.0 to 3.23.0.
- [Release notes](https://github.com/apache/maven-pmd-plugin/releases)
- [Commits](https://github.com/apache/maven-pmd-plugin/compare/maven-pmd-plugin-3.22.0...maven-pmd-plugin-3.23.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-pmd-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-12 06:15:51 +00:00
dependabot[bot]
0e8fed0dd6
Chore(deps): bump gitpod/workspace-java-21 from 2024-06-03-17-43-12 to 2024-06-10-10-39-01 (#5218)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-06-03-17-43-12 to 2024-06-10-10-39-01.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-11 00:02:21 +02:00
StarDxxx
a81fb32e6c
style: enable TypeName (#5214)
* style: enable `TypeName` in checkstyle

* style: enable `TypeName` in checkstyle

* Update directory

* style: use proper formatting

---------

Co-authored-by: StarDxxx <StarDxxx@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-08 13:37:20 +02:00
StarDxxx
be38886d43
style: enable OperatorWrap in checkstyle (#5212) 2024-06-08 09:36:42 +02:00
Piotr Idzik
41efe7fbbc
style: include DMC_DUBIOUS_MAP_COLLECTION (#5207) 2024-06-07 23:29:53 +05:30
dependabot[bot]
732d5e06ae
Chore(deps): bump org.apache.maven.plugins:maven-checkstyle-plugin from 3.3.1 to 3.4.0 (#5208)
Chore(deps): bump org.apache.maven.plugins:maven-checkstyle-plugin

Bumps [org.apache.maven.plugins:maven-checkstyle-plugin](https://github.com/apache/maven-checkstyle-plugin) from 3.3.1 to 3.4.0.
- [Commits](https://github.com/apache/maven-checkstyle-plugin/compare/maven-checkstyle-plugin-3.3.1...maven-checkstyle-plugin-3.4.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-checkstyle-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-05 23:54:20 +02:00
Piotr Idzik
b315b7d578
style: include WMI_WRONG_MAP_ITERATOR (#5206) 2024-06-06 00:22:12 +05:30
Piotr Idzik
440f3ce18b
style: include MAC_MANUAL_ARRAY_COPY (#5199) 2024-06-04 21:02:38 +00:00
Piotr Idzik
493942e319
style: include IT_NO_SUCH_ELEMENT (#5200) 2024-06-05 02:24:38 +05:30
dependabot[bot]
f3db699083
Chore(deps): bump gitpod/workspace-java-21 from 2024-05-27-17-11-15 to 2024-06-03-17-43-12 (#5201)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-05-27-17-11-15 to 2024-06-03-17-43-12.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-06-04 07:56:59 +02:00
Piotr Idzik
2e387fe54e
style: include IMC_IMMATURE_CLASS_VAR_NAME (#5197) 2024-06-01 21:36:12 +00:00
Piotr Idzik
5e4db7baf1
style: include SS_SHOULD_BE_STATIC (#5198) 2024-06-02 02:54:11 +05:30
Godwill Christopher
c42b1c940c
style: enable ParameterName in CheckStyle. (#5196)
* Enabled: ParameterName in CheckStyle.

* Refactored to fix  bug caused by selfAssignment of variables in VectorCrossproduct class
2024-05-31 22:01:11 +02:00
Alex K
2568b96784
Adding class for generating all subsequences from a given List (#5194)
* Adding class for generating all subsequences from a given List

* Fix test data format

* Fix braces wrong placement

* Fix "Utility classes should not have a public or default constructor."

* Fix checkstyle " Class Subsequence should be declared as final."

* Renaming class Subsequence to SubsequenceFinder. Refactored test to Parametrized test. Fixed input parameter as final.

* Fix formatting

* Fix formatting

* Fix formatting

* Fix import ordering

* Renaming method generate all.
Renaming test method.
Adding duplication test.
Renaming TestData to TestCase.

* Fix formatting

* style: add assertion to avoid potential infinite loop

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-30 18:43:15 +00:00
S. Utkarsh
a6e873deef
style: enable MemberName in checkstyle (#5193)
* style: enable MemberName in checkstyle

* style: simply uncomment `MemberName`

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-29 20:44:14 +00:00
Piotr Idzik
d2bfb100b2
style: include LII_LIST_INDEXED_ITERATING (#5190) 2024-05-28 19:06:47 +00:00
Piotr Idzik
2cda944643
style: include ENMI_EQUALS_ON_ENUM (#5189) 2024-05-28 19:03:52 +00:00
Piotr Idzik
1a98ebe36b
style: enable MissingSwitchDefault in CheckStyle (#5188) 2024-05-29 00:27:32 +05:30
S. Utkarsh
25d711c5d8
style: enable LocalVariableName in CheckStyle (#5191)
* style: enable LocalVariableName in checkstyle

* Removed minor bug

* Resolved Method Name Bug

* Changed names according to suggestions
2024-05-28 20:29:28 +02:00
dependabot[bot]
81cb09b1f8
Chore(deps): bump com.puppycrawl.tools:checkstyle from 10.16.0 to 10.17.0 (#5186)
Chore(deps): bump com.puppycrawl.tools:checkstyle

Bumps [com.puppycrawl.tools:checkstyle](https://github.com/checkstyle/checkstyle) from 10.16.0 to 10.17.0.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-10.16.0...checkstyle-10.17.0)

---
updated-dependencies:
- dependency-name: com.puppycrawl.tools:checkstyle
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-28 09:22:21 +02:00
dependabot[bot]
23ed1196c0
Chore(deps): bump gitpod/workspace-java-21 from 2024-05-15-13-36-34 to 2024-05-27-17-11-15 (#5185)
Chore(deps): bump gitpod/workspace-java-21

Bumps gitpod/workspace-java-21 from 2024-05-15-13-36-34 to 2024-05-27-17-11-15.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-28 09:16:09 +02:00
dependabot[bot]
33a34841bb
Chore(deps-dev): bump org.assertj:assertj-core from 3.25.3 to 3.26.0 (#5187)
Bumps [org.assertj:assertj-core](https://github.com/assertj/assertj) from 3.25.3 to 3.26.0.
- [Release notes](https://github.com/assertj/assertj/releases)
- [Commits](https://github.com/assertj/assertj/compare/assertj-build-3.25.3...assertj-build-3.26.0)

---
updated-dependencies:
- dependency-name: org.assertj:assertj-core
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-28 09:08:45 +02:00
Piotr Idzik
92887a10c2
style: include NAB_NEEDLESS_BOXING_PARSE (#5184) 2024-05-28 06:47:51 +00:00
Piotr Idzik
70c1d97ab1
style: include SPP_TOSTRING_ON_STRING (#5183) 2024-05-28 02:37:20 +05:30
Godwill Christopher
295e7436b1
style: enable MethodName in CheckStyle (#5182)
enabled: MethodName in CheckStyle
2024-05-27 09:06:06 +02:00
Piotr Idzik
ea4dc15a24
style: do not suppress try (#5167) 2024-05-27 03:02:36 +05:30
Bama Charan Chhandogi
37c2a96fe2
style: enable MissingSwitchDefault in checkstyle (#5179)
* Update directory

* Update directory

* Update directory

* Update directory

* add switch default

---------

Co-authored-by: BamaCharanChhandogi <BamaCharanChhandogi@users.noreply.github.com>
2024-05-26 17:28:00 +05:30
vaibhav9t1
9eaa2bb756
style: enable MultipleVariableDeclarations in checkstyle (#5175)
Co-authored-by: vaibhav <vaibhav.waghmare@techprescient.com>
2024-05-25 20:18:27 +02:00
vaibhav9t1
44ce6e7b0d
style: enable StaticVariableName in checkstyle (#5173)
* style: enable StaticVariableName in checkstyle

* Refractored: enable StaticVariableName in checkstyle

* style: mark more variables as `final`

---------

Co-authored-by: vaibhav <vaibhav.waghmare@techprescient.com>
Co-authored-by: vil02 <vil02@o2.pl>
2024-05-25 14:09:14 +00:00
Godwill Christopher
160742104d
Enabled LocalFinalVariableName in Checkstyle (#5172) 2024-05-24 16:38:37 +05:30
Piotr Idzik
8be8b953ab
style: do not suppress this-escape (#5166) 2024-05-20 16:09:23 +00:00
Piotr Idzik
324969fc4e
style: enable OverrideBothEqualsAndHashcode like checks (#5159) 2024-05-20 16:06:52 +00:00
Piotr Idzik
8466219685
style: do not suppress serial (#5168) 2024-05-20 20:39:31 +05:30
Piotr Idzik
5ee98eeb48
chore: migrate to java 21 (#5163) 2024-05-19 21:57:07 +03:00
Piotr Idzik
d77d9010a8
style: enable compiler warnings and treat them as errors (#5165) 2024-05-19 18:06:16 +05:30
Piotr Idzik
bf9d0ed66a
fix: handle constant inputs in `LongestIncreasingSubsequence::findLISLen' (#5160)
fix: handle constant inputs in `LongestIncreasingSubsequence::findLISLen`
2024-05-17 15:24:22 +05:30
Godwill Christopher
0f42e995a4
style: enabled InnerAssignment in checkstyle (#5162)
* style: enabled InnerAssignment in checkstyle

* Refactor code formatting in KnapsackMemoization.java and UnionFind.java

* style: remove redundant blank line

* style: mark `includeCurrentItem` and `excludeCurrentItem` as `final`

* style: remove `KnapsackMemoization` from `pmd-exclude.properties`

* style: use `final`

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-16 16:46:03 +00:00
dependabot[bot]
f8e62fbb90
Chore(deps): bump gitpod/workspace-java-17 from 2024-04-29-23-03-42 to 2024-05-13-09-12-40 (#5161)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-04-29-23-03-42 to 2024-05-13-09-12-40.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-14 18:02:08 +02:00
Godwill Christopher
bbef89c885
refactor: simplify logic of Point::equals in KDTree (#5158) 2024-05-12 12:37:14 +02:00
Godwill Christopher
5703be5953
style: enable EqualsHashCode in checkstyle (#5157) 2024-05-12 11:38:07 +02:00
Piotr Idzik
319d5143cc
refactor: cleanup DudeneyNumber (#5156) 2024-05-12 14:35:33 +05:30
Piotr Idzik
cf6c87c35c
style: make SubsetCount a proper utility (#5153) 2024-05-11 14:36:17 +00:00
Piotr Idzik
cb401fed69
chore: configure PMD (#5155) 2024-05-11 18:01:11 +05:30
Godwill Christopher
bbe4a025df
style: enable FinalClass in checkstyle (#5154) 2024-05-11 08:50:05 +02:00
Piotr Idzik
52f15b2b08
style: include RV_RETURN_VALUE_IGNORED (#5152) 2024-05-09 15:23:22 +00:00
Piotr Idzik
27c0978851
style: include VA_FORMAT_STRING_USES_NEWLINE (#5151) 2024-05-09 17:21:04 +02:00
Piotr Idzik
7bff82f175
style: include LEST_LOST_EXCEPTION_STACK_TRACE (#5150) 2024-05-09 15:15:36 +00:00
Piotr Idzik
ee6924a2a0
style: include PATH_TRAVERSAL_IN (#5148) 2024-05-09 20:04:57 +05:30
Piotr Idzik
d2ddec55e5
style: include NAB_NEEDLESS_BOOLEAN_CONSTANT_CONVERSION (#5149)
* style: use `assertFalse` and `assertTrue`

* style: include `NAB_NEEDLESS_BOOLEAN_CONSTANT_CONVERSION`
2024-05-08 22:41:46 +05:30
Piotr Idzik
d3bb691f59
style: enable HideUtilityClassConstructor in checkstyle (#5147) 2024-05-08 09:58:29 +03:00
Piotr Idzik
030bb91d05
chore: configure SpotBugs plugin find-sec-bugs (#5144) 2024-05-07 23:59:11 +05:30
dependabot[bot]
ff5267d393
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin from 4.8.4.0 to 4.8.5.0 (#5146)
Chore(deps): bump com.github.spotbugs:spotbugs-maven-plugin

Bumps [com.github.spotbugs:spotbugs-maven-plugin](https://github.com/spotbugs/spotbugs-maven-plugin) from 4.8.4.0 to 4.8.5.0.
- [Release notes](https://github.com/spotbugs/spotbugs-maven-plugin/releases)
- [Commits](https://github.com/spotbugs/spotbugs-maven-plugin/compare/spotbugs-maven-plugin-4.8.4.0...spotbugs-maven-plugin-4.8.5.0)

---
updated-dependencies:
- dependency-name: com.github.spotbugs:spotbugs-maven-plugin
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-07 07:44:37 +02:00
Piotr Idzik
bfb27eeb59
style: enable ArrayTypeStyle in checkstyle (#5145) 2024-05-06 22:49:52 +03:00
Piotr Idzik
414835db11
style: enable AvoidStarImport in checkstyle (#5141) 2024-05-05 20:48:56 +02:00
Piotr Idzik
dc47e0aa42
style: include ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD (#5129) 2024-05-05 18:39:26 +00:00
Piotr Idzik
5d00889291
fix: handle empty inputs in CircleSort (#5121)
* fix: handle empty inputs in `CircleSort`

* style: remove `main` method
2024-05-05 23:56:54 +05:30
Piotr Idzik
6bde5d7ed5
chore: configure SpotBugs plugin fb-contrib (#5126) 2024-05-04 21:27:59 +05:30
SOZEL
dda3c9cb59
Refactor Levenshtein distance implementation (#5138)
* ref: refactor Levenshtein distance implementation
- Rewrite the original levenshtein distance implementation in functional style
- Add optimized version of levenshtein distance

* ref: make `LevenshteinDistance` class a proper utility

* ref: remove duplicated test data

* ref: update tests

---

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-04 11:13:30 +02:00
Piotr Idzik
b3903f5768
style: enable RedundantModifier in checkstyle (#5140) 2024-05-03 22:10:49 +03:00
marysiuniq
1e2d7e9431
style: enable ConstantName in checkstyle (#5139)
Co-authored-by: Maria Paszkiewicz SCC <maria.paszkiewicz@kit.edu>
2024-05-02 18:31:37 +02:00
dependabot[bot]
ede3e4651f
Chore(deps): bump gitpod/workspace-java-17 from 2024-04-29-07-29-58 to 2024-04-29-23-03-42 (#5133)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-04-29-07-29-58 to 2024-04-29-23-03-42.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-05-02 08:20:13 +02:00
dependabot[bot]
032c288922
Chore(deps): bump org.apache.maven.plugins:maven-compiler-plugin from 3.10.1 to 3.13.0 (#5135)
Chore(deps): bump org.apache.maven.plugins:maven-compiler-plugin

Bumps [org.apache.maven.plugins:maven-compiler-plugin](https://github.com/apache/maven-compiler-plugin) from 3.10.1 to 3.13.0.
- [Release notes](https://github.com/apache/maven-compiler-plugin/releases)
- [Commits](https://github.com/apache/maven-compiler-plugin/compare/maven-compiler-plugin-3.10.1...maven-compiler-plugin-3.13.0)

---
updated-dependencies:
- dependency-name: org.apache.maven.plugins:maven-compiler-plugin
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-01 16:51:39 +02:00
dependabot[bot]
cdc320afaf
Chore(deps): bump com.puppycrawl.tools:checkstyle from 9.3 to 10.16.0 (#5134)
* Chore(deps): bump com.puppycrawl.tools:checkstyle from 9.3 to 10.16.0

Bumps [com.puppycrawl.tools:checkstyle](https://github.com/checkstyle/checkstyle) from 9.3 to 10.16.0.
- [Release notes](https://github.com/checkstyle/checkstyle/releases)
- [Commits](https://github.com/checkstyle/checkstyle/compare/checkstyle-9.3...checkstyle-10.16.0)

---
updated-dependencies:
- dependency-name: com.puppycrawl.tools:checkstyle
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update directory

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <dependabot[bot]@users.noreply.github.com>
2024-05-01 14:46:48 +00:00
Piotr Idzik
f64bc3c65d
style: include UC_USELESS_OBJECT (#5127) 2024-05-01 11:11:03 +00:00
marysiuniq
06a284f811
style: enable ModifierOrder in checkstyle (#5132)
* style: enable `ModifierOrder` in checkstyle

* style: remove redundant `final`

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

---------

Co-authored-by: Maria Paszkiewicz SCC <maria.paszkiewicz@kit.edu>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-05-01 13:06:19 +02:00
Piotr Idzik
fd65892415
chore: add maven to dependabot (#5123) 2024-05-01 10:56:47 +00:00
Piotr Idzik
2513ccd62b
style: include IM_AVERAGE_COMPUTATION_COULD_OVERFLOW (#5131) 2024-05-01 15:28:04 +05:30
dependabot[bot]
b075c19a54
Chore(deps): bump gitpod/workspace-java-17 from 2024-04-16-12-16-24 to 2024-04-29-07-29-58 (#5130)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-04-16-12-16-24 to 2024-04-29-07-29-58.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-30 08:34:07 +02:00
Piotr Idzik
4bb64559de
chore: configure SpotBugs (#5122) 2024-04-28 11:31:11 +03:00
Piotr Idzik
de18d0df7e
style: enable EmptyStatement (#5120) 2024-04-26 22:39:03 +03:00
Piotr Idzik
6de154d218
tests: add tests of Mode (#5104) 2024-04-26 06:40:01 +00:00
Piotr Idzik
7a42f68b66
chore: configure checkstyle (#5110) 2024-04-24 15:22:42 +03:00
dependabot[bot]
089b1f7c92
Chore(deps): bump gitpod/workspace-java-17 from 2024-04-15-14-41-42 to 2024-04-16-12-16-24 (#5115)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-04-15-14-41-42 to 2024-04-16-12-16-24.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-23 21:28:05 +02:00
marysiuniq
ac598e2b93
Remove unused import. (#5113)
Co-authored-by: Maria Paszkiewicz SCC <maria.paszkiewicz@kit.edu>
2024-04-21 21:02:32 +02:00
marysiuniq
8129686e2e
Added tests for FactorialRecursion (#5109)
* Added tests for `FactorialRecursion`

* Apply suggestions from code review

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

---------

Co-authored-by: Maria Paszkiewicz SCC <maria.paszkiewicz@kit.edu>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-20 20:31:13 +02:00
dependabot[bot]
05626f7a79
Chore(deps): bump gitpod/workspace-java-17 from 2024-04-07-21-39-34 to 2024-04-15-14-41-42 (#5108)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-04-07-21-39-34 to 2024-04-15-14-41-42.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-16 18:33:15 +02:00
marysiuniq
7201dc78ad
Added tests for NumberOfDigits (#5107)
Co-authored-by: Maria Paszkiewicz SCC <maria.paszkiewicz@kit.edu>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-13 20:45:07 +02:00
dependabot[bot]
f39bb8f32f
Chore(deps): bump DoozyX/clang-format-lint-action from 0.16.2 to 0.17 in /.github/workflows (#5105)
Chore(deps): bump DoozyX/clang-format-lint-action in /.github/workflows

Bumps [DoozyX/clang-format-lint-action](https://github.com/doozyx/clang-format-lint-action) from 0.16.2 to 0.17.
- [Release notes](https://github.com/doozyx/clang-format-lint-action/releases)
- [Commits](https://github.com/doozyx/clang-format-lint-action/compare/v0.16.2...v0.17)

---
updated-dependencies:
- dependency-name: DoozyX/clang-format-lint-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-12 08:36:46 +02:00
dependabot[bot]
91cdf0453a
Chore(deps): bump gitpod/workspace-java-17 from 2024-03-31-14-01-15 to 2024-04-07-21-39-34 (#5103)
Chore(deps): bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2024-03-31-14-01-15 to 2024-04-07-21-39-34.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-09 19:03:13 +02:00
Piotr Idzik
4697b87753
chore: update maven dependencies (#5101) 2024-04-08 18:10:15 +00:00
Piotr Idzik
f490b5936a
docs: add codecov badge (#5099)
Continuation of #5098.
2024-04-08 18:08:35 +00:00
Piotr Idzik
90704d736b
fix: update clang-format tag (#5095) 2024-04-08 23:08:31 +05:30
Piotr Idzik
295ac4b1ac
Update codecov/codecov-action to v4 (#5100) 2024-04-06 21:50:15 +03:00
Piotr Idzik
ab094ef04d
chore: generate coverage report and upload it to codecov (#5098) 2024-04-06 20:36:30 +05:30
SOZEL
c53f178308
Implement Parentheses Generator (#5096)
* chore: add `ParenthesesGenerator` to `DIRECTORY.md`

* feat: implement Parentheses Generator

* ref: change `ParenthesesGenerator`s method to `static`

* ref: use parametrized tests

* ref: handling exception when `n < 0`

* chore: update docstrings

* ref: make `ParenthesesGenerator` to be a proper utility

* chore(docs): add private constructor docstring

* ref(tests): move bad name suggestions

* style: remove reduntant comments

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-05 18:41:27 +02:00
Kanivets Kateryna
22310defcd
Cleaned up code for some packages (#5094)
* Cleaned up code of some packages

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-04-02 21:26:06 +02:00
dependabot[bot]
40cd4d86ef
Bump gitpod/workspace-java-17 from 2023-08-30-14-07-38 to 2024-03-31-14-01-15 (#5092)
Bump gitpod/workspace-java-17

Bumps gitpod/workspace-java-17 from 2023-08-30-14-07-38 to 2024-03-31-14-01-15.

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-02 23:52:17 +05:30
Piotr Idzik
da21ffe78c
chore: configure dependabot to update docker files (#5086) 2024-03-26 22:26:13 +05:30
dependabot[bot]
71c5f27d85
Bump actions/stale from 4 to 9 in /.github/workflows (#5085)
Bumps [actions/stale](https://github.com/actions/stale) from 4 to 9.
- [Release notes](https://github.com/actions/stale/releases)
- [Changelog](https://github.com/actions/stale/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/stale/compare/v4...v9)

---
updated-dependencies:
- dependency-name: actions/stale
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-22 11:20:45 +00:00
Piotr Idzik
098f044370
Remove CalculateMaxOfMin (#5079) 2024-03-22 19:18:08 +08:00
dependabot[bot]
84f8cee332
Bump actions/setup-python from 4 to 5 in /.github/workflows (#5084)
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 4 to 5.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-22 19:10:09 +08:00
dependabot[bot]
df20d919c8
Bump actions/setup-java from 3 to 4 in /.github/workflows (#5083)
Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4.
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-22 12:06:58 +01:00
dependabot[bot]
d4e4cd24cd
Bump github/codeql-action from 2 to 3 in /.github/workflows (#5082)
Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2 to 3.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v2...v3)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-22 11:38:44 +01:00
Piotr Idzik
9d1635a28b
chore: configure dependabot (#5081) 2024-03-22 16:02:13 +05:30
SOZEL
192427a5d2
Parameterize references to generic types. (#5078)
* chore: remove unused imports

* fix: parameterize references to generic types


---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2024-03-15 19:03:27 +01:00
SOZEL
ab371843ac
Close Scanner to avoid resource leak (#5077) 2024-03-12 19:49:58 +01:00
straf10
47a9b1b647
Add WelshPowell (Graph Colouring) (#5034)
* Welsh Powell Algorithm + Test


---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-02-12 20:48:07 +01:00
Piotr Idzik
55cc562d64
chore: update actions/checkout to v4 (#5036) 2024-02-12 02:51:08 +05:30
VedantK
14b3f45f9f
Add ExchangeSort (#5029)
* added ExchangeSort and its testcases

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-02-01 09:25:31 +01:00
Debasish Biswas
b99aeef674
Remove debasishbsws from CODEOWNERS (#5033)
As I am not very active in this repository, I should step down from being a CodeOwner /cc @BamaCharanChhandogi @yanglbme
2024-01-29 01:18:40 +05:30
Bhishmadev Ghosh
55f08cc013
Add tests SumOfSubset (#5021)
* Updated main and test

* removed

* style: reorder test cases

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2024-01-26 19:30:26 +01:00
Piotr Idzik
a216cb8a59
Remove unused import from HashMapCuckooHashing (#5018)
style: remove unused import from `HashMapCuckooHashing`
2024-01-13 09:28:50 +00:00
Piotr Idzik
3528399b2e
Remove unused import from JobSequencing (#5017)
style: remove unused import from `JobSequencing`
2024-01-13 10:26:44 +01:00
Piotr Idzik
ac7152d757
Remove unused imports from PerfectSquareTest (#5016)
style: remove unused imports from `PerfectSquareTest`
2024-01-13 09:21:57 +00:00
Piotr Idzik
9426053f73
Remove unused import from PowerOfTwoOrNotTest (#5015)
style: remove unused import from `PowerOfTwoOrNotTest.java`
2024-01-13 14:34:32 +05:30
Sarthak Chaudhary
8804cec957
Feature/4638 array right rotation (#5014)
* Create ArrayRightRotationTest.java

* Create ArrayRightRotation.java

* The updated one

* The updated one

* Added the test cases

* Added new test cases!

* Update ArrayRightRotation.java

* Update ArrayRightRotationTest.java
2024-01-13 13:59:30 +05:30
Piotr Idzik
19b7a22ec9
Remove unused imports from BoyerMooreTest (#5012) 2024-01-10 20:31:38 +02:00
mpousmali
fd84b0b10e
Add SRTF Algorithm (#5011) 2024-01-08 23:48:11 +02:00
Piotr Idzik
570f7e7ef6
Remove unused import (#5010) 2024-01-08 23:44:32 +02:00
Piotr Idzik
c403e00331
Use GITHUB_ACTOR in git config (#5009) 2024-01-08 23:32:18 +02:00
Nishant Jain
bb2fff0cbb
Add package name (#5007) 2024-01-08 15:41:14 +02:00
Nishant Jain
0c881e39f2
Simplify minimizing lateness (#4999) 2024-01-08 15:34:36 +02:00
Tung Bui (Leo)
704b5878b6
Use Discord channel in stale issue/PR message (#5004) 2024-01-07 14:20:43 +02:00
Piotr Idzik
8930ab5b16
Cleanup SumOfDigits and its tests (#4994) 2024-01-05 23:05:52 +02:00
Piotr Idzik
1ea95ffa92
Cleanup PerfectSquare and its tests (#4992) 2024-01-04 12:56:48 +02:00
Piotr Idzik
092ac5795b
Remove SetKthBit in favor of SingleBitOperations.setBit (#4991) 2024-01-04 00:28:59 +02:00
AthinaSw
6a0c0585e4
Add cross-correlation and auto-correlation (#4984) 2024-01-03 20:11:07 +02:00
Govind Gupta
9bef5a169c
Add Playfair Cipher (#4988) 2024-01-03 15:14:38 +02:00
Nishant Jain
a7d140a43e
Add Set Kth Bit (#4990) 2024-01-02 20:18:01 +02:00
aryan1165
7ece806cf5
Remove duplicate file of Simple Substitution Cipher (fixes #4494) (#4495) 2023-12-26 00:24:28 +02:00
Niklas Hoefflin
e26fd9da71
Add OR-Set (Observed-Remove Set) (#4980) 2023-12-11 23:05:43 +02:00
Niklas Hoefflin
4aa8e6a0eb
Updated TwoPSet to use Generics instead of Strings (#4981) 2023-12-11 20:58:56 +02:00
Niklas Hoefflin
b8b1dea38d
Add LWW Element Set (Last Write Wins Element Set) (#4979) 2023-12-08 20:57:07 +02:00
Niklas Hoefflin
92131de377
Fix compare() for subset check (S.A ⊆ T.A) (#4978) 2023-12-07 18:06:56 +02:00
Niklas Hoefflin
249ee1dc99
Add 2P-Set (Two-Phase Set) for both addition and removal operations in distributed systems (#4977) 2023-12-07 17:23:22 +02:00
Nassor Shabataka
36580bac1e
Fix typo in NextGraterElement (#4976) 2023-12-06 09:37:58 +02:00
Niklas Hoefflin
e59a3b1ebb
Add G-Set (Grow-only Set) (#4975) 2023-12-05 20:39:18 +02:00
Niklas Hoefflin
3001620c1e
Add PN-Counter (#4974) 2023-12-04 18:22:02 +02:00
Niklas Hoefflin
e759544c33
Add Boruvka's algorithm to find Minimum Spanning Tree (#4964) 2023-12-02 19:53:17 +02:00
Piotr Idzik
9bebcee5c7
Make sumOfDigits long in HarshadNumber.isHarshad (#4973)
fix: make `sumOfDigits` `long` in `HarshadNumber.isHarshad`
2023-11-30 22:06:31 +05:30
Piotr Idzik
fc21a8bffe
Explicitly cast result of Math.pow to long in Armstrong (#4972) 2023-11-30 10:50:09 +02:00
Piotr Idzik
f8de290188
Explicitly cast result of Math.pow to int in BinaryToHexadecimal (#4970) 2023-11-29 23:30:59 +02:00
Piotr Idzik
361b4108ee
Use explicit cast to int in FractionalKnapsack (#4971) 2023-11-29 23:21:25 +02:00
Piotr Idzik
3392b5116d
Add codeql.yml (#4966) 2023-11-28 22:40:51 +02:00
Doksanbir
1518e84fb9
Add Tribonacci Numbers (fixes #4646) (#4959) 2023-11-26 13:34:13 +02:00
Niklas Hoefflin
b1efd4e34b
Add G-Counter (Grow-only Counter) (#4965) 2023-11-24 19:13:44 +02:00
D.Sunil
c527dff92d
Add Javadoc comments (#4745) 2023-11-11 22:55:48 +02:00
Prathamesh Powar
574138c7a3
Cleanup BoyerMoore (#4951)
* modify code to make use of java Optional class

* revert changes

* add java.util.Optional<Integer>

* add java.util.Optional

* refactors: make `findmajor` return `optional`

* refactors: make method name findMajor and split it

* refactors: change method name in tests

* Apply suggestions from code review

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* change back to int

* fix: swap arguments

* tests: add some test cases

* refactor: add `isMajority` and avoid rounding

* style: use `var`

* style: swap arguments of `countOccurrences`

---------

Co-authored-by: vil02 <vil02@o2.pl>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-31 09:07:59 +01:00
Hardik Pawar
d086afce09
Enhance code density and readability (#4914)
* Enhance code density and readability

* Add wiki link

---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2023-10-30 23:18:05 +01:00
Phuong Nguyen
e5f3d232c9
refactor: use method SortUtils.swap (#4946)
* refactor: use method SortUtils.swap

* fix: clang format

* style: explicitly import `swap`

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-30 23:09:43 +01:00
Satvik Singh Sengar
945e7b56bb
Fix:/Number of count of major element in Boyer Moore algorithm (#4728)
* Number of count of major element in Boyer Moore algorithm

* test: add `BoyerMooreTest`

* style: basic linting

* tests: add test case from the issue

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: vil02 <vil02@o2.pl>
2023-10-30 18:24:23 +01:00
Anup Omkar
9dde8a7808
Add MatrixRank (#4571)
* feat: adding matrix rank algorithm

* fix: formatting

* fix: adding comments, refactor and handling edge cases

* refactor: minor refactor

* enhancement: check matrix validity

* refactor: minor refactor and fixes

* Update src/main/java/com/thealgorithms/maths/MatrixRank.java

* feat: add unit test to check if input matrix is not modified while calculating the rank

---------

Co-authored-by: Anup Omkar <anup_omkar@intuit.com>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2023-10-25 15:34:05 +02:00
Aakil Iqbal
a4711d61d8
Added MapReduce Algorithm in Misc Folder. (#4828)
* Added MapReduce Algorithm in Misc Folder.

* Did formatting correctly

* Removed main function and added MapReduceTest

* format the code
2023-10-25 09:30:18 +05:30
Appari Satya Barghav
9dae389faa
Herons : Changed the signature of the function (#4686)
* Made changes to the code to correct the Logic of Armstrong Number

* Resolved the issues

* Trying to resolve the Linter error by changing Variable name

* Changed Variable Names : trying to resolve Clang error

* Chnged the signature of the function

* Added the Function documentation

* Added exception for parameters

* Resolved with suggested changes

* Resolved with Suggested changes

* fix: use proper logic

---------

Co-authored-by: vil02 <vil02@o2.pl>
2023-10-23 23:09:42 +02:00
Aditi Bansal
e87036d886
Correct documentation of IsEven (#4845)
* Update IsEven.java

* Update IsEven.java

* Update IsEven.java

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-19 21:37:29 +02:00
ironspec07
f3345d9e06
Fixed typo error for better readability (#4835) 2023-10-20 00:32:27 +05:30
Ayoub Chegraoui
8002137b76
Fixed some typos and links for javadoc, and some refactoring (#4755) 2023-10-15 19:32:24 +05:30
Lukas
48ae88f09d
Bit swap (#4770)
* Create BitSwap.java

* Create BitSwapTest.java

* Update BitSwap.java

* Update BitSwap.java

* Update BitSwapTest.java

* Update BitSwap.java

* Update BitSwap.java

* Update BitSwapTest.java

* Update BitSwapTest.java

* Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update BitSwap.java

* Update BitSwap.java

* Update BitSwap.java

* Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/bitmanipulation/BitSwapTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* style: remove redundant blank line

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-15 07:03:25 +00:00
Pronay Debnath
24a8223062
Added [FEATURE REQUEST] Golden Ration formula to find Nth Fibonacci number #4505 (#4513)
* Create FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Create FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Delete src/main/java/com/thealgorithms/maths/FibonacciNumberTest.java

* Create FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Create FibonacciCalculator.java

* Update FibonacciNumberTest.java

* Update and rename FibonacciCalculator.java to FibCalc.java

* Update FibonacciNumberTest.java

* Update FibCalc.java

* Update FibonacciNumber.java

* Delete src/test/java/com/thealgorithms/maths/FibCalc.java

* Create FibCalc.java

* Update FibonacciNumberTest.java

* Update FibCalc.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumber.java

* fix: use proper name

* fix: use proper class name

* tests: add `returnsCorrectValues`

* Update and rename FibCalc.java to Fibonacci.java

* Update Fibonacci.java

* Update FibonacciNumber.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update Fibonacci.java

* Update FibonacciNumber.java

* Update and rename FibCalcTest.java to FibonacciTest.java

* Update FibonacciNumber.java

* Update Fibonacci.java

* Update Fibonacci.java

* Update Fibonacci.java

* Update FibonacciTest.java

* Update Fibonacci.java

* Update src/main/java/com/thealgorithms/maths/Fibonacci.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FibonacciTest.java

* Update FibonacciNumberTest.java

* Update FibonacciNumberTest.java

* Update FibonacciTest.java

* Update src/main/java/com/thealgorithms/maths/Fibonacci.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/Fibonacci.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FibonacciNumber.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FibonacciNumberTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FibonacciNumber.java

* Update FibonacciNumber.java

* Update Fibonacci.java

* Update FibonacciNumber.java

* Update and rename FibonacciNumber.java to FibonacciNumberGoldenRation.java

* Update and rename FibonacciNumberTest.java to FibonacciNumberGoldenRationTest.java

* Update Fibonacci.java

* Update FibonacciNumberGoldenRation.java

* Update FibonacciNumberGoldenRationTest.java

* Update FibonacciTest.java

* Update Fibonacci.java

* Update FibonacciNumberGoldenRationTest.java

* Update FibonacciNumberGoldenRationTest.java

* Update FibonacciNumberGoldenRation.java

* Update FibonacciNumberGoldenRation.java

* Update FibonacciNumberGoldenRationTest.java

* Update FibonacciNumberGoldenRationTest.java

* Update src/main/java/com/thealgorithms/maths/FibonacciNumberGoldenRation.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update and rename Fibonacci.java to FibonacciLoop.java

* Update FibonacciNumberGoldenRation.java

* Update FibonacciNumberGoldenRationTest.java

* Update and rename FibonacciTest.java to FibonacciLoopTest.java

* Update FibonacciLoop.java

* Update FibonacciLoop.java

* Update FibonacciNumberGoldenRation.java

* docs: add missing dot

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: vil02 <vil02@o2.pl>
2023-10-13 21:23:30 +02:00
D.Sunil
1dc64b1685
Update BinarySearch (#4747) 2023-10-12 23:13:32 +03:00
Ricardo Ramos
e9bbf35ff9
Add FloorTest and clean-up Floor (#4769)
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Ricardo Ramos <0102016812@grupotel.corp>
2023-10-12 00:21:53 +03:00
Abhinav Pandey
152e29034d
Improved code readability and code quality (#4663)
* Fixed Small typos :-)

* Update BufferedReader.java

* Made the following changes :

* Improved readability of files and removed gramatical errors.

* Implemented data assigning instead of manually calling arr.ylength in several instances like FindMax, FindMaxRecursion etc.

* Removed unwanted params from several files

* Implemented Math methods in files math/FindMinRecursion.java and FindMaxRecursion.java

* Update src/main/java/com/thealgorithms/maths/FindMinRecursion.java

---------

Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
2023-10-11 17:29:55 +05:30
Lukas
17fe4298b6
Add MaxValueTest and remove main from MaxValue (#4756)
* Create MaxValueTest.java

* Update MaxValue.java
2023-10-10 21:27:23 +02:00
Anuj Rathour
ced9678699
Update queue readme (#4721) 2023-10-09 18:33:34 +03:00
Lukas
c6a22de12f
Add MinValueTest and remove main from MinValue (#4713)
* Update MinValue.java

* Create MinValueTest.java

* Revert "Create MinValueTest.java"

* Create MinValueTest.java

* Update MinValueTest.java

* Update MinValueTest.java

* Update MinValue.java

* Update src/test/java/com/thealgorithms/maths/MinValueTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/MinValueTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/MinValue.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-09 17:17:02 +02:00
Arin
facc62a81a
adding formatting steps in pull request template (#4606)
* adding formatting steps in contribution.md

* adding format to pull request template

* made format instruction shorter

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-08 21:06:13 +02:00
Prabhat-Kumar
8200a791a2
Add AhoCorasick (#4465)
* Added code to find Articulation Points and Bridges

* tried to solve clang-formant test

* removed new line at EOF to get lint to pass

* feature: Added Ahocorasick Algorithm

* fixed lint using clang-format

* removed datastructures/graphs/ArticulationPointsAndBridge.java from this branch

* removed main, since test-file is added. Also modified and renamed few functions.

* Added test-file for AhoCorasick Algorithm

* Modified some comments in test-file

* Modified some comments in AhoCorasick.java

* lint fix

* added few more test cases

* Modified some comments

* Change all class fields to private, added initializeSuffixLinksForChildNodesOfTheRoot() method, hashmap string search position (also has previous index based search), removed java.util.*

* Added Missing Test-Cases and more

* minor text changes

* added direct test check i.e. defining a variable expected and just checking if res and expected are equal.

* Created New Class Trie, merged 'buildTrie and buildSuffixAndOutputLinks' with 'Trie constructor'. Merged setUpStartPoints with searchIn. Now AhoCorasick contains -> inner class: Trie, Node. Methods: search and convert. Trie has -> Methods : constructor and searchIn

* Updated TestFile according to the updated AhoCorasick Class. Added Few more test cases

* updated - broken down constructor to relavent parts, made string final, made res local to searchIn(), doxygen-like style

* lint fix clang

* Updated Tests Files

* Added final field to Node class setters and Trie Constructor arguments, removed getTrieRoot() and some unnecessory comments, renamed [old -> new]: res -> positionByStringIndexValue, removed if condition from setupStartPoints()

* updated test file

* lint fix clang

* minor chage - 'removed a comment'

* added final fields to some arguments, class and variables, added a method initializePositionByStringIndexValue()

* updated to remove * inclusion and added the required modules only

* Implemented a new class PatternPositionRecorder to wrap up the position recording in searchIn()

* Added final fields to PatternPositionRecorder Class

* style: mark default constructor of `AhoCorasick` as `private`

* style: remoce redundant `public`

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-08 15:16:06 +02:00
Aman
06aa834fa6
Enhance queue README.md (#4710) 2023-10-08 10:47:35 +03:00
Anuj Rathour
7f9555bd94
Update stack readme.md (#4678) 2023-10-07 20:37:57 +03:00
Piyush Pagar
aaa2b26ed1
Issue #4706 Solved (#4707)
Import Package into the RecursiveBinarySearchTest and RecursiveBinarySearch

Co-authored-by: PiyushPagar1 <piyus.p@ergobite.com>
2023-10-07 18:57:46 +05:30
Suchi Bansal
081f308b9d
Add ReverseWordsInString (#4456)
* return a string of the words in reverse order concatenated by a single space.

Input: s = "the sky is blue"
Output: "blue is sky the"

* return a string of the words in reverse order concatenated by a single space.

Input: s = "the sky is blue"
Output: "blue is sky the"

* space reduce

* removed main method

* added test cases

* formatting fix

* formatting fix

* worked on pr reviews

* formatting fix

* private constructor added

* added test case for when string contains white space

* simplified method

* fix issue

* formatting issues fix

* fixed issue

* code refactor

* documented method

* worked on pr comments

* docs: add missing space

* tests: express as `ParameterizedTest`

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: vil02 <vil02@o2.pl>
2023-10-06 20:15:27 +02:00
Lukas
064ca8f591
cleanup FindMinRecursion (#4568)
* Create FindMinRecusionTest.java

* Update FindMinRecursion.java

* Update FindMinRecursion.java

* Update FindMinRecursion.java

* Rename FindMinRecusionTest.java to FindMinRecursionTest.java

* Update FindMinRecursionTest.java

* style: remove unused imports

---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
2023-10-05 22:01:27 +02:00
Aman
06d6e2116b
Update Readme.md (#4634) 2023-10-05 16:08:28 +03:00
Appari Satya Barghav
a3a2d845d5
Made changes to the code to correct the Logic of Armstrong Number (#4619)
* Made changes to the code to correct the Logic of Armstrong Number

* Resolved the issues

* Trying to resolve the Linter error by changing Variable name

* Changed Variable Names : trying to resolve Clang error
2023-10-04 20:02:49 +05:30
Arin
4fab7adfaa
code-clean-up (#4519)
* code-clean-up

* style: make `RabinKarpAlgorithm` a proper utility class

---------

Co-authored-by: arintripathi1 <arint@trainee.nrifintech.com>
Co-authored-by: vil02 <vil02@o2.pl>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-03 17:32:59 +00:00
Vineet Chotaliya
535230acae
Add Greedy Algorithms (fixes #4493) (#4504) 2023-10-03 20:30:18 +03:00
Aman
329cc3bcf9
Added MirrorOfMatrix.java (#4461)
* Added MirrorOfMatrix.java

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Fixing Linting Issue

* Changes Done

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Changes Done

* Added MirrorOfMatrixTest.java

* Added MirrorOfMatrixTest.java

* Linting Error in Test

* Linting Error in Test

* Linting Error in Test

* trying to fix build error

* trying to fix build error

* final

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/misc/MirrorOfMatrixTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Changing Description

* Final

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Final

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Changes

* Changes

* Linting Issue

* Linting Issue

* Linting Issue

* Changes

* Fixing Minor Linting Issue

* Fixing Minor Linting Issue

* Final

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Changes

* Linting Issue

* Linting Issue

* Linting Issue

* Linting Issue

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/misc/MirrorOfMatrix.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Changes

* Changes

* fix: use proper size in `checkInput`

* style: basic linting

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Co-authored-by: vil02 <vil02@o2.pl>
2023-10-03 16:42:56 +00:00
Shreyash Kashyap
9795bada90
Update Readme.md (#4561) 2023-10-03 14:22:19 +00:00
Bama Charan Chhandogi
5f5a61de87
Add median of matrix (#4590) 2023-10-03 17:16:14 +03:00
Bama Charan Chhandogi
536978919d
Add reverse k group in LinkedList algorithm (#4532) 2023-10-03 09:43:49 +03:00
Piotr Idzik
6283572637
Ask contributors to create drafts (#4522) 2023-10-01 22:55:37 +03:00
Lukas
8dc5505323
Add FindMaxRecursionTest (#4431)
* Update FindMaxRecursion.java

* Create FindMaxRecusionTest.java

* Update and rename FindMaxRecusionTest.java to FindMaxRecursionTest.java

* Update FindMaxRecursion.java

* Update FindMaxRecursion.java

* Update src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/maths/FindMaxRecursionTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/maths/FindMaxRecursion.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FindMaxRecursion.java

* Update FindMaxRecursionTest.java

* Update FindMaxRecursionTest.java

* Update FindMaxRecursion.java

* Update src/main/java/com/thealgorithms/maths/FindMaxRecursion.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update FindMaxRecursion.java

* Update FindMaxRecursion.java

* Update FindMaxRecursion.java

* Update FindMaxRecursion.java

* Update FindMaxRecursion.java

* Update src/main/java/com/thealgorithms/maths/FindMaxRecursion.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-01 18:21:29 +00:00
Arin
f72b80b116
rewrote as parameterized tests (#4458)
* rewrote as parameterized tests

* formatting issue resolved

* added test with different prime number q

* style: run `clang-format`

* tests: add missing test case

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-01 18:05:27 +02:00
Prabhat-Kumar
edb0489440
[FEATURE] #4486 QuickSort Algo for LinkedList (#4487)
* Added code to find Articulation Points and Bridges

* tried to solve clang-formant test

* removed new line at EOF to get lint to pass

* feature: Added Ahocorasick Algorithm

* fixed lint using clang-format

* Added QuickSort Algorithm for linked list

* removed datastructures/graphs/ArticulationPointsAndBridges and string/AhoCorasick.java from this branch

* Added datastructures/lists/SinglyLinkedList class, Replaced ListNode class

* Modified some comments

* Added tests in QuickSortLinkedListsTest.java

* removed main as added a test file to test test-cases

* test file for QuickSortLinkedLinst.java
2023-10-01 16:01:32 +00:00
Bharath Sanjeevi T
37b3844b98
Add SecondMinMax (#4432)
* Added Second Min/Max program

* Clang-format-lint error resolved

* Clang-format-error 2

* Added Program to find Second Minimum/Maximum element

* Test File & few changes

* Clang-lint-error resolved

* Maven Build Error Resolved

* Clang-lint-error resolved

* Clang-lint-error resolved 2

* Changes Resolved

* Test Arguements are Streamed

* Clang-lint-error resolved

* incresed code reusability

* Added Program to find Second Min / Max

* Program to find Second Min / Max

* Program to find Second Minimum / Maximum

* Program to find Second Best Number

* style: mark `initialVal` as `final`

* style: resolve `MultipleVariableDeclarations`

Each variable declaration must be in its own statement.

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-10-01 15:28:37 +00:00
Pronay Debnath
da687c11cb
Added [FEATURE REQUEST] <Recursive Binary Search> #4457 (#4469)
* Create RecursiveBinarySearch.java

* Update RecursiveBinarySearch.java

* Update RecursiveBinarySearch.java

* Update RecursiveBinarySearch.java

* Update RecursiveBinarySearch.java

* Create ReverseArray.java

* Update RecursiveBinarySearch.java

* Update RecursiveBinarySearch.java

* Create RecursiveBinarySearchTest.java

* Update RecursiveBinarySearchTest.java

* Update RecursiveBinarySearchTest.java

* Delete src/main/java/com/thealgorithms/others/ReverseArray.java

* Update RecursiveBinarySearchTest.java

* Update RecursiveBinarySearchTest.java

* Create ReverseArray.java

* Delete src/main/java/com/thealgorithms/others/ReverseArray.java

* Update RecursiveBinarySearchTest.java

* Update RecursiveBinarySearch.java
2023-10-01 15:22:51 +00:00
ANKIT SAHA
ee2629c8ab
Update Pangram.java using Java Collections (#4479)
* Update Pangram.java using Java Collections

A simple separate function isPangramOrNot(String s) has been created which implements the Pangram checking of a string using Java Collection Framework approach.

* Update Pangram.java using Java Collections

* Updated some linting errors in Pangram.java

* Update src/main/java/com/thealgorithms/strings/Pangram.java

Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>

* Updated Pangram.java

Method name updated to - isPangramUsingSet(String s)

* Updated the testcases PangramTest.java

Successfully updated the testcases in this same PR branch

---------

Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
2023-10-01 16:28:13 +05:30
Lukas
e5d33f3565
Add SingleBitOperations (#4415)
* SingleBitOperators

* Tests

* Update SingleBitOperatorTest.java

* Update SingleBitOperators.java

* Update SingleBitOperators.java

* Update SingleBitOperators.java

* Update SingleBitOperatorTest.java

* deliting files

* Update SingleBitOperators.java

* Update SingleBitOperatorTest.java

* Update SingleBitOperators.java

* Update SingleBitOperators.java

* Update SingleBitOperatorTest.java

* Update SingleBitOperatorTest.java

* Update and rename SingleBitOperators.java to SingleBitOperator.java

* Update SingleBitOperatorTest.java

* Update SingleBitOperator.java

* Update SingleBitOperator.java

* Update SingleBitOperator.java

* style: declare private default constructor

* fix: remove `SetBitTest.java`

* Update and rename SingleBitOperator.java to SingleBitOperations.java

* Update SingleBitOperatorTest.java

* Update SingleBitOperations.java

* Update and rename SingleBitOperatorTest.java to SingleBitOperationsTest.java

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-30 10:06:45 +02:00
Arin
ea0eef128d
corrected test file name (#4422) 2023-09-28 18:30:41 +02:00
Janmesh Singh
566c27a996
WildcardMatching Added (#4404)
* Added WildcardMatching DP

* Wildcard Matching update

* Updated WildcardMatching

* Added WildcardMatchingTests

* WildcardMatching update

* Clang-formatting done

* WildcardMatching_Clang-formatting done

* WildcardMatching
2023-09-27 12:54:52 +03:00
Andrii Siriak
1cf193c7f4
Remove @siriak from CODEOWNERS 2023-09-27 10:10:03 +03:00
Lukas
8583ca3b40
Changing MaxFindTest (#4406)
* Changing MaxFindTest

* Update FindMaxTest.java

* Update FindMaxTest.java

* Update FindMaxTest.java

* Apply suggestions from code review

- add test case with unsorted array,
- test FindMax

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-26 19:36:56 +00:00
Lukas
bf777fff8f
Remove array len + Math.min (#4405) 2023-09-26 18:31:16 +03:00
Piotr Idzik
02bac7e3d4
Add test case with minimum not at index 0 (#4403) 2023-09-26 08:41:27 +03:00
Lukas
cada67b1eb
Remove array len + Math.max (#4401) 2023-09-25 19:10:04 +00:00
Lukas
01157f299c
Add negative FindMinTest (#4388) 2023-09-25 18:38:54 +00:00
Manan Solanki
9d8a0f36cf
Optimize MinimumPathSum (#4400) 2023-09-25 14:25:16 +00:00
Piotr Idzik
d6024f9cd4
Make FindMin a proper utilty class (#4397) 2023-09-24 10:25:28 +00:00
Piotr Idzik
fa77b50ef9
style: make FindMax a proper utilty class (#4398) 2023-09-24 13:55:19 +05:30
Lukas
ad4be217d4
Update FindMax.java (#4396) 2023-09-24 09:11:36 +02:00
Lukas
c1476d796c
Make FindMin more efficient (#4389) 2023-09-24 06:26:05 +00:00
Ansh Shah
d3a32135dc
Make MedianOfRunningArray Generic (#4392) 2023-09-24 08:50:43 +03:00
Manan Solanki
8803b1ead5
#4387 Enhance Minimum sum partition problem implementation (#4394)
* Enhance Minimum sum partition problem implementation

* Linter resolved

* Linter resolved

* Code review comments

* Code review comments

* Add validation for non-negative numbers

* Linter resolved

* style: fix formiatting

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-23 10:26:14 +02:00
Ansh Shah
fbe348b105
#4382 Bug Fix (#4384)
* #4382 Bug Fix

* #4382 Bug Fix

* Made Requested Changes

* Made Requested Changes

* Made Requested Changes

* Made Requested Changes

* Made Requested Changes

* Made Requested Changes

* Made Requested Changes

* Update src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* Update src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-21 06:05:26 +00:00
Piotr Idzik
906cd87731
style: avoid wildcard imports (#4386)
* style: import `assertEquals` explicitly

* fix: import `assertThrows`
2023-09-20 23:08:37 +05:30
Manan Solanki
12b6c29243
#4367 Enhance Knapsack problem (#4368)
* Enhance Knapsack problem

* Linter solved

* Linter solved

* Remove DynamicProgrammingKnapsack file, duplicate of Knapsack file

* Add null input testcase

* Linter resolved

* Updated meaningful test names

* Add check for negative weightCapacity

* Linter resolved

* Linter resolved

* Add check for non-positive weight

* Linter resolved

* fix: use proper formatting

* fix: use proper formatting

* fix: use proper formatting (I hope this will work now)

Sorry for the previous mess.

* Code review comments

* Code review comments

* Code review comments

* Code review comments

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-19 19:53:53 +00:00
Subhradeep Bera
26c2465328
Moved StackPostfixNotation.java from the Others section to the Stack section (#4372)
* Moved StackPostfixNotation.java from the Others section to the Stack section

* Put all stack related algo in a separate stack directory in the algorithms directory. The stack directory under data-structures now only contains various implementations of the stack data structure.

* formatted files
2023-09-18 21:27:36 +02:00
Andrii Siriak
a1844840fd
Add a note about leetcode to CONTRIBUTING.md 2023-09-17 23:43:55 +03:00
Piotr Idzik
58c21c5756
refactor: simplify ParseInteger (#4376) 2023-09-16 21:57:03 +03:00
Manan Solanki
5bb54977fe
#4369 Enhance UniquePaths (#4373)
* Enhance UnquiePaths DP problem solution

* Update testcases

* Linter issue resolved

* Code review comments

* Code review comments

* Code review comments

* Code review comments

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-14 19:45:16 +02:00
Bama Charan Chhandogi
34cf6dab28
add two sum problem (#4364)
* add two sum problem

* linter solved

* linter solved

* improve code

* linter solved

* improve code

* mini linter solved

* update code

---------

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
2023-09-12 08:00:08 +00:00
Manan Solanki
94621fb63e
Enhancing DisjointSetUnion data structure (#4366)
* Enhancing DisjointSetUnion data structure

* Linter resolved

* Linter resolved

* Linter resolved

* Linter resolved

* Added next line

* added next Line

* Resolve review comments

---------

Co-authored-by: Bama Charan Chhandogi <b.c.chhandogi@gmail.com>
2023-09-10 22:30:35 +05:30
Piotr Idzik
c54b8cddf3
Fix formatting of FloodFill (#4361) 2023-09-09 21:48:02 +03:00
Manan Solanki
a88abb7ac2
Fix : Floodfill infinite recursion due to same color (#4359)
Fix : Floodfill infinite recursion due to same color
2023-09-09 20:07:59 +02:00
Abhinav Pandey
81f38174a6
Fix small typos (#4357) 2023-09-08 16:10:22 +03:00
Andrii Siriak
77caf26033
Update CODEOWNERS 2023-09-07 21:17:08 +03:00
Lukas
fbef4023d5
Add Clear Bit (#4355) 2023-09-07 21:16:02 +03:00
Lukas
29a864b5b3
Add SetBit to bitmanipulation (#4348) 2023-09-06 14:46:45 +00:00
Bama Charan Chhandogi
fc693e8b51
Add Highest Set Bit algorithm (#4330) 2023-09-05 20:19:23 +00:00
Piotr Idzik
72247ed85c
chore: update actions/setup-java to v3 (#4352)
chore: use `actions/setup-java@v3`
2023-09-05 11:19:26 +05:30
Piotr Idzik
40a0515054
Update actions/checkout to v4 (#4351) 2023-09-04 22:21:39 +03:00
Bama Charan Chhandogi
09950d6097
Add Rotate a Linkedlist (#4345) 2023-09-02 19:32:28 +00:00
Punit Patel
a96ad84fac
Add different types of Mean (#4339) 2023-09-02 17:22:28 +00:00
Piotr Idzik
cfdbc413f1
Cleanup PalindromeSinglyLinkedList (#4336) 2023-09-02 17:05:10 +00:00
Piotr Idzik
657e85634f
Configure clang-format-16 in gitpod (#4347) 2023-09-02 20:00:54 +03:00
Piotr Idzik
f010a47608
chore: enforce InsertNewlineAtEOF in clang-format (#4343)
* style: insert newline at eof

* style: use `InsertNewlineAtEOF` in `clang-format`

* fix: use `clang-format-16`

* chore: update clang-format-lint-action to v0.16.2

---------

Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
2023-09-01 04:10:46 +00:00
BHARATH GADDAM
78ca465b1e
Update .gitignore (#4344)
Added comments on to this code for better readability.
2023-09-01 09:37:29 +05:30
Piotr Idzik
7dc0600ff4
Update gitpod/workspace-java-17 to 2023-08-30-14-07-38 (#4341) 2023-08-30 22:43:50 +03:00
Piotr Idzik
ea15f2bd98
Make SinglyLinkedList Iterable (#4334) 2023-08-28 07:11:07 +00:00
Bama Charan Chhandogi
80a4435038
Add tests for power using recursion algorithm (#4335) 2023-08-28 07:03:27 +00:00
tomkrata
ebd356e182
Add Miller-Rabin Primality Test (#4329) 2023-08-27 20:07:27 +00:00
Piotr Idzik
8d9c49dafe
Add PalindromeSinglyLinkedListTest (#4327) 2023-08-24 17:49:02 +00:00
Bama Charan Chhandogi
b4f786369b
Add find non repeating number algorithm (#4328) 2023-08-24 20:36:12 +03:00
Bama Charan Chhandogi
52f365a915
Add Index Of Right Most Set Bit Test (#4325)
* add Index Of Right Most Set Bit Test

* clang linter solved
2023-08-23 11:14:53 +05:30
Bama Charan Chhandogi
4bcddd323c
Add Preemptive Priority Scheduling Algorithm (#4323) 2023-08-20 19:40:23 +00:00
SwargaRajDutta
af80c8005d
Add Sliding Window Problem (#4322) 2023-08-18 14:08:40 +00:00
Bama Charan Chhandogi
b61faf4ede
Is power two algo added. (#4321)
* is power two algo added

* Linter solved

* Update src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java

* Update src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java

---------

Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
2023-08-18 12:53:09 +00:00
EdsTomato
68fdec5977
Add Tests for PancakeSort (#4318) 2023-08-16 18:57:36 +03:00
EdsTomato
ac14411b39
Add Tests for GnomeSort (#4315) 2023-08-15 16:39:12 +00:00
Bama Charan Chhandogi
2c16c86054
Add Numbers Have Different Signs (#4317)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
2023-08-15 19:36:00 +03:00
Snir Turgeman
18848574be
Make DFS and BFS search algorithms generic (fixes #4229) (#4230) 2023-08-13 11:59:26 +05:30
Bama Charan Chhandogi
1ef700e850
Add IsEven Algorithm (#4301)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
2023-08-12 23:06:39 +03:00
Bama Charan Chhandogi
251157059c
Add Reverse Bits Algo in Bit-Manipulation (#4299)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
2023-08-12 15:55:10 +00:00
Himesh Kohad
07945c7704
Add StrobogrammaticNumber (#4278) 2023-08-11 12:22:14 +00:00
Bama Charan Chhandogi
4fe419ebd8
Add Recursive Reverse of Linked List (#4292)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
2023-08-10 11:38:56 +03:00
Bama Charan Chhandogi
1ef5208b75
Add M-coloring Problem (#4282)
Co-authored-by: BamaCharanChhandogi <b.c.chhandogi@gmailcom>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
2023-08-05 22:00:26 +03:00
Piotr Idzik
c4a9ef1566
Add PowerOfTwoOrNotTest (#4279) 2023-08-04 12:31:47 +00:00
Piotr Idzik
ee23b6c2e5
Add tests for GenericRoot (#4276) 2023-08-03 23:14:59 +03:00
Piotr Idzik
087d523ed0
Make Factorial a proper utility class (#4267) 2023-07-29 08:15:03 +03:00
Albina Gimaletdinova
f83008d80a
Refactor factorial, add unit tests (#4266) 2023-07-28 22:02:04 +03:00
Ranjeet Kumar Jena
cc9afea036
Fix formatting (#4259)
Co-authored-by: Ranjeet Kumar Jena <ranjeetjena06@gmai.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2023-07-27 08:50:47 +05:30
Piotr Idzik
de50fc0294
Simplify StackPostfixNotation.postfixEvaluate (#4264) 2023-07-26 20:16:52 +03:00
Albina Gimaletdinova
fc274c84f8
Fix style in AmicableNumbers (#4263) 2023-07-26 16:52:46 +03:00
Piotr Idzik
e5c7a08874
Handle inputs like "2 +" in StackPostfixNotation (#4262) 2023-07-26 14:11:28 +03:00
Piotr Idzik
44dcebb699
Handle incorrect inputs in StackPostfixNotation (#4261) 2023-07-26 06:20:56 +00:00
Albina Gimaletdinova
dec3b98e4b
Refactor FibonacciJavaStreams and add unit tests (#4260) 2023-07-25 22:42:09 +03:00
Ranjeet Kumar Jena
ef4ef42ed3
Remove duplicated lines (#4258)
Co-authored-by: Ranjeet Kumar Jena <ranjeetjena06@gmai.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2023-07-25 13:36:00 +03:00
Piotr Idzik
3c80e262a7
Update ReverseNumber (#4257)
- removes an unused import,
- fixes the order of the of the _modifiers_ in the definition of the class `ReverseNumber`.
2023-07-25 14:14:59 +08:00
Andrii Siriak
fdb7fd0252
Update CODEOWNERS 2023-07-24 19:27:23 +03:00
Piotr Idzik
06ef351987
Add tests for SumOfArithmeticSeries (#4256) 2023-07-24 19:25:40 +03:00
Piotr Idzik
e897a93166
Fix formatting of NthUglyNumber (#4248) 2023-07-23 11:16:35 +00:00
Ranjeet Kumar Jena
1afc4cc319
Make code more idiomatic (#4249) 2023-07-23 13:51:52 +03:00
Piotr Idzik
b1ba262b64
Add clang-format to gitpod (#4247) 2023-07-23 00:19:50 +03:00
HManiac74
2488a2ad51
Code cleanup (#4246) 2023-07-22 15:23:00 +00:00
Piotr Idzik
3facb0d862
Add gitpod (#4243) 2023-07-22 16:20:35 +03:00
ngominhtrint
4effd28d80
Add unit tests for Minimum Path Sum algorithm (#4233)
* Add unit tests for Minimum Path Sum algorithm

* fix lint issues

* fix lint issues

* fix clang lint issue
2023-07-09 22:54:00 +05:30
Albina Gimaletdinova
9ecc3aae59
Add a new implementation for CheckAnagrams (#4231) 2023-07-06 16:56:59 +03:00
Albina Gimaletdinova
2456d86432
Add unit tests for ParseInteger (#4228) 2023-07-02 11:31:55 +03:00
Albina Gimaletdinova
4b45ac7e71
Add unit tests for PalindromeNumber (#4227) 2023-07-01 18:29:10 +00:00
Albina Gimaletdinova
8862a4dea5
Add unit tests for FibonacciNumberCheck (#4225) 2023-07-01 20:52:52 +03:00
Albina Gimaletdinova
bc699b86e5
Refactor BinaryTreeIsBalanced algorithm (#4222) 2023-06-26 22:26:17 +08:00
THIRUMURUGAN
05ca93eace
Rename surfaceAreaTriangle for clarity (#4220) 2023-06-23 19:39:10 +03:00
Piotr Idzik
63739f4933
refactor: simplify HammingDistance (#4218)
* refactor: make HammingDistance an utility class

* tests: add some tests, simplify logic of some

* refator: simplify logic in HammingDistance

* style: remove logging messages
2023-06-21 21:11:13 +05:30
Piotr Idzik
7a3273ae1d
tests: add tests for SieveOfEratosthenes (#4217)
* tests: add tests for SieveOfEratosthenes

* feat: throw for inputs <= 0

* refactor: simplify logic in SieveOfEratosthenes.findPrimesTill

* refactor: make SieveOfEratosthenes a utility class

* docs: update docs, fix typo
2023-06-20 23:58:53 +05:30
Piotr Idzik
87d6083bac
Add tests for EulersFunction (#4216) 2023-06-19 20:46:54 +03:00
Kim Areum
e29a22770b
Fix typo in README-ko.md (#4215) 2023-06-14 15:37:14 +03:00
acbin
415a04ea7f
Add automatic linter (#4214) 2023-06-09 20:05:14 +08:00
acbin
00282efd8b
style: format code (#4212)
close #4204
2023-06-09 18:52:05 +08:00
Piotr Idzik
ad03086f54
Remove main and add tests for CountWords (#4210) 2023-06-02 16:28:33 +00:00
Piotr Idzik
22002c9939
Generalize NthUglyNumber (#4209) 2023-06-02 14:17:26 +03:00
Piotr Idzik
4bbc4bd69f
Refactor ReverseNumber (#4208) 2023-05-31 09:07:55 +03:00
Bama Charan Chhandogi
b6e78a45ac
Add Octal To Binary Converter (#4202) 2023-05-30 07:37:50 +00:00
Piotr Idzik
5d7a59654f
Refactor LowestBasePalindrome (#4207) 2023-05-29 23:05:23 +03:00
Piotr Idzik
96c1a96647
Fix empty input handling in FindMax (#4206) 2023-05-28 23:45:13 +03:00
Piotr Idzik
4f15149804
style: handle empty input array in FindMin.findMin (#4205)
* tests: add test case with mininum not being at the beginning

* style: throw IllegalArgumentException when input is empty

* style: use enhanced for loop

* docs: update doc-str
2023-05-28 16:38:44 +05:30
Piotr Idzik
e14b30b88c
Fix empty input handling in GCD (#4199) 2023-05-27 17:58:56 +03:00
Glib
36232a8373
Fix typo (#4197) 2023-05-23 09:38:44 +03:00
Indrranil Pawar
9ce275c16d
Update FibonacciNumber.java (#4195) 2023-05-21 11:08:54 +05:30
Albina Gimaletdinova
deef2ae445
Refactor CreateBinaryTreeFromInorderPreorder (#4190) 2023-05-14 14:52:30 +03:00
Anirudh Pathak
0255705388
Add WordSearch (#4189) 2023-05-12 22:44:16 +03:00
Anirudh Pathak
de2696d0c5
Add Null/Empty check for param in average method (#4185) 2023-05-10 19:30:41 +03:00
Md. Asif Joardar
122f5e5556
Add Round Robin scheduling (#4184) 2023-05-10 16:04:55 +03:00
Md. Asif Joardar
3109c11c59
Add Partition Problem (#4182) 2023-05-09 13:21:11 +03:00
Albina Gimaletdinova
3a593d5d3c
Cover BSTRecursive with tests (#4180) 2023-05-06 21:10:33 +03:00
Manoj Kumar
89b7ee42e6
Add one more solution for anagrams check (#4175) 2023-05-05 20:50:47 +03:00
Rutikpatil0123
bb830e9559
Add tests for TwoSumProblem and reduce duplication (fixes #4177) (#4176) 2023-05-02 20:03:21 +03:00
Aditya Pal
fb18c27905
Add wiki link for DES (#4173) 2023-04-30 22:22:19 +03:00
Aditya Pal
19bd2408ff
Des (#4172)
* Update directory

* Add DES Encryption algorithm

* Update directory

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
2023-04-30 20:19:14 +05:30
Rutikpatil0123
db9c78a598
Remove duplicated ThreeSum problem (fixes #4169) (#4170) 2023-04-29 10:17:00 +03:00
Rutikpatil0123
7ed65b0a1e
Add climbing stairs (#4168) 2023-04-28 20:34:15 +03:00
Lieu Chi Tung
b55fc972ac
Add tests for HorspoolSearch (#4165) 2023-04-25 14:04:15 +03:00
Albina Gimaletdinova
f69cd7cfa2
Remove redundant code and add tests for BSTIterative (#4164) 2023-04-24 14:52:38 +03:00
Albina Gimaletdinova
4c18e60671
Refactor BSTFromSortedArray (#4162) 2023-04-22 07:53:12 +00:00
Albina Gimaletdinova
c01a382d94
Remove redundant tree traversals (#4161) 2023-04-21 11:41:24 +03:00
LOne2three
1551b8f50b
Add line sweep algorithm (#4157) 2023-04-19 08:12:30 +00:00
Saurabh Rahate
1dc388653a
Refactor Code Style (#4151) 2023-04-15 11:25:54 +03:00
Akshith121
1ce907625b
Fix NullPointer Exception (#4142) 2023-04-15 11:10:39 +03:00
Ishan Makadia
0c618b5ee8
Refactoring (#4146) 2023-04-14 08:34:47 +00:00
Andrii Siriak
d241fafd64
Remove blinking test for BufferedReader (#4153) 2023-04-14 11:33:22 +03:00
Rohan Anand
8259f0e9cf
Add Majority Element (#4131) 2023-04-13 15:28:36 +03:00
Ishan Makadia
181906d5f7
Refactor Code (MemoryManagementAlgorithms): Pull Up Variable (#4145) 2023-04-12 15:18:49 +00:00
Volodymyr Labliuk
7779c18ef6
Add More Tests (#4148) 2023-04-08 19:56:07 +03:00
Rohan Anand
f35e9a7d81
Update SieveOfEratosthenes.java (#4149) 2023-04-07 20:50:43 +08:00
Sukruti Mallesh
8798e042a8
Refactor BinaryToDecimal class (#4135) 2023-04-03 22:42:50 +08:00
duyuanch
d160156003
Update AbsoluteMax (#4140) 2023-04-03 22:39:17 +08:00
Saurabh Rahate
ad72c28d91
Remove unnecessary code (#4141) 2023-04-03 22:35:59 +08:00
duyuanch
805f09850c
Update SortUtils (#4139) 2023-04-02 23:09:51 +08:00
JarZombie
acfa2890a4
Fix DIRECTORY.md formatting (closes #3922) (#4124) 2023-04-01 21:43:47 +03:00
Isak Einberg
3b2ca81765
Fix spelling in Volume (#3893) 2023-03-24 19:22:56 +00:00
SwargaRajDutta
86c93146d9
Add Run-Length Encoding (fixes #3911) (#3916) 2023-03-19 09:51:48 +02:00
Andrii Siriak
0b6fa5c3b8
Remove old Gitter chat 2023-03-18 10:09:06 +02:00
Christian Clauss
3a56c963b3
Change Python version for directory workflow from 3.10 to 3.x to use newer and faster language versions (#3921) 2023-03-18 10:03:32 +02:00
Trần Quang Dự
2418604f7a
Add tests for SinglyLinkedList (#3913) 2023-03-12 13:49:17 +02:00
Enrique Clerici
a7e76c57a0
feat: Backtracking algorithms (All combinations) #3912 (#3917)
* ArrayCombination function which uses Combination.java by creating an array of 1 to n

* modified tests
2023-03-11 02:59:49 +05:30
Kumaraswamy B G
b6563cf37a
Add Buffered Reader (#3910) 2023-03-07 10:13:46 +02:00
Kumaraswamy B G
3e9dd776e5
Make LinkedQueue generic (#3909) 2023-03-05 19:08:42 +00:00
a-kbd
dd949e9b5d
Increase test coverage (fixes #3895 #3896) (#3897) 2023-03-05 21:03:08 +02:00
Siddhant Swarup Mallick
87f9ebcb29
Add Frizzy Number (fixes #3379) (#3906) 2023-03-01 17:16:32 +02:00
Siddhant Swarup Mallick
f3613382aa
Add All Paths from Source to Target (fixes #3359) (#3873) 2023-02-28 12:46:17 +02:00
Albina Gimaletdinova
3499c1bee6
Add postorder binary tree traversal (#3899) 2023-02-27 12:06:39 +00:00
Narek Karapetian
b98dc2c5b5
Fix linear probing hash map (#3902) 2023-02-26 21:15:48 +00:00
Albina Gimaletdinova
45923d6872
Add inorder binary tree traversal (#3898) 2023-02-25 20:58:06 +00:00
Stronshade
6d13d95e41
Graham scan algorithm (#3903)
* Added Graham scan algorithm #3894

* Added Graham scan algorithm (#3894)

---------

Co-authored-by: Stronshade <diegobrocker1999@gmail.com>
2023-02-25 18:31:51 +05:30
Isak Einberg
be13981e94
Add tests for 2D array binary search (#3892) 2023-02-23 18:49:24 +00:00
HumbleFool
6b9eb1b9c1
Add orderAgnosticBinarySearch (#3882)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2023-02-23 17:19:05 +00:00
Specialist Steak
3c0d94292c
Add Introspective Search (#3887) 2023-02-19 21:50:59 +02:00
Albina Gimaletdinova
541f490d1e
Valid BST: refactoring + added unit test (#3883)
Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2023-02-17 11:43:17 +00:00
Albina Gimaletdinova
d565edc69a
Added recursive&iterative preorder binary tree traversal (#3884)
Added recursive& iterative preorder binary tree traversal
2023-02-17 17:04:44 +05:30
Davide Nigri
e0b1235bef
Fix ArrayIndexOutOfBoundsException in LevenshteinDistance (#3871) 2023-02-15 20:34:36 +00:00
Shivanagouda Agasimani
69a428470c
Add Tarjans Algorithm (#3874) 2023-02-15 20:27:21 +00:00
Albina Gimaletdinova
a584ca248c
Refactor Level Order Traversal (#3869) 2023-02-14 12:33:14 +02:00
georgioct
c0fec8dfe2
Add Optimal Job Scheduling (#3868) 2023-02-08 18:09:38 +00:00
Shivanagouda Agasimani
39df47b5f2
Add Kosaraju Algorithm (#3859) 2023-02-08 18:05:52 +00:00
Hikmet Çakır
54d6f79acd
Add SimpleSubstitutionCipherTest (#3857) 2023-01-17 22:05:24 +02:00
YuLuo
b14f55096d
Fix LFUCache (#3847) 2023-01-15 11:28:16 +02:00
eloibru
b6c1d250f4
Add Conway Sequence (#3807)
Co-authored-by: Bruno Eloi <bruno.eloi@minfin.fed.be>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2023-01-14 12:22:15 +02:00
sadiul-hakim☪️
d5f140458a
Add two algorithms with matrixes (#3364) 2023-01-14 10:01:03 +00:00
Albina Gimaletdinova
351e85d264
Added same trees algorithm check with a unit test (#3845)
Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2023-01-13 20:07:56 +00:00
thanoskiver
44c05bf7db
Add Shortest Job First Scheduling (#3843) 2023-01-13 21:22:45 +02:00
Albina Gimaletdinova
3b6e3edbfb
Vertical order traversal refactoring, added unit test (#3844)
Vertical order traversal refactoring, added test
2023-01-13 19:26:15 +05:30
Albina
5aa417b6ae
Added Zigzag Traversal of a Binary Tree (#3811)
* Added Zigzag Traversal of a Binary Tree

* fixed file name

Co-authored-by: Albina Gimaletdinova <gimaletdinovaalbina@gmail.com>
2023-01-12 17:36:11 +05:30
Om Shinde
64181d6ea7
Remove unnecessary import (#3809) 2023-01-10 09:30:22 +02:00
Abinash Satapathy
9d86348cce
Update CONTRIBUTING.md (#3486) 2023-01-04 10:13:38 +02:00
Andrii Siriak
1aed52ba58
Trigger builds for all changes 2023-01-04 10:11:45 +02:00
Narek Karapetian
1eedaeb073
Move common tests for sorting algorithms to the base test class (#3782)
* bug fix for CircularBuffer + refactoring + add unit tests

* change Insertion sort to classical implementation + add isSorted function to SortUtils + add SortUtilsRandomGenerator for generating random values and arrays

* little fix

* move all common tests to SortingAlgorithmTest and utilize them

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2023-01-01 14:50:56 +00:00
김준홍
ce55420418
Add tests for Tree Sort (#3787) 2022-12-31 19:09:09 +00:00
adrianparas
9123474729
Add Leftist Heap (#3789)
Co-authored-by: Adrian Paras <aparas@terpmail.umd.edu>
2022-12-29 12:19:35 +00:00
Tanmay Jadhav
6a0035d872
Add description for SkipList.java (#3503) 2022-12-28 12:01:05 +00:00
Nathan Cheshire
c6694fc1bd
Simplifying boolean returns (#3796)
* Simplifying boolean returns

* add comment back
2022-12-18 03:03:09 +00:00
David Leal
fb09eb289e
fix: bug report form error 2022-12-17 19:35:47 -06:00
David Leal
7fe9928ee8
docs: improve the issue forms (#3797)
* docs: improve the issue forms

* Update directory

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
2022-12-17 18:58:52 +05:30
PuneetTri
5512fea0a8
Improve priority queues with max-heap (#3648) 2022-12-13 20:02:15 +02:00
Nishanth Chandra
8ba295b1ad
Added Order Agnostic Binary Search problem in Searches folder. (#3791)
* Added Order Agnostic Binary Search problem

* Update OrderAgnosticBinSearch.java

* Added JUnit Tests and removed redundant code.

* Made minor changes in JUnit Tests

* Removed tests for main folder and added docs.

* Added OrderAgnosticBinarySearchTest.java

* Renamed file to avoid errors.

* Updated the file to avoid build error
2022-12-12 00:43:27 +05:30
Hyun
219ec7c223
Create ShellSortTest (#3783)
Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-12-03 13:27:15 +00:00
Hyun
501aca3e31
Create SimpleSortTest (#3784) 2022-12-03 18:55:00 +05:30
Narek Karapetian
3f7e4d3f8f
Simplify Tim Sort (#3780) 2022-11-30 19:05:13 +02:00
Hyun
6c9090ffed
Create BucketSortTest (#3779)
* Create BucketSortTest

* Update src/test/java/com/thealgorithms/sorts/BucketSortTest.java

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-28 15:15:06 +05:30
PuneetTri
27fc872edb
Add JUnit tests for priority queue data structure (#3778) 2022-11-27 19:56:16 +08:00
김준홍
bdfecbe1c1
Added test cases to CombSort. (#3776)
* Add testcase to CocktailShakerSort Algorithm

* fixed method name to lowerCamelCase

* Added test cases to OddEvenSortTest

* Added test case to CombSort
2022-11-26 15:20:53 +00:00
Narek Karapetian
7692e8f47d
Heap Sort: Simplify (#3777)
* bug fix for CircularBuffer + refactoring + add unit tests

* change Insertion sort to classical implementation + add isSorted function to SortUtils + add SortUtilsRandomGenerator for generating random values and arrays

* little fix

* simplify heap sort

* Update src/main/java/com/thealgorithms/sorts/HeapSort.java

* Update src/main/java/com/thealgorithms/sorts/HeapSort.java

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-25 22:33:04 +05:30
Narek Karapetian
72468cc707
MergeSort: Simplify merge function (#3774)
* bug fix for CircularBuffer + refactoring + add unit tests

* change Insertion sort to classical implementation + add isSorted function to SortUtils + add SortUtilsRandomGenerator for generating random values and arrays

* little fix

* simplify merge function in MergeSort

* refactor one-liners

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-25 03:54:17 +05:30
Debasish Biswas
260f1b2bee
Remove duplicate KnapsackMemoization (#3769) 2022-11-19 13:32:01 +02:00
김준홍
9f78d1fcf7
Added test cases to OddEvenSort. (#3768)
* Add testcase to CocktailShakerSort Algorithm

* fixed method name to lowerCamelCase

* Added test cases to OddEvenSortTest
2022-11-18 18:34:34 +05:30
김준홍
ac71f6eb79
Added test cases to CocktailShakerSort. (#3766)
* Add testcase to CocktailShakerSort Algorithm

* fixed method name to lowerCamelCase
2022-11-16 13:39:02 +05:30
Thanh-Thai Tran
f7dee0d958
Add tests for recursive merge sort (#3510) 2022-11-12 16:10:13 +00:00
Taranjeet Singh Kalsi
b294ddcb38
Add AliquotSum (#3765) 2022-11-11 21:57:18 +02:00
Arya Sen
9cde14095c
Fix BFS (#3759) 2022-11-09 19:40:20 +00:00
Hyun
4990f791a6
Add Bead Sort (#3761) 2022-11-09 19:33:30 +00:00
rnzit
b8d6b1a9b0
Create CRC16.java (#3733)
* Create CRC16.java

* Create CRC16Test.java
2022-11-09 10:20:54 +05:30
Dnyanesh Nimbalkar
eb375a6015
Fix spelling (#3444) 2022-11-07 18:31:44 +00:00
Akshay Dubey
b75dce17c3
algorithm: Square free integer (#3760)
* feat: Add square free integer implementation

Closes #3402

* test: Add unit tests for square free integer

Closes #3402

* fix: Fix failing build

Changed static import for assertEquals()
Closes #3402
2022-11-07 14:31:44 +05:30
Narek Karapetian
58cf08f2fd
Modify Insertion sort implementation to classical one + add function insertion-sentinel sort. (#3622)
* bug fix for CircularBuffer + refactoring + add unit tests

* change Insertion sort to classical implementation + add isSorted function to SortUtils + add SortUtilsRandomGenerator for generating random values and arrays

* little fix

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-06 17:54:08 +05:30
kongleong86
c8ecd23183
Constructors BigInteger and BigDecimal used to wrap primitives should never be used. (#3627)
Constructors BigInteger and BigDecimal used to wrap primitives should never be used.

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-06 17:40:14 +05:30
Alexandre Velloso
cc17d60d5c
Add unit tests for SimpleSubCipher (#3688) 2022-11-06 10:21:22 +00:00
Aidar Djamalbek
1c7da7af25
Add LongDivision (#3691) 2022-11-06 12:18:14 +02:00
Taranjeet Singh Kalsi
37a1659e18
Add HarshadNumberTest (#3722) 2022-11-03 12:59:13 +00:00
Taranjeet Singh Kalsi
37db41fd6b
Add AutomorphicNumber (#3735) 2022-11-03 12:55:48 +00:00
Debasish Biswas
dfe733f777
Convert Issue Template to Issue form (#3641) 2022-11-01 17:40:55 +00:00
Aidar Djamalbek
1a391c2fe9
Add ValidParentheses (#3689) 2022-11-01 19:26:13 +02:00
Aidar Djamalbek
fea982d54d
Create Atoi Function.java (#3756)
* Create MyAtoi.java

There is a method in C++, which converts String to an Integer, called Atoi function, this is my own implementation of this function.

* Update directory

* Update MyAtoi.java

* Create MyAtoiTest.java

* Update directory

* Update directory

* Update directory

* Update MyAtoi.java

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-01 16:34:14 +05:30
Taranjeet Singh Kalsi
d418bbd1cf
Created PerfectNumberTest.java & Added function in PerfectNumber.java (#3751)
* Added function in PerfectNumber.java

Added isPerfectNumber2() in PerfectNumber.java

* Created PerfectNumberTest.java

* fixed isPerfectNumber()

fixed bug in isPerfectNumber() for negative numbers

* fixed typo

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-11-01 06:22:56 +00:00
Hyun
5864f3296f
Add BogoSort Tests (#3716) 2022-10-31 19:52:57 +00:00
shlokam
9e7456a2a8
Add tests for merge sort (#3715) 2022-10-31 19:26:49 +00:00
Amit Kumar
3542f1c4c1
Add check if tree is symmetric or not (fixes #3471) (#3472)
Co-authored-by: Amit Kumar <akumar@indeed.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-10-30 10:29:22 +02:00
Aayush2111
23eec39a29
Fibonacci optimized using binet's formula (#3728)
* Fibonacci optimized using binet's formula

* Update Fibonacci.java

* Update Fibonacci.java

* updated changes

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-10-30 09:26:08 +05:30
Taranjeet Singh Kalsi
8efc71e609
Added functions in Perimeter.java (#3739)
* Added functions and removed main

* deleted perimeterTest.java

deleted perimeterTest.java to create PerimeterTest.java

* Recreated PerimeterTest.java

Renamed perimeterTest.java to PerimeterTest.java and added test cases

* deleted PerimeterTest.java

* Recreated PerimeterTest.java

Recreated PerimeterTest.java from perimeterTest.java
2022-10-30 09:22:25 +05:30
Taranjeet Singh Kalsi
957f633c93
Added function and fixed bug in PerfectCube.java (#3655)
* Added another function to PerfectCube.java

Added another function to PerfectCube.java and fixed a testing mistake in line number 9

* Created PerfectCubeTest.java

Created PerfectCubeTest.java

* fixed PerfectCubeTest.java

* Fixed bug in PerfectCube.java

Fixed bug in PerfectCube.java in isPerfectCube() function for negative numbers. Now It gives the correct output for perfect negative numbers.

* removed main() in PerfectCube.java
2022-10-29 11:57:17 +05:30
Taranjeet Singh Kalsi
5ab1b6c319
Created VolumeTest.java & Fixed Bugs in Volume.java (#3682)
* Fixed functions and removed main() in Volume.java

Fixed calculation errors in volumeSphere() and volumeHemisphere() functions and removed main() and changed functions access specifier from private to public

* Created VolumeTest.java

Created VolumeTest.java JUnit Tests for Volume.java

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-10-28 00:35:59 +05:30
Taranjeet Singh Kalsi
bd267bb7d8
Fixed error in Palindrome.java and gave semantic names to functions (#3643)
* fixed error and changed functions names

fixed error at line 57 and gave semantic names to functions with comments

* renamed functions

renamed functions to match with original functions' names in the file

* Updated TestCases

Updated TestCases and changed a function name

* Removed main() and changed function name

Removed main() and changed the function name from isPalindromeStringBuilder to isPalindrome

* fixed typo

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-10-28 00:17:16 +05:30
Taranjeet Singh Kalsi
acf7a86b96
Added function in Pangram.java (#3703)
* Added function in Pangram.java

Added isPangramIndexOf() function in Pangram.java

* Added Tests for new function

Added Tests for isPangramIndexOf() function

* fixed typo

* changed function name

* changed function name

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
2022-10-27 23:26:34 +05:30
Nandini Anagondi
b2393d62a0
Add Test case for EggDropping (#3687) 2022-10-27 20:52:45 +03:00
Andrii Siriak
703c60fa7a
Update CODEOWNERS 2022-10-27 18:03:22 +03:00
Nandini Anagondi
8504e6ad35
Add test case for RomanToInteger (#3686) 2022-10-27 20:42:57 +08:00
Nandini Anagondi
23949cac47
Add test case for BinaryToDecimal (#3684) 2022-10-27 20:40:08 +08:00
Nandini Anagondi
2c9edc95b8
Add test case for HexaDecimalToBinary (#3683) 2022-10-27 20:34:01 +08:00
Nandini Anagondi
838916d8e9
Add test case for hexadecimal to decimal (#3685) 2022-10-27 19:17:38 +08:00
rashmibharambe
0bed437eb2
Add test case for BinaryToHexadecimal (#3694) 2022-10-27 18:15:39 +08:00
rashmibharambe
c7b69561a5
Add test case for BinaryToOctal (#3696) 2022-10-27 18:11:16 +08:00
rashmibharambe
a1a2a849c2
Add test case for DecimalToHexaDecimal (#3697) 2022-10-27 18:07:13 +08:00
rashmibharambe
38eadd928a
Add test case for CatalanNumber (#3698) 2022-10-27 17:34:39 +08:00
harshalkhachane
b46bf0d9b0
Add test case for OctalToDecimal (#3678) 2022-10-27 00:06:25 +08:00
harshalkhachane
0bbacb1925
Add test case for OctalToHexadecimal (#3679) 2022-10-27 00:04:26 +08:00
Taranjeet Singh Kalsi
a0d03e814a
Update WordLadderTest.java & WordLadder.java (#3674) 2022-10-26 21:14:03 +08:00
harshalkhachane
2e25f89c36
Add test case for HexToOct (#3675) 2022-10-26 21:10:25 +08:00
harshalkhachane
0365afa16a
Add test case for IntegerToRoman (#3676) 2022-10-26 21:03:04 +08:00
Taranjeet Singh Kalsi
eecec0f706
Add test case for LetterCombinationsOfPhoneNumber (#3662) 2022-10-26 16:38:24 +08:00
Artan.sh
c9e1d96147
Fix typos (#3615)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-10-26 07:40:06 +00:00
Andrii Siriak
a4ede35bef
Update pull_request_template.md 2022-10-26 10:23:38 +03:00
Harshal
0953236b4c
Add tests for WordLadder (#3668) 2022-10-26 07:18:33 +00:00
Harshal
0a5ee18079
Add tests for HowManyTimesRotated (#3669) 2022-10-26 10:16:02 +03:00
Harshal
3aadb9da1e
Add tests for vowels check (#3658) 2022-10-26 09:15:25 +03:00
Harshal
9a09a9e772
Add test case for Rotation (#3667) 2022-10-26 09:44:37 +08:00
Alexandre Velloso
8c6ed9c240
Add unit test for RSA cipher (#3664) 2022-10-26 09:10:27 +08:00
Alexandre Velloso
f8897f166d
Add unit tests for Caesar cipher (#3665)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-10-26 09:01:35 +08:00
Alexandre Velloso
7ef75980d5
Add unit tests for Vigenere cipher (#3666) 2022-10-26 08:57:51 +08:00
Taranjeet Singh Kalsi
fd3386a0db
Removed extra loop in Anagram.java (#3654) 2022-10-25 12:19:03 +00:00
Debasish Biswas
315e947c87
Add more tests (#3601) 2022-10-25 12:15:41 +00:00
Philippe CANCELLIER
6235fd6505
Add tests for Average (#3652) 2022-10-25 15:00:53 +03:00
Debasish Biswas
d88b70113f
Fix naming LinkList_sort -> LinkListSort (#3640) 2022-10-24 21:27:17 +03:00
Siddhant Deepak Pradhan
1e16709680
Update README.md (#3362) 2022-10-23 05:59:40 +00:00
Amit Kumar
c9e7b219a7
Add unit test for CeilInBinarySearchTree (fixes #3395) (#3396)
Co-authored-by: Amit Kumar <akumar@indeed.com>
2022-10-23 05:47:00 +00:00
James Tuong
f35aeb5311
Add ReverseStringTest (#3607)
Co-authored-by: jtuong <Rofleveryday1?>
2022-10-22 19:23:35 +00:00
laks-mi1099
8d4b048cb3
Add LongestValidParenthesesTest (#3612) 2022-10-22 19:21:54 +00:00
ff124012
bf03d16303
Add test for Lower (#3328) 2022-10-22 19:17:18 +00:00
laks-mi1099
ea05286c86
Add tests for PowerSum (#3603) 2022-10-22 19:11:40 +00:00
Andrii Siriak
51f9596649
Update pull_request_template.md 2022-10-21 22:05:14 +03:00
samratpodder
3ef3d761c6
Add DP Solution to Subset Count (#3580) 2022-10-20 19:51:54 +00:00
kongleong86
f2e0126469
Use GCM mode in AES (fixes #3324) (#3325) 2022-10-18 21:24:25 +03:00
Amarildo Aliaj
8803b7f5e7
Add tests for Area (#3358) 2022-10-18 21:03:58 +03:00
Rebecca Velez
ddcb5cfead
Create test cases for SlowSort (closes #3361) (#3363) 2022-10-17 15:15:06 +00:00
Kumaraswamy B G
8855cf9525
Optimize Hashmap implementation (#3533) 2022-10-17 14:36:09 +00:00
Debasish Biswas
d5f8e5f87a
Fix grammar in pr template (#3346) 2022-10-15 09:16:15 +03:00
Debasish Biswas
cdd12a128d
Add Dual Pivot QuickSort (#3357) 2022-10-15 06:06:36 +00:00
Akshay Dubey
efac505a6d
Add twin prime (#3312) 2022-10-14 09:36:26 +00:00
Ricardo Ramos
c805437c0c
Add tests for CountChar (#3334) 2022-10-12 18:42:24 +00:00
Smiti Maheshwari
c59fc923bf
Add fcfs scheduling (#3335)
Co-authored-by: Smiti <smmaheshwari@paypal.com>
2022-10-12 21:39:34 +03:00
Ricardo Ramos
911b98472c
Add Tests for Dudeney Number (#3336) 2022-10-10 17:25:06 +00:00
samratpodder
8661d07276
Add sum without using any mathematical operators (#3473) 2022-10-10 20:19:01 +03:00
Aitor Fidalgo Sánchez
40dc1c483d
Fix scope of junit-jupiter-api artifact in pom.xml (fixes #3321) (#3322) 2022-10-09 21:04:02 +03:00
Aitor Fidalgo Sánchez
03a4832a7d
Add an interface for matrix search algorithms (closes #3461) (#3464) 2022-10-09 14:45:36 +03:00
Shashwat Gupta
cce1dbd124
Add algorithm to search for an element in 2D array (#3306) 2022-10-09 12:23:36 +03:00
Aitor Fidalgo Sánchez
302db81bb8
Fixes #3323 Javadoc generation errors in backtracking algorithms (#3326) 2022-10-08 14:10:34 +03:00
Narek Karapetian
471d2c0b5d
Fix CircularBuffer and add unit tests (#3411) 2022-10-06 16:51:10 +08:00
acbin
e96f567bfc
Format code with prettier (#3375) 2022-10-03 17:23:00 +08:00
Shashwat Gupta
32b9b11ed5
Update Directory.md (#3309) 2022-10-01 13:00:51 +03:00
J2mF
e4eb99ff18
Add A5 Cipher (#3292) 2022-09-27 16:33:13 +00:00
Amarildo Aliaj
8ca571d887
Add Collatz Conjecture (#3290) 2022-09-26 04:51:21 +00:00
Aitor Fidalgo Sánchez
2847953a03
Remove duplicate in pom.xml (#3288) 2022-09-25 15:47:47 +00:00
Akshay Dubey
ea8e0463ef
Add Liouville lambda function (#3284) 2022-09-24 13:18:12 +00:00
Mihir Sawant
2fbb1d6402
Add hamming distance (#3270) 2022-09-24 16:14:39 +03:00
Akshay Dubey
07a5531f1a
Add prime factorization algorithm (#3278) 2022-09-21 19:29:20 +00:00
valjamwo
d56eaa58af
Add LRUCacheTest and MRUCacheTest (fixes #3263) (#3277) 2022-09-19 20:55:15 +03:00
Aitor Fidalgo Sánchez
a2dd154ad6
Add BubbleSort unit tests (#3275) 2022-09-19 17:23:08 +00:00
Kalash Jain
276bbe2530
Fix errors in Directory.md (#3272) 2022-09-18 21:27:15 +03:00
Akshay Dubey
a41656a311
Add pollard rho algorithm (#3260) 2022-09-16 07:27:40 +00:00
0x3C50
9c418ba827
Add pangram check tests (#3267) 2022-09-15 13:31:11 +00:00
Pratyush Singh
8f18b92f6e
Add count set bits algorithm (#3262) 2022-09-14 17:05:23 +00:00
Mann
20a1f40c5a
Add Isomorphic Strings (#3253)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-09-13 02:29:26 +03:00
Poorva Diwan
1e4c4a112d
Add Perimeter Calculation Algorithms (#3247)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-09-08 10:05:06 +03:00
vie02
d22420fea8
Fix off-by-one error (fixes #3248) (#3250) 2022-09-07 09:01:22 +03:00
Akshay Dubey
69d0070c99
Add mobius function (#3241) 2022-09-03 06:34:06 +00:00
Shashwat Gupta
6cfb628487
Add Binary Search in 2D Array (#3240) 2022-09-03 09:31:55 +03:00
David Liu
9e37775506
Replace List in BFS with Queue (#3231) 2022-08-28 05:46:58 +00:00
Shashwat Gupta
c500e8ae5a
Add Newton Raphson method (#3224) 2022-08-27 09:40:06 +03:00
Siddhant Swarup Mallick
2ffcff12fc
Fix fast inverse sqrt (fixes #3199) (#3228)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-08-24 13:37:07 +03:00
Zohaib Hussain
12a4e27213
Fix printTreepre (#3218) 2022-08-18 20:40:20 +03:00
LauKinHoong
3f69603440
Add least common multiple algorithm (#3216) 2022-08-17 08:59:07 +03:00
HManiac74
e87e097f06
Cleanup unused imports (#3217) 2022-08-17 08:30:15 +03:00
AmirMohammad Hosseini Nasab
05660dae92
Add K-D Tree (#3210) 2022-08-13 11:00:00 +00:00
Kunal Patil
854b900257
Add Josephus Problem Recursive Solution (#3208) 2022-08-13 10:50:39 +00:00
Mohit Chakraverty
4aa58b63d2
Fix grammar in CONTRIBUTING.md (#3215) 2022-08-12 19:28:19 +03:00
AmirMohammad Hosseini Nasab
3e8f30c72a
Add Lazy Segment Tree (#3209) 2022-08-10 17:27:53 +00:00
Ong Lip Wei
d63813e0a2
Add maze recursion algorithm (#3204) 2022-08-08 20:47:04 +03:00
tackhwa
d82a2006ba
Add Binary Insertion Sort (#3206) 2022-08-07 08:19:25 +00:00
Marcus
b36f359076
Add Strand Sort (#3205) 2022-08-06 20:22:42 +00:00
tackhwa
92bd9ba3c9
Add Rabin-Karp String Search Algorithm (#3201) 2022-08-05 20:29:35 +03:00
Marcus
965c20381c
Add KMP String Search Algorithm (#3200) 2022-08-03 20:46:44 +03:00
edison3701
3918d9eaee
Add three new distance formulas (#3203)
-Manhattan Distance
-Hamming Distance
-Minkowski Distance
2022-08-02 21:39:52 +03:00
Tuca Wang
9b13852f20
Fix missing package paths (#3196) (#3198) 2022-07-22 22:51:38 +03:00
Hien Nguyen
898c2f6414
Add tests for Selection Sort (#3091) 2022-07-19 20:40:59 +03:00
haeshed
0abce97682
Add Hash Table with Cuckoo Hashing (#3191) 2022-07-18 18:01:29 +00:00
Divya Raichura
ffd02504d9
Add generic hashmaps (#3195) 2022-07-17 23:00:55 +03:00
Jainam Kothari
1a9937c7cb
Add index validation to Min Heap and Max Heap (#3189)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-07-13 17:40:21 +00:00
Ankush Banik
b2f6827c36
Add Tests for DigitalRoot Algorithm (#3186) 2022-07-12 06:29:49 +00:00
Hikmet Çakır
199c85d191
Add Polybius Cipher (#3185) 2022-07-11 15:15:14 +00:00
Ankush Banik
f7bd7682ba
Update Combinations.java and add test case (#3184) 2022-07-08 19:31:09 +08:00
Ankush Banik
826b612d0d
Add testcase to Ceil Algorithm (#3183)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-07-07 14:24:24 +08:00
tuca
8c8a61a224
Fix CircleLinkedList toString (#3182) 2022-07-07 14:18:46 +08:00
Susobhan Das
f7c40ad749
Change filename for Intersection.java file (#3178)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-07-05 17:50:46 +08:00
Ankush Banik
3fb9a606a3
Add test case to Binomial Coefficient Algorithm (#3179)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-07-05 17:37:11 +08:00
Ankush Banik
f273b30998
Add test case to BinaryPow Algorithm (#3177)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-07-04 20:53:56 +08:00
Ankush Banik
8b8e98e89a
Fix TreeRandomNode Algorithm (#3174)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-07-03 17:49:32 +08:00
Arthita Paul
b0f21803d1
Simplify CheckVowels (#3172) 2022-07-01 14:58:28 +03:00
Sahil Parekh
6665ab262c
Add a check of the existance of a next node (#3051)
* Fix #2976

Co-authored-by: Sahil Prafulkumar Parekh <sh883193@dal.ca>
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-06-29 20:02:40 +08:00
Ankush263
2a23770873
Add tests for Amicable Numbers (#3168) 2022-06-28 18:36:06 +00:00
Speecker
bf3ad33d34
Fix typo (#3167) 2022-06-27 05:36:39 +00:00
Ankush263
c750283a1c
Add testcase to Automorphic Number Algorithm (#3166) 2022-06-27 08:34:42 +03:00
Arindam Paul
0d97d0bc8e
Add Devcontainer Support (#3156)
Co-authored-by: Arindam Paul <arindam.paul.1989@gmail.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-06-24 16:29:08 +03:00
Akshay Dubey
85c836c795
Add quick sort tests (#3165) 2022-06-24 08:57:01 +03:00
Sedat Aybars Nazlica
d8c9c1ac85
Add Hamming Distance (#3164) 2022-06-23 09:29:08 +03:00
gkgaurav31
e572354976
Fix off-by-one mistake in MinHeap.java (#3162) 2022-06-23 09:27:21 +03:00
Hai Nguyen
c0b2c56628
Add tests for PasswordGen (#3163) 2022-06-23 09:23:11 +03:00
Akshay Dubey
2a2c575c89
Add LFU Cache (#3161) 2022-06-22 19:31:24 +03:00
Artem Boiarshinov
a910d8754e
Specify python version for CI job (#3157) 2022-06-22 22:00:33 +08:00
Artem Boiarshinov
d14a5d1eed
Fix SkipList remove operation (#3160) 2022-06-22 21:56:35 +08:00
Artem Boiarshinov
e59568bc5e
Add Skip List (#3154) 2022-06-21 10:41:22 +03:00
Akshay Dubey
22be348c54
Add algorithm to find Hamiltonian cycle (#3151) 2022-06-20 21:07:41 +03:00
Ankush263
6472d33092
Add heaps folder (#3150)
Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-06-20 21:04:13 +03:00
BI11-061 Hoàng Anh Đức
678ec396fc
Add tests for isPerfectSquare (#3131) 2022-06-15 19:19:27 +03:00
Ankush263
4ccb9f460f
Fix the folder structure (#3141) 2022-06-14 21:31:50 +08:00
Hai Nguyen
a33a26a9d1
Cover CheckAnagrams with tests (#3124) 2022-06-14 10:50:50 +03:00
Jonathan Taylor
6c4092a46b
Add Topological Sorting Algorithm (#3060)
Co-authored-by: thanhtri122002 <thanhnt122002@122002>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
Co-authored-by: Anh Pham <62592224+anhpham197@users.noreply.github.com>
Co-authored-by: SanOtaku <SanOtaku098@gmail.com>
Co-authored-by: Raghav Taneja <97575679+RaghavTaneja@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
Co-authored-by: Hai Nguyen <88832724+ntquanghai@users.noreply.github.com>
Co-authored-by: Utkarsh Yadav <Utkarshrock1510@gmail.com>
Co-authored-by: Phạm Minh Hiếu <84634830+Ph1eu@users.noreply.github.com>
Co-authored-by: nguyenviettrung-bi11276 <101244039+nguyenviettrung-bi11276@users.noreply.github.com>
Co-authored-by: TaiNguyen2001 <102779475+TaiNguyen2001@users.noreply.github.com>
Co-authored-by: de <88503943+HuyQHoang@users.noreply.github.com>
Co-authored-by: thanhtri122002 <93241140+thanhtri122002@users.noreply.github.com>
Co-authored-by: thanhtri122002 <thanhnt122002@122002>
2022-06-11 21:53:33 +03:00
Artem Boiarshinov
ec1ab53eea
Reduce memory usage of bloom filter (#3115) 2022-06-10 20:44:23 +03:00
Quốc Thái Vũ
ba3c0319ed
Add tests for sum of digits (#3083) 2022-06-09 09:50:16 +03:00
Squirrellllllllllll
8982692ca6
Add tests for factorial (#3107) 2022-06-09 09:47:31 +03:00
thanhtri122002
45f3e5b6de
Add a test for average (#3084)
Co-authored-by: thanhtri122002 <thanhnt122002@122002>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-06-08 18:19:42 +03:00
de
77e481336e
Add test for Armstrong (#3104)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-06-08 18:15:01 +03:00
TaiNguyen2001
9b4ac70403
Add more tests for findMin (#3102)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-06-07 08:21:46 +03:00
nguyenviettrung-bi11276
8e8d11a63c
Add Tests for FindMin (#3079) 2022-06-04 19:49:37 +03:00
Phạm Minh Hiếu
2fb87c37fc
Add tests for PythagoreanTriple (#3070) 2022-06-02 17:21:40 +03:00
Utkarsh Yadav
2bcae52dce
Rename CPUalgorithms to MemoryManagmentAlgorithms (#3071) 2022-05-31 16:12:59 +03:00
Hai Nguyen
e5057defa7
Add tests for findMax (#3067) 2022-05-30 14:11:30 +03:00
Raghav Taneja
bb5b50dea2
Add Z-Score Algorithm (#3065)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-05-29 11:16:04 +03:00
SanOtaku
2e09e44a38
Add ZigZag Encoding and Longest Nonrepetitive Substring Algorithms (#3058) 2022-05-26 12:47:23 +03:00
Anh Pham
f35eef285a
Add tests for GCD and PrimeCheck (#3062) 2022-05-25 13:46:20 +03:00
Sahil Parekh
550adb2287
Fix Bug in Tim Sort (#3050)
Co-authored-by: Sahil Prafulkumar Parekh <sh883193@dal.ca>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-05-20 20:19:18 +03:00
Akshay Dubey
f9b788f7f4
Add Blowfish Algorithm (#3052) 2022-05-18 20:29:31 +03:00
Raghav Taneja
239b274069
Add Euclidean Distance Formula (#3047) 2022-05-11 22:23:56 +03:00
Siddhant Swarup Mallick
10f41eeee9
Add max of mins algorithm (#3044) 2022-05-08 12:05:05 +03:00
Omar
9b5dca5534
Add directories (#3043) 2022-05-05 19:29:20 +03:00
Omar
f272d8a949
Add Bloom Filter (#3042) 2022-05-04 09:24:19 +03:00
Omar
00c758a299
Add Fibonacci Heap (#3037) 2022-05-02 18:56:05 +03:00
RaghavTaneja
c52b2a649c
Add Standard Deviation (#3039) 2022-05-01 10:32:03 +03:00
Omar
1a230bd61e
Add New Prime Check (#3036) 2022-04-29 16:30:05 +03:00
Shuangchi He
3ebba74e04
Fix some typos (#3038) 2022-04-28 21:09:25 +08:00
RaghavTaneja
41be089f6a
Add Tests for Heron's Formula (#3035) 2022-04-28 10:40:13 +03:00
BranAndSceolan
dfdce96c6e
Add Dutch National Flag Sort (#3025)
Co-authored-by: Antonia Strack <antonia.strack@thm.mni.de>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-04-25 17:02:15 +03:00
BranAndSceolan
99ff5163e3
Add Wigglesort (#3032)
Co-authored-by: Antonia Strack <antonia.strack@thm.mni.de>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-04-25 16:54:33 +03:00
Samir M'Sallem
7c31c5bada
Add else clause for node (#3014)
Co-authored-by: Samir M'Sallem <samir.msallem@valtech-mobility.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-04-22 19:50:04 +03:00
Yadunandan Bhat
64f1e51df4
Add pigeonhole sort (fixes #2992) (#3013) 2022-04-21 15:35:27 +03:00
Cristiano Jesus
1320748c88
Code refactor for AbsoluteMin improvements (#3031)
Fix #3030

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-04-21 09:34:40 +08:00
Cristiano Jesus
c8b0a201da
Code refactor for AbsoluteMax improvements (#3029)
Fix #3028

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-04-21 09:33:29 +08:00
Cristiano Jesus
9f7613b467
Code refactor for AliquotSum improvements (#3027)
Fix #3026
2022-04-21 09:31:55 +08:00
Cristiano Jesus
4b15b2c021
Code refactor for ADTFraction improvements (#3016)
Fix #3015

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-04-20 16:20:47 +08:00
Cristiano Jesus
5eed0849ef
Code refactor for AbsoluteValue improvements (#3018)
Fix #3017

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-04-20 16:17:44 +08:00
Cristiano Jesus
64b624efb2
Code refactor for AbsoluteMax improvements (#3020)
Fix #3019

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-04-20 16:15:30 +08:00
Cristiano Jesus
02375e0683
Code refactor for AbsoluteMin improvements (#3022)
Fix #3021
2022-04-20 16:12:55 +08:00
Vivek
719e1d8132
Update Armstrong Number (#2981) 2022-04-10 17:11:05 +03:00
Eduardo Cabral
cca4038008
Run actions only if code related files changes (#3000) 2022-04-07 20:49:44 +03:00
Siddhant Swarup Mallick
060069cf73
Add Golomb Sequence (fixes #2889) (#2991) 2022-04-06 19:02:30 +03:00
acbin
ab544c3b9f
Fix Null Pointer Exception in strings/Upper (#3005)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-04-05 17:02:20 +08:00
acbin
e7ff986414
Fix CheckVowels (#3004)
Close #2990
2022-04-04 16:44:38 +08:00
Aldo Telese
8d099ee7d1
Update Anagrams and add unit test (#3002)
* Add test for Anagrams
* Update Anagrams.java

Co-authored-by: Yang Libin <contact@yanglibin.info>
2022-04-04 16:34:27 +08:00
Aldo Telese
140f6ec6e3
Add test for Upper (#3001) 2022-04-04 16:21:53 +08:00
Aldo Telese
1b02b41fcc
Add test for Palindrome (#2993) 2022-04-03 16:19:24 +03:00
funCodeSonali
77bcd4daa3
Fix singly linked list (#2988) 2022-04-03 16:11:43 +03:00
Aldo Telese
63f486c6ba
Add tests for CharacterSame (#2989) 2022-03-31 20:54:48 +03:00
Eduardo Cabral
1fc897ed4d
Fix outdated directory.md (#2995) 2022-03-31 11:19:39 +08:00
RishabhSrivastava1423
d53c2cef8c
Modify singly linked list swap function to swap nodes (#2983) 2022-03-26 21:31:11 +02:00
Aldo Telese
7d5de041eb
Test alphabetical (#2987) 2022-03-24 08:03:36 +02:00
Aldo Telese
8b71a15cbb
Add test for Pangram.java (#2986) 2022-03-23 22:34:50 +02:00
Rushipatel0995
1d5d672fbd
Refactor to remove code smells (#2982)
Co-authored-by: Rushi <rs397441@dal.ca>
2022-03-21 20:35:11 +02:00
rameez471
4da27429c4
Add Largest Rectangle Problem (fixes #2916) (#2971) 2022-03-14 23:19:42 +02:00
XU ZHIWEI
a01be023e1
Add find kth element in an array (#2968) 2022-03-12 11:59:34 +02:00
Nikhil Bisht
260a302563
Fix bound checks in flood fill (fixes #2836) (#2974) 2022-03-12 11:56:43 +02:00
20481A05F2
63637c439d
Remove white spaces (#2975) 2022-03-11 09:39:55 +08:00
leren1
49a4a83ada
Refactor and add tests (fixes #2963) (#2964) 2022-03-10 19:56:26 +02:00
H1manshu-$oni
f0b52022e8
Fix spelling (#2973) 2022-03-08 17:46:01 +02:00
Nikhil Bisht
1ac1a5a6a5
Add Postfix to Infix using Stack (fixes #2339) (#2970) 2022-03-06 08:59:45 +02:00
leren1
fe61eb2bdf
Fix rounding in FFT (fixes #2961) (#2962) 2022-03-05 19:16:34 +02:00
leren1
8bf74929e3
Refactor algorithm & add Junit test (fixes #2959) (#2960) 2022-03-04 18:25:42 +02:00
Siddhant Swarup Mallick
cf07de8afa
Add Newman–Shanks–Williams prime (#2884) (#2955)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-02-26 09:54:10 +02:00
Changjiyuan
68e2ba29d4
Fix typos (fixes #2941) (#2948) 2022-02-20 10:11:41 +02:00
Siddhant Swarup Mallick
2cb4c2fff4
Add unique paths (fixes #2873) (#2943)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-02-19 13:59:14 +02:00
ZiQiang Cao
a30f08b8b2
Fix typo (#2950) 2022-02-18 21:58:22 +02:00
Siddhant Swarup Mallick
0a062d4616
Add tests for Kadane algorithm (#2877) (#2939)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-02-13 20:24:31 +02:00
alexlemo20
adadb2f6d6
Unify dynamic memory allocation algorithms (#2935) 2022-02-10 19:08:21 +02:00
cpiao3
12c67bc501
Add permutations and combinations (#2932) 2022-02-09 20:57:14 +02:00
Saumya
101d08ae24
Add Square Root by Babylonian Method (#2883) 2022-01-30 20:49:32 +02:00
Suraj Kumar
e4fa83bd29
Add select random tree node algorithm (#2906)
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-01-21 21:20:11 +02:00
Siddhant Swarup Mallick
857c4aafb2
Add linked list sorting (#2882)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-01-19 21:35:43 +02:00
Kabir
76fbe7c9e9
Update LongestPalindromicSubstring - Remove ; (#2905)
Removing unnecessary semi-colon ';'

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-01-13 09:59:11 +08:00
Subhro Acharjee
ab9f74c2ee
Add BigInteger to karprekar number (#2899)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-01-12 22:23:53 +02:00
ArunPrasanth-V
2a27d09a17
Update PascalTriangleTest (#2900)
* Update in indentation to makes code more readable

Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2022-01-11 14:56:59 +08:00
Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ
5c7c6c4702
Add volume of prism and pyramid (#2902) 2022-01-10 17:36:37 +08:00
Subhro Acharjee
a0a392297e
Add kaprekarNumberInRange (#2894)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2022-01-07 21:50:32 +02:00
Preshita01
97dfbfd67f
Fix formatting errors in DIRECTORY.md (#2896) 2022-01-04 16:11:28 +02:00
Subhro Acharjee
549a27a327
Add bruteforce to the caesar cipher (#2887) 2022-01-01 23:16:53 +02:00
Akshay Dubey
32cdf02afb
Add Pronic Number (#2867)
* Add Pronic Number

* Update directory

* Add unit tests for Pronic Number implementation

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-12-21 22:06:16 +02:00
s-devran
98656cb0cd
Add Kaprekar Numbers (#2881) 2021-12-15 16:55:04 +02:00
Hardik Soni
b1242e045b
Add Pascal's Triangle (#2871)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-12-13 22:04:19 +02:00
sangin-lee
734f7a4a04
Add Array Left Rotation (#2869) 2021-12-11 18:54:12 +02:00
Siddhant Swarup Mallick
0bb7db2d87
Add anagrams (#2859)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-12-09 20:47:45 +02:00
Nils-Goldmann
66d8d51de6
Add Quick Select (#2860)
Co-authored-by: Nils Goldmann <goldman09@mi.fu-berlin.de>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-12-08 21:38:19 +02:00
Andrii Siriak
8e01cd46bf
Switch CI builds to Maven (#2863) 2021-12-07 08:22:28 +02:00
Mohit Kumar
1f50c40e5d
Add Next Greater and Next Smaller Elements using Stack (#2858) 2021-12-06 22:07:26 +02:00
Suraj Kumar
bc6de37a53
Add RandomNode in lists section (#2851)
Co-authored-by: Yang Libin <contact@yanglibin.info>
2021-11-30 10:22:01 +08:00
Yang Libin
b870de4db4
Fix formatting in Juggler Sequence (#2846) 2021-11-27 12:55:32 +02:00
Akshay Dubey
2954ed2ab1
Add Juggler Sequence (#2845)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-26 19:39:14 +02:00
Louve Le bronec
e488b7b5bb
Add Happy Numbers (#2839)
Co-authored-by: Louve Le Bronec <loane.le.bronec@eisti.fr>
Co-authored-by: Yang Libin <contact@yanglibin.info>
Co-authored-by: Yang Libin <szuyanglb@outlook.com>
2021-11-26 19:35:35 +02:00
R_juzi
fb3cec06a1
Fix a bug in A_Star.Graph in jdk17 (#2842)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-24 10:29:38 +02:00
FyZhu97
6c00beec90
Fix NoClassDefFoundError exception (#2838)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-23 08:55:24 +02:00
Akshay Dubey
1869eab042
Add binomial coefficients (#2835) 2021-11-22 15:22:15 +02:00
Sachwin Kohli
fe7e5d842c
Add author (#2831)
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
2021-11-20 11:46:15 +02:00
Akshay Dubey
6be3c99399
Add Boundary Fill Algorithm (#2822)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-15 07:39:42 +02:00
Aitor Fidalgo Sánchez
dee4fc747c
Change Java version to 17 (#2819)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-15 07:38:34 +02:00
Akshay Dubey
1f17076571
Add Flood Fill Algorithm Implementation (#2821)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-14 10:03:17 +02:00
Aitor Fidalgo Sánchez
4fb7470f9a
Update DIRECTORY.md (#2818) 2021-11-13 13:10:08 +02:00
Aitor Fidalgo Sánchez
9fb3364ccc
Change project structure to a Maven Java project + Refactor (#2816) 2021-11-12 08:59:36 +02:00
Artem Boiarshinov
8e533d2617
Add Damm algorithm (Fixes: #2814) (#2815)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-10 18:33:52 +02:00
Ian Cowan
e240c1e33c
Add Dequeue (#2809)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-09 09:49:35 +02:00
Sachwin Kohli
9b0543d281
Add Gaussian Elimination (#2810)
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-09 09:45:41 +02:00
caos321
ba6a3d6856
Add Breadth First Search (#2801)
Co-authored-by: xzero <andrejmezler@yahoo.de>
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-08 20:25:18 +02:00
Aitor Fidalgo Sánchez
7f3eb1b6dc
Add generic Node classes (#2782)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-08 20:03:06 +02:00
Ian Cowan
78f770683a
Improve documentation for MatrixGraphs (#2808) 2021-11-08 20:59:14 +08:00
Ian Cowan
5f424ce931
Add BFS/DFS ordering to matrix graphs (#2807) 2021-11-04 12:35:52 +02:00
Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ
bc6510e03d
Add volume formulas (#2805)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
2021-11-03 20:49:35 +02:00
Du Yuanchao
b0ccec9d61
Update bubble sort (#2806) 2021-11-03 09:07:59 +08:00
Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ
9567a78521
Fix typo (#2802) 2021-11-03 08:52:05 +08:00
Ian Cowan
55c114df2e
Add doubly linked list print reverse (#2797) 2021-11-02 21:28:00 +02:00
caos321
b05b4d0b2c
Add DepthFirstSearch with Java Streams (#2800)
Co-authored-by: xzero <andrejmezler@yahoo.de>
2021-11-02 08:11:13 +02:00
Amritesh Anand
27c5237b06
Add Banker's Algorithm (#2799) 2021-11-02 08:08:57 +02:00
caos321
7abd239842
Add MatrixUtil for matrix operations (#2798)
Co-authored-by: xzero <andrejmezler@yahoo.de>
2021-11-02 08:06:25 +02:00
Ian Cowan
5b261e9808
Add algorithm to reverse doubly linked list (#2796) 2021-11-01 20:57:31 +02:00
Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ
9e368100fe
Add surface area of Cone and Hemisphere (#2791) 2021-10-31 13:42:49 +02:00
Ian Cowan
664bcf494f
Check if Binary Tree is Balanced Closes #2719 (#2732) 2021-10-31 07:56:52 +02:00
JadenLeake333
f9e42010a2
Update directory (fixes #2785) (#2786) 2021-10-31 07:31:21 +02:00
Shardul Negi
6aabc0297b
Add Duplicate Brackets (#2766) 2021-10-30 11:55:19 +03:00
JadenLeake333
0607bf9b47
Add Odd-Even Sort (#2765) 2021-10-30 11:39:37 +03:00
Aitor Fidalgo Sánchez
bc6c8544b1
Add reverse number (#2759) 2021-10-30 08:25:54 +03:00
Aitor Fidalgo Sánchez
5834a949a6
Add Palindrome Linked List (Fixes #2360) (#2746) 2021-10-30 08:21:08 +03:00
ayush26sharma
332f63b942
Add some useful functions for singly linked list (#2757) 2021-10-30 08:19:48 +03:00
Artem Boiarshinov
bfa30ca3a4
Add Verhoeff Algorithm (Fixes: #2754) (#2755) 2021-10-30 08:15:43 +03:00
Yang Libin
794719c773
Fix formatting in Ciphers package (#2756) 2021-10-29 08:19:42 +03:00
Shikhar Chandra
0503c46680
Add Huffman Compression (#2753) 2021-10-29 08:16:26 +03:00
Shraddha
4db7a0c77e
Adde Dutch National Flag Algorithm (#2728) 2021-10-29 07:54:11 +03:00
1268 changed files with 66696 additions and 27654 deletions

136
.clang-format Normal file
View File

@ -0,0 +1,136 @@
---
Language: Java
AccessModifierOffset: -4
AlignAfterOpenBracket: DontAlign
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: false
AlignTrailingComments: false
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeComma
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 300
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
- Regex: '.*'
Priority: 1
SortPriority: 0
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertNewlineAtEOF: true
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard: Latest
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseCRLF: false
UseTab: Never
...

25
.devcontainer/Dockerfile Normal file
View File

@ -0,0 +1,25 @@
# See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/java/.devcontainer/base.Dockerfile
# [Choice] Java version (use -bullseye variants on local arm64/Apple Silicon): 11, 17, 11-bullseye, 17-bullseye, 11-buster, 17-buster
ARG VARIANT="21-bullseye"
FROM mcr.microsoft.com/vscode/devcontainers/java:1.1.0-${VARIANT}
# [Option] Install Maven
ARG INSTALL_MAVEN="false"
ARG MAVEN_VERSION=""
# [Option] Install Gradle
ARG INSTALL_GRADLE="false"
ARG GRADLE_VERSION=""
RUN if [ "${INSTALL_MAVEN}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install maven \"${MAVEN_VERSION}\""; fi \
&& if [ "${INSTALL_GRADLE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install gradle \"${GRADLE_VERSION}\""; fi
# [Choice] Node.js version: none, lts/*, 16, 14, 12, 10
ARG NODE_VERSION="none"
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
# [Optional] Uncomment this section to install additional OS packages.
# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
# && apt-get -y install --no-install-recommends <your-package-list-here>
# [Optional] Uncomment this line to install global node packages.
# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g <your-package-here>" 2>&1

View File

@ -0,0 +1,47 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/java
{
"name": "Java",
"build": {
"dockerfile": "Dockerfile",
"args": {
// Update the VARIANT arg to pick a Java version: 11, 17
// Append -bullseye or -buster to pin to an OS version.
// Use the -bullseye variants on local arm64/Apple Silicon.
"VARIANT": "21-bullseye",
// Options
"INSTALL_MAVEN": "true",
"INSTALL_GRADLE": "true",
"NODE_VERSION": "lts/*"
}
},
// Configure tool-specific properties.
"customizations": {
// Configure properties specific to VS Code.
"vscode": {
// Set *default* container specific settings.json values on container create.
"settings": {
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"vscjava.vscode-java-pack",
"GitHub.copilot",
]
}
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
"postCreateCommand": "java -version",
// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode",
"features": {
"git": "os-provided",
"github-cli": "latest"
}
}

2
.github/CODEOWNERS vendored
View File

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

View File

@ -1,29 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ""
labels: ""
assignees: ""
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Device Specification**
**Additional context**
Add any other context about the problem here.

45
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,45 @@
name: "Bug report"
description: "Create a report to help us improve"
title: "[BUG] <title>"
labels: ["bug"]
body:
- type: textarea
id: description
attributes:
label: "Description"
description: "A clear and concise description of what the bug is."
validations:
required: true
- type: textarea
id: steps
attributes:
label: "Steps to reproduce"
description: "Steps to reproduce the behavior (if applicable)"
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: false
- type: textarea
id: exceptedbhv
attributes:
label: "Excepted behavior"
description: "A clear and concise description of what you expected to happen."
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: "Screenshots"
description: "If applicable, add screenshots to help explain your problem."
validations:
required: false
- type: textarea
id: context
attributes:
label: "Additional context"
description: "Is there anything else we should know about this bug report?"
validations:
required: false

5
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Discord community
url: https://the-algorithms.com/discord/
about: Have any questions or found any bugs? Please contact us via Discord

View File

@ -1,19 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ""
labels: ""
assignees: ""
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -0,0 +1,34 @@
name: "Feature Request"
description: "Suggest an idea for this project"
title: "[FEATURE REQUEST] <title>"
labels: ["enhancement"]
body:
- type: textarea
id: description
attributes:
label: What would you like to Propose?
description: Provide a clear and concise explanation of your Proposal.
validations:
required: true
- type: markdown
attributes:
value: |
For new implementations, please specify the name and problem statement for the algorithm.
For algorithm enhancements, specify what needs to be changed and why. For example:
- Adding tests.
- Optimizing logic.
- Refactoring the file and folders for better structure.
- type: textarea
id: needdetails
attributes:
label: "Issue details"
description: "Write down all the issue/algorithm details description mentioned above."
validations:
required: true
- type: textarea
id: extrainfo
attributes:
label: "Additional Information"
description: "Add any other information or screenshots about the request here."
validations:
required: false

19
.github/ISSUE_TEMPLATE/other.yml vendored Normal file
View File

@ -0,0 +1,19 @@
name: Other
description: Use this for any other issues. Do NOT create blank issues
title: "[OTHER]"
labels: ["awaiting triage"]
body:
- type: textarea
id: issuedescription
attributes:
label: What would you like to share?
description: Provide a clear and concise explanation of your issue.
validations:
required: true
- type: textarea
id: extrainfo
attributes:
label: Additional information
description: Is there anything else we should know about this issue?
validations:
required: false

18
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,18 @@
---
version: 2
updates:
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/.github/workflows/"
schedule:
interval: "daily"
- package-ecosystem: "maven"
directory: "/"
schedule:
interval: "daily"
...

View File

@ -1,23 +1,16 @@
### **Describe your change:** <!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->
- [ ] Add an algorithm? <!-- For completed items, change [ ] to [x] -->
- [ ] Fix a bug or typo in an existing algorithm?
- [ ] Documentation change?
#### References
<!-- Add any reference to previous pull-request or issue -->
### **Checklist:**
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
- [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md). - [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [ ] This pull request is all my own work -- I have not plagiarized. - [ ] This pull request is all my own work -- I have not plagiarized it.
- [ ] I know that pull requests will not be merged if they fail the automated tests. - [ ] All filenames are in PascalCase.
- [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
- [ ] All new Java files are placed inside an existing directory.
- [ ] All filenames are in all uppercase characters with no spaces or dashes.
- [ ] All functions and variable names follow Java naming conventions. - [ ] All functions and variable names follow Java naming conventions.
- [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. - [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`. - [ ] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

View File

@ -1,14 +1,37 @@
name: Build name: Build
on: [push, pull_request] on: [push, pull_request]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- uses: actions/setup-python@v2 - name: Set up JDK
- name: Set up JDK 17 uses: actions/setup-java@v4
uses: actions/setup-java@v1
with: with:
java-version: 17 java-version: 21
- run: find . -type f -name "*.java" > sources.txt distribution: 'adopt'
- run: javac @sources.txt - name: Build with Maven
run: mvn --batch-mode --update-snapshots verify
- name: Upload coverage to codecov (tokenless)
if: >-
github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name != github.repository
uses: codecov/codecov-action@v4
with:
fail_ci_if_error: true
- name: Upload coverage to codecov (with token)
if: >
github.repository == 'TheAlgorithms/Java' &&
(github.event_name != 'pull_request' ||
github.event.pull_request.head.repo.full_name == github.repository)
uses: codecov/codecov-action@v4
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

16
.github/workflows/clang-format-lint.yml vendored Normal file
View File

@ -0,0 +1,16 @@
name: Clang format linter
on:
push: {}
pull_request: {}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: DoozyX/clang-format-lint-action@v0.18
with:
source: './src'
extensions: 'java'
clangFormatVersion: 16

47
.github/workflows/codeql.yml vendored Normal file
View File

@ -0,0 +1,47 @@
---
name: "CodeQL"
on:
workflow_dispatch:
push:
branches:
- master
pull_request:
schedule:
- cron: '53 3 * * 0'
env:
LANGUAGE: 'java-kotlin'
jobs:
analyze:
name: Analyze
runs-on: 'ubuntu-latest'
permissions:
actions: read
contents: read
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
java-version: 21
distribution: 'adopt'
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ env.LANGUAGE }}
- name: Build
run: mvn --batch-mode --update-snapshots verify
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{env.LANGUAGE}}"
...

View File

@ -1,18 +0,0 @@
name: Prettify
on: [push, pull_request]
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
ref: ${{ github.head_ref }}
- name: Prettify code
uses: creyD/prettier_action@v3.3
with:
prettier_options: --write **/*.java
commit_message: 'Prettify code'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -6,12 +6,12 @@ jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/stale@v4 - uses: actions/stale@v9
with: with:
stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution!'
close-issue-message: 'Please reopen this issue once you add more information and updates here. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' close-issue-message: 'Please reopen this issue once you have made the required changes. If you need help, feel free to ask in our [Discord](https://the-algorithms.com/discord) server or ping one of the maintainers here. Thank you for your contribution!'
stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.' stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contribution!'
close-pr-message: 'Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!' close-pr-message: 'Please reopen this pull request once you have made the required changes. If you need help, feel free to ask in our [Discord](https://the-algorithms.com/discord) server or ping one of the maintainers here. Thank you for your contribution!'
exempt-issue-labels: 'dont-close' exempt-issue-labels: 'dont-close'
exempt-pr-labels: 'dont-close' exempt-pr-labels: 'dont-close'
days-before-stale: 30 days-before-stale: 30

View File

@ -1,12 +1,33 @@
# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push # This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push or pull_request
name: Update Directory name: Update Directory
on: [push, pull_request] permissions:
contents: write
on:
push:
paths:
- 'src/**'
pull_request:
paths:
- 'src/**'
workflow_dispatch:
inputs:
logLevel:
description: 'Log level'
required: true
default: 'info'
type: choice
options:
- info
- warning
- debug
jobs: jobs:
update_directory_md: update_directory_md:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@master - uses: actions/checkout@master
- uses: actions/setup-python@master - uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Update Directory - name: Update Directory
shell: python shell: python
run: | run: |
@ -32,8 +53,12 @@ jobs:
def print_path(old_path: str, new_path: str) -> str: def print_path(old_path: str, new_path: str) -> str:
global g_output global g_output
old_parts = old_path.split(os.sep) old_parts = old_path.split(os.sep)
for i, new_part in enumerate(new_path.split(os.sep)): mid_diff = False
if i + 1 > len(old_parts) or old_parts[i] != new_part: new_parts = new_path.split(os.sep)
for i, new_part in enumerate(new_parts):
if i + 1 > len(old_parts) or old_parts[i] != new_part or mid_diff:
if i + 1 < len(new_parts):
mid_diff = True
if new_part: if new_part:
g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ')}") g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ')}")
return new_path return new_path
@ -42,7 +67,7 @@ jobs:
def build_directory_md(top_dir: str = ".") -> str: def build_directory_md(top_dir: str = ".") -> str:
global g_output global g_output
old_path = "" old_path = ""
for filepath in sorted(good_filepaths(), key=str.lower): for filepath in sorted(good_filepaths(top_dir), key=str.lower):
filepath, filename = os.path.split(filepath) filepath, filename = os.path.split(filepath)
if filepath != old_path: if filepath != old_path:
old_path = print_path(old_path, filepath) old_path = print_path(old_path, filepath)
@ -59,8 +84,8 @@ jobs:
- name: Update DIRECTORY.md - name: Update DIRECTORY.md
run: | run: |
cat DIRECTORY.md cat DIRECTORY.md
git config --global user.name github-actions git config --global user.name "$GITHUB_ACTOR"
git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com' git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com"
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
git add DIRECTORY.md git add DIRECTORY.md
git commit -am "Update directory" || true git commit -am "Update directory" || true

22
.gitignore vendored
View File

@ -1,6 +1,6 @@
/gradle/wrapper/gradle-wrapper.properties /gradle/wrapper/gradle-wrapper.properties
##----------Android---------- ##----------Android----------
# build
*.apk *.apk
*.ap_ *.ap_
*.dex *.dex
@ -10,29 +10,35 @@ gen/
build/ build/
out/ out/
# gradle # Ignoring Gradle build artifacts and project files
##----------Gradle----------
.gradle/ .gradle/
gradle-app.setting gradle-app.setting
!gradle-wrapper.jar !gradle-wrapper.jar
build/ build/
# Ignoring Maven build artifacts and project files
##----------Maven----------
*.classpath
*.project
*.settings
/target/
local.properties local.properties
##----------idea---------- # Ignoring IntelliJ IDEA project files and configurations
##----------IDEA----------
*.iml *.iml
.idea/ .idea/
*.ipr *.ipr
*.iws *.iws
# Android Studio Navigation editor temp files # Ignoring Android Studio Navigation editor temporary files
.navigation/ .navigation/
# Ignoring common system and editor-generated files
##----------Other---------- ##----------Other----------
# osx
*~ *~
.DS_Store .DS_Store
gradle.properties gradle.properties
.vscode .vscode
*.log
*.log

7
.gitpod.Dockerfile vendored
View File

@ -1,7 +0,0 @@
FROM gitpod/workspace-full
# Install custom tools, runtimes, etc.
# For example "bastet", a command-line tetris clone:
# RUN brew install bastet
#
# More information: https://www.gitpod.io/docs/config-docker/

22
.gitpod.dockerfile Normal file
View File

@ -0,0 +1,22 @@
FROM gitpod/workspace-java-21:2024-07-14-17-19-51
ENV LLVM_SCRIPT="tmp_llvm.sh"
RUN test ! -f "$LLVM_SCRIPT" \
&& wget https://apt.llvm.org/llvm.sh -O "$LLVM_SCRIPT" \
&& chmod +x "$LLVM_SCRIPT"
USER root
RUN ./"$LLVM_SCRIPT" 16 \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
clang-format-16=1:16.0.6~++20231112100510+7cbf1a259152-1~exp1~20231112100554.106 \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
RUN ln -s "$(command -v clang-format-16)" "/usr/bin/clang-format"
USER gitpod
RUN rm "$LLVM_SCRIPT"

View File

@ -1,6 +1,13 @@
---
image: image:
file: .gitpod.Dockerfile file: .gitpod.dockerfile
tasks: tasks:
- init: 'echo "TODO: Replace with init/build command"' - init: |
command: (e.g. 'npm start', 'yarn watch'...) mvn dependency:resolve
mvn compile
vscode:
extensions:
- xaver.clang-format

View File

@ -1,52 +0,0 @@
package Backtracking;
import java.util.Scanner;
/*
* Problem Statement :
* Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers.
* For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3.
* Therefore output will be 1.
*/
public class PowerSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number and the power");
int N = sc.nextInt();
int X = sc.nextInt();
PowerSum ps = new PowerSum();
int count = ps.powSum(N,X);
//printing the answer.
System.out.println("Number of combinations of different natural number's raised to "+X+" having sum "+N+" are : ");
System.out.println(count);
sc.close();
}
private int count = 0,sum=0;
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) {
//if sum is equal to N that is one of our answer and count is increased.
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);
//backtracking and removing the number added last since no possible combination is there with it.
sum-=power(i,X);
}
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);
}
}
//creating a separate power function so that it can be used again and again when required.
private int power(int a , int b ){
return (int)Math.pow(a,b);
}
}

View File

@ -1,27 +1,31 @@
## How to contribute? ## How to contribute?
#### **Did you find a bug?** NOTE: *We DO NOT add leetcode problems. They are just applications of basic principles that can be found in other algorithms included in the repository.*
- **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues). ### Did you find a bug?
- Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request and it will be evaluated by project maintainers. **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues).
- If it is mentioned in the issues and you want to fix it, [fork](https://github.com/TheAlgorithms/Java/fork) the repository and submit your implementation in a pull request. The project maintainers will evaluate it.
- If the bug is **NOT** mentioned in the issues, [open a new issue](https://github.com/TheAlgorithms/Java/issues/new). Be sure to include a **title**, a clear **description** and a **test case** demonstrating the expected behavior that is not occurring.
- If you are unable to find an open issue referring to the same problem, depending on the type of issue follow the appropriate steps: NOTE: *Please avoid opening issues asking to be "assigned" to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request and project maintainers will evaluate it.*
#### **Do you want to contribute to the documentation?**
- Please read the documentation here [Contributing to the Documentation](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md), [open a new issue](https://github.com/TheAlgorithms/Java/issues/new), make changes, and then create a pull request, it will be put under review and accepted if it is appropriate.
#### **Do you want to add a new feature?** ### Do you want to contribute to the documentation?
- [Fork](https://github.com/TheAlgorithms/Java/fork) the repository and make necessary changes.
- Create a pull request.
- It will be put under review for approval.
- If approved, the requested changes will be merged to the repository.
- [Open a new issue](https://github.com/TheAlgorithms/Java/issues/new). Be sure to include a **title and a clear description** and a **test case** demonstrating the new feature that you want to add to the project. ### Do you want to add a new feature?
#### **Do you want to fix a bug?** - [Open a new issue](https://github.com/TheAlgorithms/Java/issues/new).
- Be sure to include a **title**, a clear **description** and a **test case** demonstrating the new feature you want to add to the project.
- [Open a new issue](https://github.com/TheAlgorithms/Java/issues/new).Be sure to include a **title and a clear description** and a **test case** demonstrating the expected behavior that is not occurring.
#### **Do you have questions about the source code?** ### Do you have questions about the source code?
- Ask any question about how to use the repository in the [TheAlgorithms room in GITTER](https://gitter.im/TheAlgorithms/community?source=orgpage#) or [open a new issue](https://github.com/TheAlgorithms/Java/issues/new) - Ask any question about how to use the repository in the [TheAlgorithms room in GITTER](https://gitter.im/TheAlgorithms/community?source=orgpage#) or [open a new issue](https://github.com/TheAlgorithms/Java/issues/new)
:+1::tada: That's all you need to know about the process now it's your turn to help us improve the repository, thank you again! :+1::tada: :+1::tada: That's all you need to know about the process now it's your turn to help us improve the repository, thank you again! :+1::tada:

View File

@ -1,605 +0,0 @@
package Ciphers;
import java.math.BigInteger;
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 {
/**
* Precalculated values for x to the power of 2 in Rijndaels galois field. Used as 'RCON' during
* the key expansion.
*/
private static final int[] RCON = {
0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d
};
/**
* Rijndael S-box Substitution table used for encryption in the subBytes step, as well as the key
* expansion.
*/
private static final int[] SBOX = {
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
};
/** Inverse Rijndael S-box Substitution table used for decryption in the subBytesDec step. */
private static final int[] INVERSE_SBOX = {
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
};
/**
* Precalculated lookup table for galois field multiplication by 2 used in the MixColums step
* during encryption.
*/
private static final int[] MULT2 = {
0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e,
0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e,
0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, 0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e,
0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe,
0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde,
0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, 0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe,
0x1b, 0x19, 0x1f, 0x1d, 0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05,
0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d, 0x23, 0x21, 0x27, 0x25,
0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55, 0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45,
0x7b, 0x79, 0x7f, 0x7d, 0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65,
0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d, 0x83, 0x81, 0x87, 0x85,
0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5, 0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5,
0xdb, 0xd9, 0xdf, 0xdd, 0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5,
0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed, 0xe3, 0xe1, 0xe7, 0xe5
};
/**
* Precalculated lookup table for galois field multiplication by 3 used in the MixColums step
* during encryption.
*/
private static final int[] MULT3 = {
0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39, 0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21,
0x60, 0x63, 0x66, 0x65, 0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71,
0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d, 0x44, 0x47, 0x42, 0x41,
0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9, 0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1,
0xf0, 0xf3, 0xf6, 0xf5, 0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1,
0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd, 0xb4, 0xb7, 0xb2, 0xb1,
0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99, 0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81,
0x9b, 0x98, 0x9d, 0x9e, 0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a,
0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6, 0xbf, 0xbc, 0xb9, 0xba,
0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2, 0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea,
0xcb, 0xc8, 0xcd, 0xce, 0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda,
0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46, 0x4f, 0x4c, 0x49, 0x4a,
0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62, 0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a,
0x3b, 0x38, 0x3d, 0x3e, 0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a,
0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16, 0x1f, 0x1c, 0x19, 0x1a
};
/**
* Precalculated lookup table for galois field multiplication by 9 used in the MixColums step
* during decryption.
*/
private static final int[] MULT9 = {
0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77,
0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf, 0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7,
0x3b, 0x32, 0x29, 0x20, 0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c,
0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8, 0xc7, 0xce, 0xd5, 0xdc,
0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49, 0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01,
0xe6, 0xef, 0xf4, 0xfd, 0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91,
0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e, 0x21, 0x28, 0x33, 0x3a,
0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2, 0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa,
0xec, 0xe5, 0xfe, 0xf7, 0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b,
0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f, 0x10, 0x19, 0x02, 0x0b,
0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8, 0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0,
0x47, 0x4e, 0x55, 0x5c, 0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30,
0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9, 0xf6, 0xff, 0xe4, 0xed,
0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35, 0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d,
0xa1, 0xa8, 0xb3, 0xba, 0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6,
0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62, 0x5d, 0x54, 0x4f, 0x46
};
/**
* Precalculated lookup table for galois field multiplication by 11 used in the MixColums step
* during decryption.
*/
private static final int[] MULT11 = {
0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45, 0x74, 0x7f, 0x62, 0x69,
0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81, 0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9,
0x7b, 0x70, 0x6d, 0x66, 0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12,
0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e, 0xbf, 0xb4, 0xa9, 0xa2,
0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7, 0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f,
0x46, 0x4d, 0x50, 0x5b, 0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f,
0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8, 0xf9, 0xf2, 0xef, 0xe4,
0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c, 0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54,
0xf7, 0xfc, 0xe1, 0xea, 0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e,
0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02, 0x33, 0x38, 0x25, 0x2e,
0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd, 0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5,
0x3c, 0x37, 0x2a, 0x21, 0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55,
0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44, 0x75, 0x7e, 0x63, 0x68,
0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80, 0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8,
0x7a, 0x71, 0x6c, 0x67, 0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13,
0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f, 0xbe, 0xb5, 0xa8, 0xa3
};
/**
* Precalculated lookup table for galois field multiplication by 13 used in the MixColums step
* during decryption.
*/
private static final int[] MULT13 = {
0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f, 0x5c, 0x51, 0x46, 0x4b,
0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3, 0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b,
0xbb, 0xb6, 0xa1, 0xac, 0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0,
0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14, 0x37, 0x3a, 0x2d, 0x20,
0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e, 0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26,
0xbd, 0xb0, 0xa7, 0xaa, 0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6,
0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9, 0x8a, 0x87, 0x90, 0x9d,
0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25, 0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d,
0xda, 0xd7, 0xc0, 0xcd, 0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91,
0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75, 0x56, 0x5b, 0x4c, 0x41,
0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42, 0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a,
0xb1, 0xbc, 0xab, 0xa6, 0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa,
0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8, 0xeb, 0xe6, 0xf1, 0xfc,
0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44, 0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c,
0x0c, 0x01, 0x16, 0x1b, 0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47,
0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3, 0x80, 0x8d, 0x9a, 0x97
};
/**
* Precalculated lookup table for galois field multiplication by 14 used in the MixColums step
* during decryption.
*/
private static final int[] MULT14 = {
0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62, 0x48, 0x46, 0x54, 0x5a,
0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca, 0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba,
0xdb, 0xd5, 0xc7, 0xc9, 0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81,
0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59, 0x73, 0x7d, 0x6f, 0x61,
0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87, 0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7,
0x4d, 0x43, 0x51, 0x5f, 0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17,
0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14, 0x3e, 0x30, 0x22, 0x2c,
0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc, 0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc,
0x41, 0x4f, 0x5d, 0x53, 0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b,
0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3, 0xe9, 0xe7, 0xf5, 0xfb,
0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0, 0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0,
0x7a, 0x74, 0x66, 0x68, 0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20,
0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e, 0xa4, 0xaa, 0xb8, 0xb6,
0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26, 0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56,
0x37, 0x39, 0x2b, 0x25, 0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5, 0x9f, 0x91, 0x83, 0x8d
};
/**
* Subroutine of the Rijndael key expansion.
*/
public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
StringBuilder rBytes = new StringBuilder(t.toString(16));
// Add zero padding
while (rBytes.length() < 8) {
rBytes.insert(0, "0");
}
// rotate the first 16 bits to the back
String rotatingBytes = rBytes.substring(0, 2);
String fixedBytes = rBytes.substring(2);
rBytes = new StringBuilder(fixedBytes + rotatingBytes);
// apply S-Box to all 8-Bit Substrings
for (int i = 0; i < 4; i++) {
StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2));
int currentByte = Integer.parseInt(currentByteBits.toString(), 16);
currentByte = SBOX[currentByte];
// add the current RCON value to the first byte
if (i == 0) {
currentByte = currentByte ^ RCON[rconCounter];
}
currentByteBits = new StringBuilder(Integer.toHexString(currentByte));
// Add zero padding
while (currentByteBits.length() < 2) {
currentByteBits.insert(0, '0');
}
// replace bytes in original string
rBytes = new StringBuilder(rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
}
// t = new BigInteger(rBytes, 16);
// return t;
return new BigInteger(rBytes.toString(), 16);
}
/**
* Returns an array of 10 + 1 round keys that are calculated by using Rijndael key schedule
*
* @return array of 10 + 1 round keys
*/
public static BigInteger[] keyExpansion(BigInteger initialKey) {
BigInteger[] roundKeys = {
initialKey,
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
new BigInteger("0"),
};
// initialize rcon iteration
int rconCounter = 1;
for (int i = 1; i < 11; i++) {
// get the previous 32 bits the key
BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
// split previous key into 8-bit segments
BigInteger[] prevKey = {
roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
roundKeys[i - 1]
.remainder(new BigInteger("10000000000000000", 16))
.divide(new BigInteger("100000000", 16)),
roundKeys[i - 1]
.remainder(new BigInteger("1000000000000000000000000", 16))
.divide(new BigInteger("10000000000000000", 16)),
roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
};
// run schedule core
t = scheduleCore(t, rconCounter);
rconCounter += 1;
// Calculate partial round key
BigInteger t0 = t.xor(prevKey[3]);
BigInteger t1 = t0.xor(prevKey[2]);
BigInteger t2 = t1.xor(prevKey[1]);
BigInteger t3 = t2.xor(prevKey[0]);
// Join round key segments
t2 = t2.multiply(new BigInteger("100000000", 16));
t1 = t1.multiply(new BigInteger("10000000000000000", 16));
t0 = t0.multiply(new BigInteger("1000000000000000000000000", 16));
roundKeys[i] = t0.add(t1).add(t2).add(t3);
}
return roundKeys;
}
/**
* representation of the input 128-bit block as an array of 8-bit integers.
*
* @param block of 128-bit integers
* @return array of 8-bit integers
*/
public static int[] splitBlockIntoCells(BigInteger block) {
int[] cells = new int[16];
StringBuilder blockBits = new StringBuilder(block.toString(2));
// Append leading 0 for full "128-bit" string
while (blockBits.length() < 128) {
blockBits.insert(0, '0');
}
// split 128 to 8 bit cells
for (int i = 0; i < cells.length; i++) {
String cellBits = blockBits.substring(8 * i, 8 * (i + 1));
cells[i] = Integer.parseInt(cellBits, 2);
}
return cells;
}
/**
* Returns the 128-bit BigInteger representation of the input of an array of 8-bit integers.
*
* @param cells that we need to merge
* @return block of merged cells
*/
public static BigInteger mergeCellsIntoBlock(int[] cells) {
StringBuilder blockBits = new StringBuilder();
for (int i = 0; i < 16; i++) {
StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i]));
// Append leading 0 for full "8-bit" strings
while (cellBits.length() < 8) {
cellBits.insert(0, '0');
}
blockBits.append(cellBits);
}
return new BigInteger(blockBits.toString(), 2);
}
/**
* @return ciphertext XOR key
*/
public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) {
return ciphertext.xor(key);
}
/**
* substitutes 8-Bit long substrings of the input using the S-Box and returns the result.
*
* @return subtraction Output
*/
public static BigInteger subBytes(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
for (int i = 0; i < 16; i++) {
cells[i] = SBOX[cells[i]];
}
return mergeCellsIntoBlock(cells);
}
/**
* substitutes 8-Bit long substrings of the input using the inverse S-Box for decryption and
* returns the result.
*
* @return subtraction Output
*/
public static BigInteger subBytesDec(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
for (int i = 0; i < 16; i++) {
cells[i] = INVERSE_SBOX[cells[i]];
}
return mergeCellsIntoBlock(cells);
}
/**
* Cell permutation step. Shifts cells within the rows of the input and returns the result.
*/
public static BigInteger shiftRows(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
int[] output = new int[16];
// do nothing in the first row
output[0] = cells[0];
output[4] = cells[4];
output[8] = cells[8];
output[12] = cells[12];
// shift the second row backwards by one cell
output[1] = cells[5];
output[5] = cells[9];
output[9] = cells[13];
output[13] = cells[1];
// shift the third row backwards by two cell
output[2] = cells[10];
output[6] = cells[14];
output[10] = cells[2];
output[14] = cells[6];
// shift the forth row backwards by tree cell
output[3] = cells[15];
output[7] = cells[3];
output[11] = cells[7];
output[15] = cells[11];
return mergeCellsIntoBlock(output);
}
/**
* Cell permutation step for decryption . Shifts cells within the rows of the input and returns
* the result.
*/
public static BigInteger shiftRowsDec(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
int[] output = new int[16];
// do nothing in the first row
output[0] = cells[0];
output[4] = cells[4];
output[8] = cells[8];
output[12] = cells[12];
// shift the second row forwards by one cell
output[1] = cells[13];
output[5] = cells[1];
output[9] = cells[5];
output[13] = cells[9];
// shift the third row forwards by two cell
output[2] = cells[10];
output[6] = cells[14];
output[10] = cells[2];
output[14] = cells[6];
// shift the forth row forwards by tree cell
output[3] = cells[7];
output[7] = cells[11];
output[11] = cells[15];
output[15] = cells[3];
return mergeCellsIntoBlock(output);
}
/**
* Applies the Rijndael MixColumns to the input and returns the result.
*/
public static BigInteger mixColumns(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
int[] outputCells = new int[16];
for (int i = 0; i < 4; i++) {
int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]};
outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3];
outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3];
outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]];
outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
/**
* Applies the inverse Rijndael MixColumns for decryption to the input and returns the result.
*/
public static BigInteger mixColumnsDec(BigInteger ciphertext) {
int[] cells = splitBlockIntoCells(ciphertext);
int[] outputCells = new int[16];
for (int i = 0; i < 4; i++) {
int[] row = {cells[i * 4], cells[i * 4 + 1], cells[i * 4 + 2], cells[i * 4 + 3]};
outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]];
outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
outputCells[i * 4 + 2] = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]];
outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
/**
* Encrypts the plaintext with the key and returns the result
*
* @param plainText which we want to encrypt
* @param key the key for encrypt
* @return EncryptedText
*/
public static BigInteger encrypt(BigInteger plainText, BigInteger key) {
BigInteger[] roundKeys = keyExpansion(key);
// Initial round
plainText = addRoundKey(plainText, roundKeys[0]);
// Main rounds
for (int i = 1; i < 10; i++) {
plainText = subBytes(plainText);
plainText = shiftRows(plainText);
plainText = mixColumns(plainText);
plainText = addRoundKey(plainText, roundKeys[i]);
}
// Final round
plainText = subBytes(plainText);
plainText = shiftRows(plainText);
plainText = addRoundKey(plainText, roundKeys[10]);
return plainText;
}
/**
* Decrypts the ciphertext with the key and returns the result
*
* @param cipherText The Encrypted text which we want to decrypt
* @return decryptedText
*/
public static BigInteger decrypt(BigInteger cipherText, BigInteger key) {
BigInteger[] roundKeys = keyExpansion(key);
// Invert final round
cipherText = addRoundKey(cipherText, roundKeys[10]);
cipherText = shiftRowsDec(cipherText);
cipherText = subBytesDec(cipherText);
// Invert main rounds
for (int i = 9; i > 0; i--) {
cipherText = addRoundKey(cipherText, roundKeys[i]);
cipherText = mixColumnsDec(cipherText);
cipherText = shiftRowsDec(cipherText);
cipherText = subBytesDec(cipherText);
}
// Invert initial round
cipherText = addRoundKey(cipherText, roundKeys[0]);
return cipherText;
}
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :");
char choice = input.nextLine().charAt(0);
String in;
switch (choice) {
case 'E', 'e' -> {
System.out.println("Choose a plaintext block (128-Bit Integer in base 16):");
in = input.nextLine();
BigInteger plaintext = new BigInteger(in, 16);
System.out.println("Choose a Key (128-Bit Integer in base 16):");
in = input.nextLine();
BigInteger encryptionKey = new BigInteger(in, 16);
System.out.println(
"The encrypted message is: \n" + encrypt(plaintext, encryptionKey).toString(16));
}
case 'D', 'd' -> {
System.out.println("Enter your ciphertext block (128-Bit Integer in base 16):");
in = input.nextLine();
BigInteger ciphertext = new BigInteger(in, 16);
System.out.println("Choose a Key (128-Bit Integer in base 16):");
in = input.nextLine();
BigInteger decryptionKey = new BigInteger(in, 16);
System.out.println(
"The deciphered message is:\n" + decrypt(ciphertext, decryptionKey).toString(16));
}
default -> System.out.println("** End **");
}
}
}
}

View File

@ -1,97 +0,0 @@
package Ciphers;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
* This example program shows how AES encryption and decryption can be done in Java. Please note
* that secret key and encrypted text is unreadable binary and hence in the following program we
* display it in hexadecimal format of the underlying bytes.
*/
public class AESEncryption {
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
/**
* 1. Generate a plain text for encryption 2. Get a secret key (printed in hexadecimal form). In
* actual use this must by encrypted and kept safe. The same key is required for decryption.
*/
public static void main(String[] args) throws Exception {
String plainText = "Hello World";
SecretKey secKey = getSecretEncryptionKey();
byte[] cipherText = encryptText(plainText, secKey);
String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText);
System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()));
System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText));
System.out.println("Descrypted Text:" + decryptedText);
}
/**
* gets the AES encryption key. In your actual programs, this should be safely stored.
*
* @return secKey (Secret key that we encrypt using it)
* @throws NoSuchAlgorithmException (from KeyGenrator)
*/
public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(128); // The AES key size in number of bits
return aesKeyGenerator.generateKey();
}
/**
* Encrypts plainText in AES using the secret key
*
* @return byteCipherText (The encrypted text)
* @throws NoSuchPaddingException (from Cipher)
* @throws NoSuchAlgorithmException (from Cipher)
* @throws InvalidKeyException (from Cipher)
* @throws BadPaddingException (from Cipher)
* @throws IllegalBlockSizeException (from Cipher)
*/
public static byte[] encryptText(String plainText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
return aesCipher.doFinal(plainText.getBytes());
}
/**
* Decrypts encrypted byte array using the key used for encryption.
*
* @return plainText
*/
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, secKey);
byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
return new String(bytePlainText);
}
/**
* Convert a binary byte array into readable hex form Old library is deprecated on OpenJdk 11 and
* this is faster regarding other solution is using StringBuilder
*
* @return hexHash
*/
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
}

View File

@ -1,98 +0,0 @@
//The key for the Affine cipher consists of 2 numbers, well call them a and b.
// The following discussion assumes the use of a 26 character alphabet (m = 26).
// a should be chosen to be relatively prime to m (i.e. a should have no factors in common with m).
package Ciphers;
import java.util.Scanner;
class AffineCipher
{
static Scanner in = new Scanner(System.in);
static String encryptMessage(char[] msg)
{
System.out.println("Enter key value a for encryption : ");
int a = in.nextInt();
System.out.println("Enter key value b for encryption : ");
int b = in.nextInt();
/// Initially empty cipher String
String cipher = "";
for (int i = 0; i < msg.length; i++)
{
// Avoid space to be encrypted
/* applying encryption formula ( a x + b ) mod m
{here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ')
{
cipher = cipher
+ (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else // append space character
{
cipher += msg[i];
}
}
return cipher;
}
static String decryptCipher(String cipher)
{
System.out.println("Enter key value a for decryption : ");
int a = in.nextInt();
System.out.println("Enter key value b for decryption : ");
int b = in.nextInt();
String msg = "";
int a_inv = 0;
int flag = 0;
//Find a^-1 (the multiplicative inverse of a
//in the group of integers modulo m.)
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
// Check if (a*i)%26 == 1,
// if so, then i will be the multiplicative inverse of a
if (flag == 1)
{
a_inv = i;
}
}
for (int i = 0; i < cipher.length(); i++)
{
/*Applying decryption formula a^-1 ( x - b ) mod m
{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');
}
else // append space character
{
msg += cipher.charAt(i);
}
}
return msg;
}
// Main method
public static void main(String[] args)
{
String msg = "AFFINE CIPHER";
// Encrypting message
String cipherText = encryptMessage(msg.toCharArray());
System.out.println("Encrypted Message is : " + cipherText);
// Decrypting message
System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
}
}

View File

@ -1,115 +0,0 @@
package Ciphers;
import java.util.Scanner;
/**
* A Java implementation of Caesar Cipher. /It is a type of substitution cipher in which each letter
* in the plaintext is replaced by a letter some fixed number of positions down the alphabet. /
*
* @author FAHRI YARDIMCI
* @author khalil2535
*/
public class Caesar {
/**
* Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B
*
* @return Encrypted message
*/
public static String encode(String message, int shift) {
StringBuilder encoded = new StringBuilder();
shift %= 26;
final int length = message.length();
for (int i = 0; i < length; i++) {
// int current = message.charAt(i); //using char to shift characters because ascii
// is in-order latin alphabet
char current = message.charAt(i); // Java law : char + int = char
if (IsCapitalLatinLetter(current)) {
current += shift;
encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) {
current += shift;
encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else {
encoded.append(current);
}
}
return encoded.toString();
}
/**
* Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A
*
* @return message
*/
public static String decode(String encryptedMessage, int shift) {
StringBuilder decoded = new StringBuilder();
shift %= 26;
final int length = encryptedMessage.length();
for (int i = 0; i < length; i++) {
char current = encryptedMessage.charAt(i);
if (IsCapitalLatinLetter(current)) {
current -= shift;
decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) {
current -= shift;
decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else {
decoded.append(current);
}
}
return decoded.toString();
}
/**
* @return true if character is capital Latin letter or false for others
*/
private static boolean IsCapitalLatinLetter(char c) {
return c >= 'A' && c <= 'Z';
}
/**
* @return true if character is small Latin letter or false for others
*/
private static boolean IsSmallLatinLetter(char c) {
return c >= 'a' && c <= 'z';
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the message (Latin Alphabet)");
String message = input.nextLine();
System.out.println(message);
System.out.println("Please enter the shift number");
int shift = input.nextInt() % 26;
System.out.println("(E)ncode or (D)ecode ?");
char choice = input.next().charAt(0);
switch (choice) {
case 'E':
case 'e':
System.out.println(
"ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle
break;
case 'D':
case 'd':
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift));
default:
System.out.println("default case");
}
input.close();
}
}

View File

@ -1,199 +0,0 @@
package Ciphers;
import java.util.Objects;
/**
* Columnar Transposition Cipher Encryption and Decryption.
*
* @author <a href="https://github.com/freitzzz">freitzzz</a>
*/
public class ColumnarTranspositionCipher {
private static String keyword;
private static Object[][] table;
private static String abecedarium;
public static final String ABECEDARIUM =
"abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
private static final String ENCRYPTION_FIELD = "";
private static final char ENCRYPTION_FIELD_CHAR = '≈';
/**
* Encrypts a certain String with the Columnar Transposition Cipher Rule
*
* @param word Word being encrypted
* @param keyword String with keyword being used
* @return a String with the word encrypted by the Columnar Transposition Cipher Rule
*/
public static String encrpyter(String word, String keyword) {
ColumnarTranspositionCipher.keyword = keyword;
abecedariumBuilder(500);
table = tableBuilder(word);
Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[i].length; i++) {
for (int j = 1; j < sortedTable.length; j++) {
wordEncrypted.append(sortedTable[j][i]);
}
}
return wordEncrypted.toString();
}
/**
* Encrypts a certain String with the Columnar Transposition Cipher Rule
*
* @param word Word being encrypted
* @param keyword String with keyword being used
* @param abecedarium String with the abecedarium being used. null for default one
* @return a String with the word encrypted by the Columnar Transposition Cipher Rule
*/
public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword;
ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word);
Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[0].length; i++) {
for (int j = 1; j < sortedTable.length; j++) {
wordEncrypted.append(sortedTable[j][i]);
}
}
return wordEncrypted.toString();
}
/**
* Decrypts a certain encrypted String with the Columnar Transposition Cipher Rule
*
* @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule
*/
public static String decrypter() {
StringBuilder wordDecrypted = new StringBuilder();
for (int i = 1; i < table.length; i++) {
for (Object item : table[i]) {
wordDecrypted.append(item);
}
}
return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, "");
}
/**
* Builds a table with the word to be encrypted in rows by the Columnar Transposition Cipher Rule
*
* @return An Object[][] with the word to be encrypted filled in rows and columns
*/
private static Object[][] tableBuilder(String word) {
Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()];
char[] wordInChards = word.toCharArray();
// Fils in the respective numbers
table[0] = findElements();
int charElement = 0;
for (int i = 1; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
if (charElement < wordInChards.length) {
table[i][j] = wordInChards[charElement];
charElement++;
} else {
table[i][j] = ENCRYPTION_FIELD_CHAR;
}
}
}
return table;
}
/**
* Determines the number of rows the table should have regarding the Columnar Transposition Cipher
* Rule
*
* @return an int with the number of rows that the table should have in order to respect the
* Columnar Transposition Cipher Rule.
*/
private static int numberOfRows(String word) {
if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else {
return word.length() / keyword.length();
}
}
/** @return charValues */
private static Object[] findElements() {
Object[] charValues = new Object[keyword.length()];
for (int i = 0; i < charValues.length; i++) {
int charValueIndex = abecedarium.indexOf(keyword.charAt(i));
charValues[i] = charValueIndex > -1 ? charValueIndex : null;
}
return charValues;
}
/**
* @return tableSorted
*/
private static Object[][] sortTable(Object[][] table) {
Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < tableSorted.length; i++) {
System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
}
for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) {
Object[] column = getColumn(tableSorted, tableSorted.length, i);
switchColumns(tableSorted, j, i, column);
}
}
}
return tableSorted;
}
/**
* @return columnArray
*/
private static Object[] getColumn(Object[][] table, int rows, int column) {
Object[] columnArray = new Object[rows];
for (int i = 0; i < rows; i++) {
columnArray[i] = table[i][column];
}
return columnArray;
}
private static void switchColumns(
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
for (int i = 0; i < table.length; i++) {
table[i][secondColumnIndex] = table[i][firstColumnIndex];
table[i][firstColumnIndex] = columnToSwitch[i];
}
}
/**
* Creates an abecedarium with a specified ascii inded
*
* @param value Number of characters being used based on the ASCII Table
*/
private static void abecedariumBuilder(int value) {
StringBuilder t = new StringBuilder();
for (int i = 0; i < value; i++) {
t.append((char) i);
}
abecedarium = t.toString();
}
private static void showTable() {
for (Object[] table1 : table) {
for (Object item : table1) {
System.out.print(item + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
String keywordForExample = "asd215";
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
System.out.println("### Example of Columnar Transposition Cipher ###\n");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
System.out.println(
"Word encrypted ->>> "
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###");
showTable();
}
}

View File

@ -1,172 +0,0 @@
package Ciphers;
import java.util.*;
/*
* Java Implementation of Hill Cipher
* Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25.
* To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26.
* To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
* The cipher key and plaintext/ciphertext are user inputs.
* @author Ojasva Jain
*/
public class HillCipher{
static Scanner in = new Scanner (System.in);
/* Following function encrypts the message
*/
static void encrypt(String message)
{
message = message.toUpperCase();
// Get key matrix
System.out.println("Enter key matrix size");
int n = in.nextInt();
System.out.println("Enter Key/encryptionKey matrix ");
int keyMatrix[][] = new int [n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
keyMatrix[i][j] = in.nextInt();
}
}
//check if det = 0
if(determinant(keyMatrix,n)%26 == 0)
{
System.out.println("Invalid key, as determinant = 0. Program Terminated");
return;
}
int [][]messageVector = new int[n][1];
String CipherText="";
int cipherMatrix [][] = new int [n][1];
int j = 0;
while(j<message.length()){
for (int i = 0; i < n; i++){
if(j>=message.length()){ messageVector[i][0] = 23;}
else
messageVector[i][0] = (message.charAt(j))%65;
System.out.println(messageVector[i][0]);
j++;
}
int x, i;
for (i = 0; i < n; i++)
{
cipherMatrix[i][0] = 0;
for (x = 0; x < n; x++)
{
cipherMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0];
}
System.out.println(cipherMatrix[i][0]);
cipherMatrix[i][0] = cipherMatrix[i][0] % 26;
}
for (i = 0; i < n; i++)
CipherText += (char)(cipherMatrix[i][0] + 65);
}
System.out.println("Ciphertext: "+ CipherText);
}
//Following function decrypts a message
static void decrypt(String message)
{
message = message.toUpperCase();
// Get key matrix
System.out.println("Enter key matrix size");
int n = in.nextInt();
System.out.println("Enter inverseKey/decryptionKey matrix ");
int keyMatrix[][] = new int [n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
keyMatrix[i][j] = in.nextInt();
}
}
//check if det = 0
if(determinant(keyMatrix,n)%26 == 0)
{
System.out.println("Invalid key, as determinant = 0. Program Terminated");
return;
}
//solving for the required plaintext message
int [][]messageVector = new int[n][1];
String PlainText="";
int plainMatrix [][] = new int [n][1];
int j = 0;
while(j<message.length()){
for (int i = 0; i < n; i++){
if(j>=message.length()){ messageVector[i][0] = 23;}
else
messageVector[i][0] = (message.charAt(j))%65;
System.out.println(messageVector[i][0]);
j++;
}
int x, i;
for (i = 0; i < n; i++)
{
plainMatrix[i][0] = 0;
for (x = 0; x < n; x++)
{
plainMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0];
}
plainMatrix[i][0] = plainMatrix[i][0] % 26;
}
for (i = 0; i < n; i++)
PlainText += (char)(plainMatrix[i][0] + 65);
}
System.out.println("Plaintext: "+PlainText);
}
// Determinant calculator
public static int determinant(int a[][], int n){
int det = 0, sign = 1, p = 0, q = 0;
if(n==1){
det = a[0][0];
}
else{
int b[][] = new int[n-1][n-1];
for(int x = 0 ; x < n ; x++){
p=0;q=0;
for(int i = 1;i < n; i++){
for(int j = 0; j < n;j++){
if(j != x){
b[p][q++] = a[i][j];
if(q % (n-1) == 0){
p++;
q=0;
}
}
}
}
det = det + a[0][x] *determinant(b, n-1) * sign;
sign = -sign;
}
}
return det;
}
// 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");
short sc = in.nextShort();
if(sc == 1)
encrypt(message);
else if(sc == 2)
decrypt(message);
else
System.out.println("Invalid input, program terminated.");
}
// Driver code
public static void main(String[] args)
{
// Get the message to be encrypted
System.out.println("Enter message");
String message = in.nextLine();
hillcipher(message);
}
}

View File

@ -1,72 +0,0 @@
package Ciphers;
import java.util.Scanner;
class ProductCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input to be encrypted: ");
String substitutionInput = sc.nextLine();
System.out.println(" ");
System.out.println("Enter a number: ");
int n = sc.nextInt();
// Substitution encryption
StringBuffer substitutionOutput = new StringBuffer();
for (int i = 0; i < substitutionInput.length(); i++) {
char c = substitutionInput.charAt(i);
substitutionOutput.append((char) (c + 5));
}
System.out.println(" ");
System.out.println("Substituted text: ");
System.out.println(substitutionOutput);
// Transposition encryption
String transpositionInput = substitutionOutput.toString();
int modulus;
if ((modulus = transpositionInput.length() % n) != 0) {
modulus = n - modulus;
for (; modulus != 0; modulus--) {
transpositionInput += "/";
}
}
StringBuffer transpositionOutput = new StringBuffer();
System.out.println(" ");
System.out.println("Transposition Matrix: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < transpositionInput.length() / n; j++) {
char c = transpositionInput.charAt(i + (j * n));
System.out.print(c);
transpositionOutput.append(c);
}
System.out.println();
}
System.out.println(" ");
System.out.println("Final encrypted text: ");
System.out.println(transpositionOutput);
// Transposition decryption
n = transpositionOutput.length() / n;
StringBuffer transpositionPlaintext = new StringBuffer();
for (int i = 0; i < n; i++) {
for (int j = 0; j < transpositionOutput.length() / n; j++) {
char c = transpositionOutput.charAt(i + (j * n));
transpositionPlaintext.append(c);
}
}
// Substitution decryption
StringBuffer plaintext = new StringBuffer();
for (int i = 0; i < transpositionPlaintext.length(); i++) {
char c = transpositionPlaintext.charAt(i);
plaintext.append((char) (c - 5));
}
System.out.println("Plaintext: ");
System.out.println(plaintext);
sc.close();
}
}

View File

@ -1,74 +0,0 @@
package Ciphers;
import java.math.BigInteger;
import java.security.SecureRandom;
import javax.swing.JOptionPane;
/** @author Nguyen Duy Tiep on 23-Oct-17. */
public final class RSA {
public static void main(String[] args) {
RSA rsa = new RSA(1024);
String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :");
String ciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext);
JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext));
}
private BigInteger modulus, privateKey, publicKey;
public RSA(int bits) {
generateKeys(bits);
}
/**
* @return encrypted message
*/
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
* @return encrypted message as big integer
*/
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
/**
* @return plain message
*/
public synchronized String decrypt(String encryptedMessage) {
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
* @return plain message as big integer
*/
public synchronized BigInteger decrypt(BigInteger encryptedMessage) {
return encryptedMessage.modPow(privateKey, modulus);
}
/**
* Generate a new public and private key set.
*/
public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bits / 2, 100, r);
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("3");
while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(new BigInteger("2"));
}
privateKey = publicKey.modInverse(m);
}
}

View File

@ -1,83 +0,0 @@
package Ciphers;
import java.util.*;
/**
* The simple substitution cipher is a cipher that has been in use for many hundreds of years (an
* excellent history is given in Simon Singhs 'the Code Book'). It basically consists of
* substituting every plaintext character for a different ciphertext character. It differs from the
* Caesar cipher in that the cipher alphabet is not simply the alphabet shifted, it is completely
* jumbled.
*
* @author Hassan Elseoudy
*/
public class SimpleSubstitutionCipher {
/**
* Encrypt text by replacing each element with its opposite character.
*
* @return Encrypted message
*/
public static String encode(String message, String cipherSmall) {
StringBuilder encoded = new StringBuilder();
// This map is used to encode
Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
// To handle Small and Capital letters
for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i));
cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i));
}
for (int i = 0; i < message.length(); i++) {
if (Character.isAlphabetic(message.charAt(i))) encoded.append(cipherMap.get(message.charAt(i)));
else encoded.append(message.charAt(i));
}
return encoded.toString();
}
/**
* Decrypt message by replacing each element with its opposite character in cipher.
*
* @return message
*/
public static String decode(String encryptedMessage, String cipherSmall) {
StringBuilder decoded = new StringBuilder();
Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++);
}
for (int i = 0; i < encryptedMessage.length(); i++) {
if (Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded.append(cipherMap.get(encryptedMessage.charAt(i)));
else decoded.append(encryptedMessage.charAt(i));
}
return decoded.toString();
}
/** TODO remove main and make JUnit Testing */
public static void main(String[] args) {
String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb");
String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b);
}
}

View File

@ -1,62 +0,0 @@
package Ciphers;
/**
* A Java implementation of Vigenere Cipher.
*
* @author straiffix
* @author beingmartinbmc
*/
public class Vigenere {
public static String encrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'));
} else {
result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'));
}
} else {
result.append(c);
}
j = ++j % key.length();
}
return result.toString();
}
public static String decrypt(final String message, final String key) {
StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26));
} else {
result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26));
}
} else {
result.append(c);
}
j = ++j % key.length();
}
return result.toString();
}
public static void main(String[] args) {
String text = "Hello World!";
String key = "itsakey";
System.out.println(text);
String ciphertext = encrypt(text, key);
System.out.println(ciphertext);
System.out.println(decrypt(ciphertext, key));
}
}

View File

@ -1,92 +0,0 @@
package ciphers;
import java.util.*;
/**
*
* The simple substitution cipher is a cipher that has been in use for many hundreds of years
* (an excellent history is given in Simon Singhs 'the Code Book').
* It basically consists of substituting every plaintext character for a different ciphertext character.
* It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted,
* it is completely jumbled.
*
*/
public class simpleSubCipher {
/**
* Encrypt text by replacing each element with its opposite character.
*
* @param message
* @param cipherSmall
* @return Encrypted message
*/
public static String encode(String message, String cipherSmall) {
String encoded = "";
// This map is used to encode
Map<Character,Character> cipherMap = new HashMap<Character,Character>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
// To handle Small and Capital letters
for(int i = 0; i < cipherSmall.length(); i++){
cipherMap.put(beginSmallLetter++,cipherSmall.charAt(i));
cipherMap.put(beginCapitalLetter++,cipherCapital.charAt(i));
}
for(int i = 0; i < message.length(); i++){
if(Character.isAlphabetic(message.charAt(i)))
encoded += cipherMap.get(message.charAt(i));
else
encoded += message.charAt(i);
}
return encoded;
}
/**
* Decrypt message by replacing each element with its opposite character in cipher.
*
* @param encryptedMessage
* @param cipherSmall
* @return message
*/
public static String decode(String encryptedMessage, String cipherSmall) {
String decoded = "";
Map<Character,Character> cipherMap = new HashMap<Character,Character>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
for(int i = 0; i < cipherSmall.length(); i++){
cipherMap.put(cipherSmall.charAt(i),beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i),beginCapitalLetter++);
}
for(int i = 0; i < encryptedMessage.length(); i++){
if(Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded += cipherMap.get(encryptedMessage.charAt(i));
else
decoded += encryptedMessage.charAt(i);
}
return decoded;
}
public static void main(String[] args) {
String a = encode("defend the east wall of the castle","phqgiumeaylnofdxjkrcvstzwb");
String b = decode(a,"phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b);
}
}

View File

@ -1,127 +0,0 @@
package Conversions;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Class for converting from "any" base to "any" other base, when "any" means from 2-36. Works by
* going from base 1 to decimal to base 2. Includes auxiliary method for determining whether a
* number is valid for a given base.
*
* @author Michael Rolland
* @version 2017.10.10
*/
public class AnyBaseToAnyBase {
/** Smallest and largest base you want to accept as valid input */
static final int MINIMUM_BASE = 2;
static final int MAXIMUM_BASE = 36;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String n;
int b1, b2;
while (true) {
try {
System.out.print("Enter number: ");
n = in.next();
System.out.print(
"Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!");
continue;
}
if (!validForBase(n, b1)) {
System.out.println("The number is invalid for this base!");
continue;
}
System.out.print(
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!");
continue;
}
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input.");
in.next();
}
}
System.out.println(base2base(n, b1, b2));
in.close();
}
/** Checks if a number (as a String) is valid for a given base. */
public static boolean validForBase(String n, int base) {
char[] validDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
};
// digitsForBase contains all the valid digits for the base given
char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base);
// Convert character array into set for convenience of contains() method
HashSet<Character> digitsList = new HashSet<>();
for (int i = 0; i < digitsForBase.length; i++) digitsList.add(digitsForBase[i]);
// Check that every digit in n is within the list of valid digits for that base.
for (char c : n.toCharArray()) if (!digitsList.contains(c)) return false;
return true;
}
/**
* Method to convert any integer from base b1 to base b2. Works by converting from b1 to decimal,
* then decimal to b2.
*
* @param n The integer to be converted.
* @param b1 Beginning base.
* @param b2 End base.
* @return n in base b2.
*/
public static String base2base(String n, int b1, int b2) {
// 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;
char charB1;
String output = "";
// Go through every character of n
for (int i = 0; i < n.length(); i++) {
// store the character in charB1
charB1 = n.charAt(i);
// if it is a non-number, convert it to a decimal value >9 and store it in charB2
if (charB1 >= 'A' && charB1 <= 'Z') charB2 = 10 + (charB1 - 'A');
// Else, store the integer value in charB2
else charB2 = charB1 - '0';
// Convert the digit to decimal and add it to the
// decimalValue of n
decimalValue = decimalValue * b1 + charB2;
}
// Converting the decimal value to base b2:
// A number is converted from decimal to another base
// by continuously dividing by the base and recording
// the remainder until the quotient is zero. The number in the
// new base is the remainders, with the last remainder
// being the left-most digit.
if (0 == decimalValue) return "0";
// While the quotient is NOT zero:
while (decimalValue != 0) {
// If the remainder is a digit < 10, simply add it to
// the left side of the new number.
if (decimalValue % b2 < 10) output = Integer.toString(decimalValue % b2) + output;
// If the remainder is >= 10, add a character with the
// corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
else output = (char) ((decimalValue % b2) + 55) + output;
// Divide by the new base again
decimalValue /= b2;
}
return output;
}
}

View File

@ -1,51 +0,0 @@
package Conversions;
/** @author Varun Upadhyay (https://github.com/varunu28) */
// Driver program
public class AnyBaseToDecimal {
public static void main(String[] args) {
assert convertToDecimal("1010", 2) == Integer.valueOf("1010", 2);
assert convertToDecimal("777", 8) == Integer.valueOf("777", 8);
assert convertToDecimal("999", 10) == Integer.valueOf("999", 10);
assert convertToDecimal("ABCDEF", 16) == Integer.valueOf("ABCDEF", 16);
assert convertToDecimal("XYZ", 36) == Integer.valueOf("XYZ", 36);
}
/**
* Convert any radix to 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
*/
public static int convertToDecimal(String s, int radix) {
int num = 0;
int pow = 1;
for (int i = s.length() - 1; i >= 0; i--) {
int digit = valOfChar(s.charAt(i));
if (digit >= radix) {
throw new NumberFormatException("For input string " + s);
}
num += valOfChar(s.charAt(i)) * pow;
pow *= radix;
}
return num;
}
/**
* Convert character to integer
*
* @param c the character
* @return represented digit of given character
* @throws NumberFormatException if {@code ch} is not UpperCase or Digit character.
*/
public static int valOfChar(char c) {
if (!(Character.isUpperCase(c) || Character.isDigit(c))) {
throw new NumberFormatException("invalid character :" + c);
}
return Character.isDigit(c) ? c - '0' : c - 'A' + 10;
}
}

View File

@ -1,30 +0,0 @@
package Conversions;
import java.util.Scanner;
// given a source number , source base, destination base, this code can give you the destination
// number.
// sn ,sb,db ---> ()dn . this is what we have to do .
public class AnytoAny {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int sn = scn.nextInt();
int sb = scn.nextInt();
int db = scn.nextInt();
int m = 1, dec = 0, dn = 0;
while (sn != 0) {
dec = dec + (sn % 10) * m;
m *= sb;
sn /= 10;
}
m = 1;
while (dec != 0) {
dn = dn + (dec % db) * m;
m *= 10;
dec /= db;
}
System.out.println(dn);
scn.close();
}
}

View File

@ -1,27 +0,0 @@
package Conversions;
import java.util.Scanner;
/** This class converts a Binary number to a Decimal number */
class BinaryToDecimal {
/**
* Main Method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int binNum, binCopy, d, s = 0, power = 0;
System.out.print("Binary number: ");
binNum = sc.nextInt();
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
s += d * (int) Math.pow(2, power++);
binCopy /= 10;
}
System.out.println("Decimal equivalent:" + s);
sc.close();
}
}

View File

@ -1,55 +0,0 @@
package Conversions;
import java.util.*;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*/
public class BinaryToHexadecimal {
/**
* 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 * Math.pow(2, i);
}
hex = hm.get(code4) + hex;
}
return hex;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter binary number:");
int binary = sc.nextInt();
String hex = binToHex(binary);
System.out.println("Hexadecimal Code:" + hex);
sc.close();
}
}

View File

@ -1,47 +0,0 @@
package Conversions;
import java.util.Scanner;
/**
* 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();
}
/**
* This method converts a binary number to an octal number.
*
* @param binary The binary number
* @return The octal 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;
}
return octal;
}
}

View File

@ -1,61 +0,0 @@
package Conversions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/** @author Varun Upadhyay (https://github.com/varunu28) */
// Driver Program
public class DecimalToAnyBase {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal input below: ");
int decInput = Integer.parseInt(br.readLine());
System.out.println();
System.out.println("Enter the base below: ");
int base = Integer.parseInt(br.readLine());
System.out.println();
System.out.println("Decimal Input" + " is: " + decInput);
System.out.println(
"Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
br.close();
}
/**
* This method produces a String value of any given input decimal in any base
*
* @param inp Decimal of which we need the value in base in String format
* @return string format of the converted value in the given base
*/
public static String convertToAnyBase(int inp, int base) {
ArrayList<Character> charArr = new ArrayList<>();
while (inp > 0) {
charArr.add(reVal(inp % base));
inp /= base;
}
StringBuilder str = new StringBuilder(charArr.size());
for (Character ch : charArr) {
str.append(ch);
}
return str.reverse().toString();
}
/**
* This method produces character value of the input integer and returns it
*
* @param num integer of which we need the character value of
* @return character value of input integer
*/
public static char reVal(int num) {
if (num >= 0 && num <= 9) return (char) (num + '0');
else return (char) (num - 10 + 'A');
}
}

View File

@ -1,47 +0,0 @@
package Conversions;
import java.util.Scanner;
/** This class converts a Decimal number to a Binary number */
class DecimalToBinary {
/**
* Main Method
*
* @param args Command Line Arguments
*/
public static void main(String args[]) {
conventionalConversion();
bitwiseConversion();
}
/** This method converts a decimal number to a binary number using a conventional algorithm. */
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();
}
/** 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;
}
System.out.println("\tBinary number: " + b);
input.close();
}
}

View File

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

View File

@ -1,29 +0,0 @@
package Conversions;
import java.util.Scanner;
/** This class converts Decimal numbers to Octal Numbers */
public class DecimalToOctal {
/**
* Main Method
*
* @param args Command line Arguments
*/
// 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;
}
System.out.println("Octal equivalent:" + s);
sc.close();
}
}

View File

@ -1,73 +0,0 @@
package 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;
}
/**
* This method converts a Decimal number to a octal number
*
* @param q The Decimal Number
* @return The Octal number
*/
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++;
}
octnum /= 10;
return octnum;
}
/**
* Main method that gets the hex input from user and converts it into octal.
*
* @param args arguments
*/
public static void main(String args[]) {
String hexadecnum;
int decnum, octalnum;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
decnum =
hex2decimal(
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum
// convert decimal to octal
octalnum = decimal2octal(decnum);
System.out.println("Number in octal: " + octalnum);
scan.close();
}
}

View File

@ -1,35 +0,0 @@
package Conversions;
// Hex [0-9],[A-F] -> Binary [0,1]
public class HexaDecimalToBinary {
private final int LONG_BITS = 8;
public void convert(String numHex) {
// String a HexaDecimal:
int conHex = Integer.parseInt(numHex, 16);
// Hex a Binary:
String binary = Integer.toBinaryString(conHex);
// Output:
System.out.println(numHex + " = " + completeDigits(binary));
}
public String completeDigits(String binNum) {
for (int i = binNum.length(); i < LONG_BITS; i++) {
binNum = "0" + binNum;
}
return binNum;
}
public static void main(String[] args) {
// Testing Numbers:
String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", "19", "01", "02", "03", "04"};
HexaDecimalToBinary objConvert = new HexaDecimalToBinary();
for (String num : hexNums) {
objConvert.convert(num);
}
}
}

View File

@ -1,39 +0,0 @@
package Conversions;
import java.util.Scanner;
public class HexaDecimalToDecimal {
// convert hexadecimal to decimal
public static int getHexaToDec(String hex) {
String digits = "0123456789ABCDEF";
hex = hex.toUpperCase();
int val = 0;
for (int i = 0; i < hex.length(); i++) {
int d = digits.indexOf(hex.charAt(i));
val = 16 * val + d;
}
return val;
}
// 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;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Hexadecimal Number : ");
hexa_Input = scan.nextLine();
// convert hexadecimal to decimal
dec_output = getHexaToDec(hexa_Input);
/*
Pass the string to the getHexaToDec function
and it returns the decimal form in the variable dec_output.
*/
System.out.println("Number in Decimal: " + dec_output);
scan.close();
}
}

View File

@ -1,39 +0,0 @@
package Conversions;
/**
* Converting Integers into Roman Numerals
*
* <p>('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 {
private static int[] allArabianRomanNumbers =
new int[] {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] allRomanNumbers =
new String[] {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
// Value must be > 0
public static String integerToRoman(int num) {
if (num <= 0) {
return "";
}
StringBuilder builder = new StringBuilder();
for (int a = 0; a < allArabianRomanNumbers.length; a++) {
int times = num / allArabianRomanNumbers[a];
for (int b = 0; b < times; b++) {
builder.append(allRomanNumbers[a]);
}
num -= times * allArabianRomanNumbers[a];
}
return builder.toString();
}
public static void main(String[] args) {
System.out.println(IntegerToRoman.integerToRoman(2131));
}
}

View File

@ -1,45 +0,0 @@
package Conversions;
import java.util.Scanner;
/**
* Converts any Octal Number to a Decimal Number
*
* @author Zachary Jones
*/
public class OctalToDecimal {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Octal Input: ");
String inputOctal = sc.nextLine();
int result = convertOctalToDecimal(inputOctal);
if (result != -1) System.out.println("Result convertOctalToDecimal : " + result);
sc.close();
}
/**
* This method converts an octal number to a decimal number.
*
* @param inputOctal The octal number
* @return The decimal number
*/
public static int convertOctalToDecimal(String inputOctal) {
try {
// Actual conversion of Octal to Decimal:
Integer outputDecimal = Integer.parseInt(inputOctal, 8);
return outputDecimal;
} 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;
}
}
}

View File

@ -1,62 +0,0 @@
package Conversions;
import java.util.Scanner;
/**
* Converts any Octal Number to HexaDecimal
*
* @author Tanmay Joshi
*/
public class OctalToHexadecimal {
/**
* This method converts a Octal number to a decimal number
*
* @param s The Octal Number
* @return The Decimal number
*/
public static int octToDec(String s) {
int i = 0;
for (int j = 0; j < s.length(); j++) {
char num = s.charAt(j);
num -= '0';
i *= 8;
i += num;
}
return i;
}
/**
* This method converts a Decimal number to a Hexadecimal number
*
* @param d The Decimal Number
* @return The Hexadecimal number
*/
public static String decimalToHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0) return "0";
String hex = "";
while (d > 0) {
int digit = d % 16;
hex = digits.charAt(digit) + hex;
d = d / 16;
}
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();
}
}

View File

@ -1,165 +0,0 @@
package Conversions;
import java.util.Arrays;
/**
* The RGB color model is an additive color model in which red, green, and blue light are added
* together in various ways to reproduce a broad array of colors. The name of the model comes from
* the initials of the three additive primary colors, red, green, and blue. Meanwhile, the HSV
* representation models how colors appear under light. In it, colors are represented using three
* components: hue, saturation and (brightness-)value. This class provides methods for converting
* colors from one representation to the other. (description adapted from
* https://en.wikipedia.org/wiki/RGB_color_model and https://en.wikipedia.org/wiki/HSL_and_HSV).
*/
public class RgbHsvConversion {
public static void main(String[] args) {
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
// Test hsvToRgb-method
assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0});
assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255});
assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0});
assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0});
assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0});
assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255});
assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255});
assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128});
assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224});
assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80});
// Test rgbToHsv-method
// approximate-assertions needed because of small deviations due to converting between
// int-values and double-values.
assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[] {0, 0, 0});
assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[] {0, 0, 1});
assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[] {0, 1, 1});
assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[] {60, 1, 1});
assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[] {120, 1, 1});
assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[] {240, 1, 1});
assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[] {300, 1, 1});
assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[] {180, 0.5, 0.5});
assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[] {234, 0.14, 0.88});
assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[] {330, 0.75, 0.5});
}
/**
* Conversion from the HSV-representation to the RGB-representation.
*
* @param hue Hue of the color.
* @param saturation Saturation of the color.
* @param value Brightness-value of the color.
* @return The tuple of RGB-components.
*/
public static int[] hsvToRgb(double hue, double saturation, double value) {
if (hue < 0 || hue > 360) {
throw new IllegalArgumentException("hue should be between 0 and 360");
}
if (saturation < 0 || saturation > 1) {
throw new IllegalArgumentException("saturation should be between 0 and 1");
}
if (value < 0 || value > 1) {
throw new IllegalArgumentException("value should be between 0 and 1");
}
double chroma = value * saturation;
double hueSection = hue / 60;
double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1));
double matchValue = value - chroma;
return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent);
}
/**
* Conversion from the RGB-representation to the HSV-representation.
*
* @param red Red-component of the color.
* @param green Green-component of the color.
* @param blue Blue-component of the color.
* @return The tuple of HSV-components.
*/
public static double[] rgbToHsv(int red, int green, int blue) {
if (red < 0 || red > 255) {
throw new IllegalArgumentException("red should be between 0 and 255");
}
if (green < 0 || green > 255) {
throw new IllegalArgumentException("green should be between 0 and 255");
}
if (blue < 0 || blue > 255) {
throw new IllegalArgumentException("blue should be between 0 and 255");
}
double dRed = (double) red / 255;
double dGreen = (double) green / 255;
double dBlue = (double) blue / 255;
double value = Math.max(Math.max(dRed, dGreen), dBlue);
double chroma = value - Math.min(Math.min(dRed, dGreen), dBlue);
double saturation = value == 0 ? 0 : chroma / value;
double hue;
if (chroma == 0) {
hue = 0;
} else if (value == dRed) {
hue = 60 * (0 + (dGreen - dBlue) / chroma);
} else if (value == dGreen) {
hue = 60 * (2 + (dBlue - dRed) / chroma);
} else {
hue = 60 * (4 + (dRed - dGreen) / chroma);
}
hue = (hue + 360) % 360;
return new double[] {hue, saturation, value};
}
private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
boolean bHue = Math.abs(hsv1[0] - hsv2[0]) < 0.2;
boolean bSaturation = Math.abs(hsv1[1] - hsv2[1]) < 0.002;
boolean bValue = Math.abs(hsv1[2] - hsv2[2]) < 0.002;
return bHue && bSaturation && bValue;
}
private static int[] getRgbBySection(
double hueSection, double chroma, double matchValue, double secondLargestComponent) {
int red;
int green;
int blue;
if (hueSection >= 0 && hueSection <= 1) {
red = convertToInt(chroma + matchValue);
green = convertToInt(secondLargestComponent + matchValue);
blue = convertToInt(matchValue);
} else if (hueSection > 1 && hueSection <= 2) {
red = convertToInt(secondLargestComponent + matchValue);
green = convertToInt(chroma + matchValue);
blue = convertToInt(matchValue);
} else if (hueSection > 2 && hueSection <= 3) {
red = convertToInt(matchValue);
green = convertToInt(chroma + matchValue);
blue = convertToInt(secondLargestComponent + matchValue);
} else if (hueSection > 3 && hueSection <= 4) {
red = convertToInt(matchValue);
green = convertToInt(secondLargestComponent + matchValue);
blue = convertToInt(chroma + matchValue);
} else if (hueSection > 4 && hueSection <= 5) {
red = convertToInt(secondLargestComponent + matchValue);
green = convertToInt(matchValue);
blue = convertToInt(chroma + matchValue);
} else {
red = convertToInt(chroma + matchValue);
green = convertToInt(matchValue);
blue = convertToInt(secondLargestComponent + matchValue);
}
return new int[] {red, green, blue};
}
private static int convertToInt(double input) {
return (int) Math.round(255 * input);
}
}

View File

@ -1,66 +0,0 @@
package Conversions;
import java.util.*;
public class RomanToInteger {
private static Map<Character, Integer> map =
new HashMap<Character, Integer>() {
/** */
private static final long serialVersionUID = 87605733047260530L;
{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}
};
// Roman Number = Roman Numerals
/**
* This function convert Roman number into Integer
*
* @param A Roman number string
* @return integer
*/
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);
if (prev != ' ') {
// checking current Number greater then previous or not
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
}
int currentNum = map.get(c);
// if current number greater then prev max previous then add
if (currentNum >= newPrev) {
sum += currentNum;
} else {
// subtract upcoming number until upcoming number not greater then prev max
sum -= currentNum;
}
prev = c;
}
return sum;
}
public static void main(String[] args) {
int sum = romanToInt("MDCCCIV");
System.out.println(sum);
}
}

View File

@ -1,42 +0,0 @@
package Conversions;
import java.util.Scanner;
/**
* Converts turkish character to latin character
*
* @author Özgün Gökşenli
*/
public class TurkishToLatinConversion {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the string: ");
String b = sc.next();
System.out.println("Converted: " + convertTurkishToLatin(b));
sc.close();
}
/**
* This method converts a turkish character to latin character.
*
* @param param String paramter
* @return String
*/
public static String convertTurkishToLatin(String param) {
char[] turkishChars =
new char[] {0x131, 0x130, 0xFC, 0xDC, 0xF6, 0xD6, 0x15F, 0x15E, 0xE7, 0xC7, 0x11F, 0x11E};
char[] latinChars = new char[] {'i', 'I', 'u', 'U', 'o', 'O', 's', 'S', 'c', 'C', 'g', 'G'};
for (int i = 0; i < turkishChars.length; i++) {
param =
param.replaceAll(
new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
}
return param;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,110 +0,0 @@
package DataStructures.Bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Collection which does not allow removing elements (only collect and iterate)
*
* @param <Element> - the generic type of an element in this bag
*/
public class Bag<Element> implements Iterable<Element> {
private Node<Element> firstElement; // first element of the bag
private int size; // size of bag
private static class Node<Element> {
private Element content;
private Node<Element> nextElement;
}
/** Create an empty bag */
public Bag() {
firstElement = null;
size = 0;
}
/** @return true if this bag is empty, false otherwise */
public boolean isEmpty() {
return firstElement == null;
}
/** @return the number of elements */
public int size() {
return size;
}
/** @param element - the element to add */
public void add(Element element) {
Node<Element> oldfirst = firstElement;
firstElement = new Node<>();
firstElement.content = element;
firstElement.nextElement = oldfirst;
size++;
}
/**
* Checks if the bag contains a specific element
*
* @param element which you want to look for
* @return true if bag contains element, otherwise false
*/
public boolean contains(Element element) {
Iterator<Element> iterator = this.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals(element)) {
return true;
}
}
return false;
}
/** @return an iterator that iterates over the elements in this bag in arbitrary order */
public Iterator<Element> iterator() {
return new ListIterator<>(firstElement);
}
@SuppressWarnings("hiding")
private class ListIterator<Element> implements Iterator<Element> {
private Node<Element> currentElement;
public ListIterator(Node<Element> firstElement) {
currentElement = firstElement;
}
public boolean hasNext() {
return currentElement != null;
}
/** remove is not allowed in a bag */
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public Element next() {
if (!hasNext()) throw new NoSuchElementException();
Element element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
/** main-method for testing */
public static void main(String[] args) {
Bag<String> bag = new Bag<>();
bag.add("1");
bag.add("1");
bag.add("2");
System.out.println("size of bag = " + bag.size());
for (String s : bag) {
System.out.println(s);
}
System.out.println(bag.contains(null));
System.out.println(bag.contains("1"));
System.out.println(bag.contains("3"));
}
}

View File

@ -1,130 +0,0 @@
package DataStructures.Buffers;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
public class CircularBuffer {
private char[] _buffer;
public final int _buffer_size;
private int _write_index = 0;
private int _read_index = 0;
private AtomicInteger _readable_data = new AtomicInteger(0);
public CircularBuffer(int buffer_size) {
if (!IsPowerOfTwo(buffer_size)) {
throw new IllegalArgumentException();
}
this._buffer_size = buffer_size;
_buffer = new char[buffer_size];
}
private boolean IsPowerOfTwo(int i) {
return (i & (i - 1)) == 0;
}
private int getTrueIndex(int i) {
return i % _buffer_size;
}
public Character readOutChar() {
Character result = null;
// if we have data to read
if (_readable_data.get() > 0) {
result = Character.valueOf(_buffer[getTrueIndex(_read_index)]);
_readable_data.decrementAndGet();
_read_index++;
}
return result;
}
public boolean writeToCharBuffer(char c) {
boolean result = false;
// if we can write to the buffer
if (_readable_data.get() < _buffer_size) {
// write to buffer
_buffer[getTrueIndex(_write_index)] = c;
_readable_data.incrementAndGet();
_write_index++;
result = true;
}
return result;
}
private static class TestWriteWorker implements Runnable {
String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
Random _random = new Random();
CircularBuffer _buffer;
public TestWriteWorker(CircularBuffer cb) {
this._buffer = cb;
}
private char getRandomChar() {
return _alphabet.charAt(_random.nextInt(_alphabet.length()));
}
public void run() {
while (!Thread.interrupted()) {
if (!_buffer.writeToCharBuffer(getRandomChar())) {
Thread.yield();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
return;
}
}
}
}
}
private static class TestReadWorker implements Runnable {
CircularBuffer _buffer;
public TestReadWorker(CircularBuffer cb) {
this._buffer = cb;
}
@Override
public void run() {
System.out.println("Printing Buffer:");
while (!Thread.interrupted()) {
Character c = _buffer.readOutChar();
if (c != null) {
System.out.print(c.charValue());
} else {
Thread.yield();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
System.out.println();
return;
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
int buffer_size = 1024;
// create circular buffer
CircularBuffer cb = new CircularBuffer(buffer_size);
// create threads that read and write the buffer.
Thread write_thread = new Thread(new TestWriteWorker(cb));
Thread read_thread = new Thread(new TestReadWorker(cb));
read_thread.start();
write_thread.start();
// wait some amount of time
Thread.sleep(10000);
// interrupt threads and exit
write_thread.interrupt();
read_thread.interrupt();
}
}

View File

@ -1,32 +0,0 @@
package DataStructures.DisjointSets;
public class DisjointSets<T> {
public Node<T> MakeSet(T x) {
return new Node<T>(x);
};
public Node<T> FindSet(Node<T> node) {
if (node != node.parent) {
node.parent = FindSet(node.parent);
}
return node.parent;
}
public void UnionSet(Node<T> x, Node<T> y) {
Node<T> nx = FindSet(x);
Node<T> ny = FindSet(y);
if (nx == ny) {
return;
}
if (nx.rank > ny.rank) {
ny.parent = nx;
} else if (ny.rank > nx.rank) {
nx.parent = ny;
} else {
nx.parent = ny;
ny.rank++;
}
}
}

View File

@ -1,11 +0,0 @@
package DataStructures.DisjointSets;
public class Node<T> {
public int rank;
public Node<T> parent;
public T data;
public Node(T data) {
this.data = data;
parent = this;
}
}

View File

@ -1,211 +0,0 @@
package DataStructures.DynamicArray;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* 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 Object[] elements;
/**
* constructor
*
* @param capacity the starting length of the desired array
*/
public DynamicArray(final int capacity) {
this.size = 0;
this.capacity = capacity;
this.elements = new Object[this.capacity];
}
/** No-args constructor */
public DynamicArray() {
this(DEFAULT_CAPACITY);
}
/**
* Adds an element to the array If full, creates a copy array twice the size of the current one
*
* @param element the element of type <E> 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++;
}
/**
* Places element of type <E> at the desired index
*
* @param index the index for the element to be placed
* @param element the element to be inserted
*/
public void put(final int index, E element) {
this.elements[index] = element;
}
/**
* get method for element at a given index returns null if the index is empty
*
* @param index the desired index of the element
* @return <E> the element at the specified index
*/
public E get(final int index) {
return getElement(index);
}
/**
* Removes an element from the array
*
* @param index the index of the element to be removed
* @return <E> the element removed
*/
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));
return oldElement;
}
/**
* get method for size field
*
* @return int size
*/
public int getSize() {
return this.size;
}
/**
* isEmpty helper method
*
* @return boolean true if the array contains no elements, false otherwise
*/
public boolean isEmpty() {
return this.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);
}
elements[this.size = newSize] = null;
}
private E getElement(final int index) {
return (E) this.elements[index];
}
private int newCapacity(int capacity) {
this.capacity = capacity;
return this.capacity;
}
/**
* returns a String representation of this object
*
* @return String a String representing the array
*/
@Override
public String toString() {
return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
}
/**
* Creates and returns a new Dynamic Array Iterator
*
* @return Iterator a Dynamic Array Iterator
*/
@Override
public Iterator iterator() {
return new DynamicArrayIterator();
}
private class DynamicArrayIterator implements Iterator<E> {
private int cursor;
@Override
public boolean hasNext() {
return this.cursor != size;
}
@Override
public E next() {
if (this.cursor > DynamicArray.this.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;
}
@Override
public void remove() {
if (this.cursor < 0) throw new IllegalStateException();
DynamicArray.this.remove(this.cursor);
this.cursor--;
}
@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));
}
}
}
/**
* This class is the driver for the DynamicArray<E> class it tests a variety of methods and prints
* the output
*/
public static void main(String[] args) {
DynamicArray<String> names = new DynamicArray<>();
names.add("Peubes");
names.add("Marley");
for (String name : names) {
System.out.println(name);
}
names.stream().forEach(System.out::println);
System.out.println(names);
System.out.println(names.getSize());
names.remove(0);
for (String name : names) {
System.out.println(name);
}
}
}

View File

@ -1,179 +0,0 @@
/*
Time Complexity = O(E), where E is equal to the number of edges
*/
package DataStructures.Graphs;
import java.util.*;
public class A_Star {
private static class Graph {
// Graph's structure can be changed only applying changes to this class.
private ArrayList<ArrayList<Edge>> graph;
// Initialise ArrayLists in Constructor
public Graph(int size) {
this.graph = new ArrayList<>();
for (int i = 0; i < size; i++) {
this.graph.set(i, new ArrayList<>());
}
}
private ArrayList<Edge> getNeighbours(int from) {
return this.graph.get(from);
}
// Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) {
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
}
}
private static class Edge {
private int from;
private int to;
private int weight;
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
public int getFrom() {
return from;
}
public int getTo() {
return to;
}
public int getWeight() {
return weight;
}
}
// class to iterate during the algorithm execution, and also used to return the solution.
private static class PathAndDistance {
private int distance; // distance advanced so far.
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) {
this.distance = distance;
this.path = path;
this.estimated = estimated;
}
public int getDistance() {
return distance;
}
public ArrayList<Integer> getPath() {
return path;
}
public int getEstimated() {
return estimated;
}
private void printSolution() {
if (this.path != null)
System.out.println(
"Optimal path: " + this.path + ", distance: " + this.distance);
else System.out.println("There is no path available to connect the points");
}
}
private static void initializeGraph(Graph graph, ArrayList<Integer> data) {
for (int i = 0; i < data.size(); i += 4) {
graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2)));
}
/*
.x. node
(y) cost
- or | or / bidirectional connection
( 98)- .7. -(86)- .4.
|
( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11.
|
. 1. -------------------- (160)
| \ |
(211) \ .6.
| \ |
. 5. (101)-.13. -(138) (115)
| | | /
( 99) ( 97) | /
| | | /
.12. -(151)- .15. -(80)- .14. | /
| | | | /
( 71) (140) (146)- .2. -(120)
| | |
.19. -( 75)- . 0. .10. -(75)- .3.
| |
(118) ( 70)
| |
.16. -(111)- .9.
*/
}
public static void main(String[] args) {
// heuristic function optimistic values
int[] heuristic = {
366, 0, 160, 242, 161, 178, 77, 151, 226, 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374
};
Graph graph = new Graph(20);
ArrayList<Integer> graphData =
new ArrayList<>(
Arrays.asList(
0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151,
null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14,
146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null, 15, 5, 99, null, 14,
13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null,
17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic);
solution.printSolution();
}
public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
// nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value
// given by the heuristic function to reach the destination point from the current point.
PriorityQueue<PathAndDistance> queue =
new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
boolean solutionFound = false;
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring.
int currentPosition =
currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) solutionFound = true;
else
for (Edge edge : graph.getNeighbours(currentPosition))
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path.
queue.add(
new PathAndDistance(
currentData.getDistance() + edge.getWeight(),
updatedPath,
heuristic[edge.getTo()]));
}
}
return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1);
// Out of while loop, if there is a solution, the current Data stores the optimal path, and its
// distance
}
}

View File

@ -1,161 +0,0 @@
package DataStructures.Graphs;
import java.util.*;
class BellmanFord
/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/
{
int vertex, edge;
private Edge edges[];
private int index = 0;
BellmanFord(int v, int e) {
vertex = v;
edge = e;
edges = new Edge[e];
}
class Edge {
int u, v;
int w;
/**
* @param u Source Vertex
* @param v End vertex
* @param c Weight
*/
public Edge(int a, int b, int c) {
u = a;
v = b;
w = c;
}
}
/**
* @param p[] Parent array which shows updates in edges
* @param i Current vertex under consideration
*/
void printPath(int p[], int i) {
if (p[i] == -1) // Found the path back to parent
return;
printPath(p, p[i]);
System.out.print(i + " ");
}
public static void main(String args[]) {
BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables
obj.go();
}
public void
go() // Interactive run for understanding the class first time. Assumes source vertex is 0 and
// shows distance to all vertices
{
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please");
v = sc.nextInt();
e = sc.nextInt();
Edge arr[] = new Edge[e]; // Array of edges
System.out.println("Input edges");
for (i = 0; i < e; i++) {
u = sc.nextInt();
ve = sc.nextInt();
w = sc.nextInt();
arr[i] = new Edge(u, ve, w);
}
int dist[] =
new int
[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
int p[] = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) dist[i] = Integer.MAX_VALUE; // Initializing distance values
dist[0] = 0;
p[0] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
}
}
// Final cycle for negative checking
for (j = 0; j < e; j++)
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
}
if (neg == 0) // Go ahead and show results of computation
{
System.out.println("Distances are: ");
for (i = 0; i < v; i++) System.out.println(i + " " + dist[i]);
System.out.println("Path followed:");
for (i = 0; i < v; i++) {
System.out.print("0 ");
printPath(p, i);
System.out.println();
}
}
sc.close();
}
/**
* @param source Starting vertex
* @param end Ending vertex
* @param Edge Array of edges
*/
public void show(
int source,
int end,
Edge arr[]) // Just shows results of computation, if graph is passed to it. The graph should
// be created by using addEdge() method and passed by calling getEdgeArray() method
{
int i, j, v = vertex, e = edge, neg = 0;
double dist[] =
new double
[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
int p[] = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) dist[i] = Integer.MAX_VALUE; // Initializing distance values
dist[source] = 0;
p[source] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
}
}
// Final cycle for negative checking
for (j = 0; j < e; j++)
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
}
if (neg == 0) // Go ahead and show results of computaion
{
System.out.println("Distance is: " + dist[end]);
System.out.println("Path followed:");
System.out.print(source + " ");
printPath(p, end);
System.out.println();
}
}
/**
* @param x Source Vertex
* @param y End vertex
* @param z Weight
*/
public void addEdge(int x, int y, int z) // Adds unidirectional edge
{
edges[index++] = new Edge(x, y, z);
}
public Edge[] getEdgeArray() {
return edges;
}
}

View File

@ -1,80 +0,0 @@
package DataStructures.Graphs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Given an adjacency list of a graph adj of V no.
* of vertices having 0 based index.
* Check whether the graph is bipartite or not.
*
* Input :
* {{0, 1, 0, 1},
* {1, 0, 1, 0},
* {0, 1, 0, 1},
* {1, 0, 1, 0}}
*
* Output : YES
*/
public class BipartiteGrapfDFS {
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)== false) return false;
}
else if(color[it] == color[node]){
return false;
}
}
return true;
}
public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj)
{
// Code here
int[] color = new int[V+1];
Arrays.fill(color, -1);
for(int i =0; i< V; i++){
if(color[i] == -1){
if(!bipartite(V, adj, color, i)){
return false;
}
}
}
return true;
}
public static void main(String[] args) throws IOException {
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]);
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i =0;i < V; 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);
}
boolean ans = isBipartite(V, adj);
if(ans)
System.out.println("YES");
else
System.out.println("NO");
}
}
}

View File

@ -1,139 +0,0 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* A class that counts the number of different connected components in a graph
*
* @author Lukas Keul, Florian Mercks
*/
class Graph<E extends Comparable<E>> {
class Node {
E name;
public Node(E name) {
this.name = name;
}
}
class Edge {
Node startNode, endNode;
public Edge(Node startNode, Node endNode) {
this.startNode = startNode;
this.endNode = endNode;
}
}
ArrayList<Edge> edgeList;
ArrayList<Node> nodeList;
public Graph() {
edgeList = new ArrayList<Edge>();
nodeList = new ArrayList<Node>();
}
/**
* Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they will be added to it.
*
* @param startNode the starting Node from the edge
* @param endNode the ending Node from the edge
*/
public void addEdge(E startNode, E endNode) {
Node start = null, end = null;
for (Node node : nodeList) {
if (startNode.compareTo(node.name) == 0) {
start = node;
} else if (endNode.compareTo(node.name) == 0) {
end = node;
}
}
if (start == null) {
start = new Node(startNode);
nodeList.add(start);
}
if (end == null) {
end = new Node(endNode);
nodeList.add(end);
}
edgeList.add(new Edge(start, end));
}
/**
* Main method used for counting the connected components. Iterates through the array of nodes to
* do a depth first search to get all nodes of the graph from the actual node. These nodes are
* added to the array markedNodes and will be ignored if they are chosen in the nodeList.
*
* @return returns the amount of unconnected graphs
*/
public int countGraphs() {
int count = 0;
Set<Node> markedNodes = new HashSet<Node>();
for (Node n : nodeList) {
if (!markedNodes.contains(n)) {
markedNodes.add(n);
markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>()));
count++;
}
}
return count;
}
/**
* Implementation of depth first search.
*
* @param n the actual visiting node
* @param visited A list of already visited nodes in the depth first search
* @return returns a set of visited nodes
*/
public ArrayList<Node> depthFirstSearch(Node n, ArrayList<Node> visited) {
visited.add(n);
for (Edge e : edgeList) {
if (e.startNode.equals(n) && !visited.contains(e.endNode)) {
depthFirstSearch(e.endNode, visited);
}
}
return visited;
}
}
public class ConnectedComponent {
public static void main(String[] args) {
Graph<Character> graphChars = new Graph<>();
// Graph 1
graphChars.addEdge('a', 'b');
graphChars.addEdge('a', 'e');
graphChars.addEdge('b', 'e');
graphChars.addEdge('b', 'c');
graphChars.addEdge('c', 'd');
graphChars.addEdge('d', 'a');
graphChars.addEdge('x', 'y');
graphChars.addEdge('x', 'z');
graphChars.addEdge('w', 'w');
Graph<Integer> graphInts = new Graph<>();
// Graph 2
graphInts.addEdge(1, 2);
graphInts.addEdge(2, 3);
graphInts.addEdge(2, 4);
graphInts.addEdge(3, 5);
graphInts.addEdge(7, 8);
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
}

View File

@ -1,87 +0,0 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.util.Scanner;
class Cycle {
private int nodes, edges;
private int[][] adjacencyMatrix;
private boolean[] visited;
ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>();
public Cycle() {
Scanner in = new Scanner(System.in);
System.out.print("Enter the no. of nodes: ");
nodes = in.nextInt();
System.out.print("Enter the no. of Edges: ");
edges = in.nextInt();
adjacencyMatrix = new int[nodes][nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) {
visited[i] = false;
}
System.out.println("Enter the details of each edges <Start Node> <End Node>");
for (int i = 0; i < edges; i++) {
int start, end;
start = in.nextInt();
end = in.nextInt();
adjacencyMatrix[start][end] = 1;
}
in.close();
}
public void start() {
for (int i = 0; i < nodes; i++) {
ArrayList<Integer> temp = new ArrayList<>();
dfs(i, i, temp);
for (int j = 0; j < nodes; j++) {
adjacencyMatrix[i][j] = 0;
adjacencyMatrix[j][i] = 0;
}
}
}
private void dfs(Integer start, Integer curr, ArrayList<Integer> temp) {
temp.add(curr);
visited[curr] = true;
for (int i = 0; i < nodes; i++) {
if (adjacencyMatrix[curr][i] == 1) {
if (i == start) {
cycles.add(new ArrayList<Integer>(temp));
} else {
if (!visited[i]) {
dfs(start, i, temp);
}
}
}
}
if (temp.size() > 0) {
temp.remove(temp.size() - 1);
}
visited[curr] = false;
}
public void printAll() {
for (int i = 0; i < cycles.size(); i++) {
for (int j = 0; j < cycles.get(i).size(); j++) {
System.out.print(cycles.get(i).get(j) + " -> ");
}
System.out.println(cycles.get(i).get(0));
System.out.println();
}
}
}
public class Cycles {
public static void main(String[] args) {
Cycle c = new Cycle();
c.start();
c.printAll();
}
}

View File

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

View File

@ -1,76 +0,0 @@
package DataStructures.Graphs;
import java.util.Scanner;
public class FloydWarshall {
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
// 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
{
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; 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])
// if the new distance calculated is less then the earlier shortest
// calculated distance it get replaced as new shortest distance
{
DistanceMatrix[source][destination] =
DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
}
}
}
}
for (int source = 1; source <= numberofvertices; source++) System.out.print("\t" + source);
System.out.println();
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.println();
}
}
public static void main(String... arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int numberOfVertices = scan.nextInt();
int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberOfVertices; source++) {
for (int destination = 1; destination <= numberOfVertices; destination++) {
adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) {
adjacencyMatrix[source][destination] = 0;
continue;
}
if (adjacencyMatrix[source][destination] == 0) {
adjacencyMatrix[source][destination] = INFINITY;
}
}
}
System.out.println("The Transitive Closure of the Graph");
FloydWarshall floydwarshall = new FloydWarshall(numberOfVertices);
floydwarshall.floydwarshall(adjacencyMatrix);
scan.close();
}
}

View File

@ -1,129 +0,0 @@
package DataStructures.Graphs;
import java.util.ArrayList;
class AdjacencyListGraph<E extends Comparable<E>> {
ArrayList<Vertex> verticies;
public AdjacencyListGraph() {
verticies = new ArrayList<>();
}
private class Vertex {
E data;
ArrayList<Vertex> adjacentVerticies;
public Vertex(E data) {
adjacentVerticies = new ArrayList<>();
this.data = data;
}
public boolean addAdjacentVertex(Vertex to) {
for (Vertex v : adjacentVerticies) {
if (v.data.compareTo(to.data) == 0) {
return false; // the edge already exists
}
}
return adjacentVerticies.add(to); // this will return true;
}
public boolean removeAdjacentVertex(E to) {
// use indexes here so it is possible to
// remove easily without implementing
// equals method that ArrayList.remove(Object o) uses
for (int i = 0; i < adjacentVerticies.size(); i++) {
if (adjacentVerticies.get(i).data.compareTo(to) == 0) {
adjacentVerticies.remove(i);
return true;
}
}
return false;
}
}
/**
* this method removes an edge from the graph between two specified verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(E from, E to) {
Vertex fromV = null;
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) {
fromV = v;
break;
}
}
if (fromV == null) return false;
return fromV.removeAdjacentVertex(to);
}
/**
* this method adds an edge to the graph between two specified verticies
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(E from, E to) {
Vertex fromV = null, toV = null;
for (Vertex v : verticies) {
if (from.compareTo(v.data) == 0) { // see if from vertex already exists
fromV = v;
} else if (to.compareTo(v.data) == 0) { // see if to vertex already exists
toV = v;
}
if (fromV != null && toV != null) break; // both nodes exist so stop searching
}
if (fromV == null) {
fromV = new Vertex(from);
verticies.add(fromV);
}
if (toV == null) {
toV = new Vertex(to);
verticies.add(toV);
}
return fromV.addAdjacentVertex(toV);
}
/**
* this gives a list of verticies in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Vertex v : verticies) {
sb.append("Vertex: ");
sb.append(v.data);
sb.append("\n");
sb.append("Adjacent verticies: ");
for (Vertex v2 : v.adjacentVerticies) {
sb.append(v2.data);
sb.append(" ");
}
sb.append("\n");
}
return sb.toString();
}
}
public class Graphs {
public static void main(String args[]) {
AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>();
assert graph.addEdge(1, 2);
assert graph.addEdge(1, 5);
assert graph.addEdge(2, 5);
assert !graph.addEdge(1, 2);
assert graph.addEdge(2, 3);
assert graph.addEdge(3, 4);
assert graph.addEdge(4, 1);
assert !graph.addEdge(2, 3);
System.out.println(graph);
}
}

View File

@ -1,155 +0,0 @@
package DataStructures.Graphs;
import java.util.ArrayList;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Set;
import java.util.Queue;
import java.util.LinkedList;
/**
* An algorithm that sorts a graph in toplogical order.
*/
/**
* A class that represents the adjaceny list of a graph
*/
class AdjacencyList<E extends Comparable<E>>{
Map<E,ArrayList<E>> adj;
AdjacencyList(){
adj = new LinkedHashMap<E,ArrayList<E>>();
}
/**
* This function adds an Edge to the adjaceny list
* @param from , the vertex the edge is from
* @param to, the vertex the edge is going to
*/
void addEdge(E from, E to){
try{
adj.get(from).add(to);
}
catch(Exception E){
adj.put(from,new ArrayList<E>());
adj.get(from).add(to);
}
if(!adj.containsKey(to)){
adj.put(to, new ArrayList<E>());
}
}
/**
* @param v, A vertex in a graph
* @return returns an ArrayList of all the adjacents of vertex v
*/
ArrayList<E> getAdjacents(E v){
return adj.get(v);
}
/**
* @return returns a set of all vertices in the graph
*/
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>>{
AdjacencyList<E> graph;
Map<E,Integer> inDegree;
TopologicalSort(AdjacencyList<E> graph){
this.graph = graph;
}
/**
* Calculates the in degree of all vertices
*/
void calculateInDegree(){
inDegree = new HashMap<>();
for(E vertex: graph.getVertices()){
if(!inDegree.containsKey(vertex)){
inDegree.put(vertex,0);
}
for(E adjacent: graph.getAdjacents(vertex)){
try{
inDegree.put(adjacent,inDegree.get(adjacent) + 1);
}
catch(Exception e){
inDegree.put(adjacent,1);
}
}
}
}
/**
* Returns an ArrayList with vertices arranged in topological order
*/
ArrayList<E> topSortOrder(){
calculateInDegree();
Queue<E> q = new LinkedList<E>();
for(E vertex: inDegree.keySet()){
if(inDegree.get(vertex) == 0){
q.add(vertex);
}
}
ArrayList<E> answer = new ArrayList<>();
while(!q.isEmpty()){
E current = q.poll();
answer.add(current);
for(E adjacent: graph.getAdjacents(current)){
inDegree.put(adjacent,inDegree.get(adjacent)-1);
if(inDegree.get(adjacent) == 0){
q.add(adjacent);
}
}
}
return answer;
}
}
/**
* A driver class that sorts a given graph in topological order.
*/
public class KahnsAlgorithm{
public static void main(String[] args){
//Graph definition and initialization
AdjacencyList<String> graph = new AdjacencyList<>();
graph.addEdge("a","b");
graph.addEdge("c","a");
graph.addEdge("a","d");
graph.addEdge("b","d");
graph.addEdge("c","u");
graph.addEdge("u","b");
TopologicalSort<String> topSort = new TopologicalSort<>(graph);
//Printing the order
for(String s: topSort.topSortOrder()){
System.out.print(s+" ");
}
}
}

View File

@ -1,105 +0,0 @@
package DataStructures.Graphs;
// Problem -> Connect all the edges with the minimum cost.
// Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the
// group of edges with the minimum sum of their weights that connect the whole graph.
// The graph needs to be connected, because if there are nodes impossible to reach, there are no
// edges that could connect every node in the graph.
// KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a
// Priority Queue is used, to take first those less weighted.
// This implementations below has some changes compared to conventional ones, but they are explained
// all along the code.
import java.util.Comparator;
import java.util.HashSet;
import java.util.PriorityQueue;
public class Kruskal {
// Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of
// vertices
private static class Edge {
private int from;
private int to;
private int weight;
public Edge(int from, int to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
private static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) {
graph[from].add(new Edge(from, to, weight));
}
public static void main(String[] args) {
HashSet<Edge>[] graph = new HashSet[7];
for (int i = 0; i < graph.length; i++) {
graph[i] = new HashSet<>();
}
addEdge(graph, 0, 1, 2);
addEdge(graph, 0, 2, 3);
addEdge(graph, 0, 3, 3);
addEdge(graph, 1, 2, 4);
addEdge(graph, 2, 3, 5);
addEdge(graph, 1, 4, 3);
addEdge(graph, 2, 4, 1);
addEdge(graph, 3, 5, 7);
addEdge(graph, 4, 5, 8);
addEdge(graph, 5, 6, 9);
System.out.println("Initial Graph: ");
for (int i = 0; i < graph.length; i++) {
for (Edge edge : graph[i]) {
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
}
}
Kruskal k = new Kruskal();
HashSet<Edge>[] solGraph = k.kruskal(graph);
System.out.println("\nMinimal Graph: ");
for (int i = 0; i < solGraph.length; i++) {
for (Edge edge : solGraph[i]) {
System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to);
}
}
}
public HashSet<Edge>[] kruskal(HashSet<Edge>[] graph) {
int nodes = graph.length;
int[] captain = new int[nodes];
// captain of i, stores the set with all the connected nodes to i
HashSet<Integer>[] connectedGroups = new HashSet[nodes];
HashSet<Edge>[] minGraph = new HashSet[nodes];
PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
for (int i = 0; i < nodes; i++) {
minGraph[i] = new HashSet<>();
connectedGroups[i] = new HashSet<>();
connectedGroups[i].add(i);
captain[i] = i;
edges.addAll(graph[i]);
}
int connectedElements = 0;
// as soon as two sets merge all the elements, the algorithm must stop
while (connectedElements != nodes && !edges.isEmpty()) {
Edge edge = edges.poll();
// This if avoids cycles
if (!connectedGroups[captain[edge.from]].contains(edge.to)
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
// merge sets of the captains of each point connected by the edge
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
// update captains of the elements merged
connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]);
// add Edge to minimal graph
addEdge(minGraph, edge.from, edge.to, edge.weight);
// count how many elements have been merged
connectedElements = connectedGroups[captain[edge.from]].size();
}
}
return minGraph;
}
}

View File

@ -1,142 +0,0 @@
package DataStructures.Graphs;
public class MatrixGraphs {
public static void main(String args[]) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
graph.addEdge(2, 5);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
System.out.println(graph);
}
}
class AdjacencyMatrixGraph {
private int _numberOfVertices;
private int _numberOfEdges;
private int[][] _adjacency;
static final int EDGE_EXIST = 1;
static final int EDGE_NONE = 0;
public AdjacencyMatrixGraph(int givenNumberOfVertices) {
this.setNumberOfVertices(givenNumberOfVertices);
this.setNumberOfEdges(0);
this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]);
for (int i = 0; i < givenNumberOfVertices; i++) {
for (int j = 0; j < givenNumberOfVertices; j++) {
this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE;
}
}
}
private void setNumberOfVertices(int newNumberOfVertices) {
this._numberOfVertices = newNumberOfVertices;
}
public int numberOfVertices() {
return this._numberOfVertices;
}
private void setNumberOfEdges(int newNumberOfEdges) {
this._numberOfEdges = newNumberOfEdges;
}
public int numberOfEdges() {
return this._numberOfEdges;
}
private void setAdjacency(int[][] newAdjacency) {
this._adjacency = newAdjacency;
}
private int[][] adjacency() {
return this._adjacency;
}
private boolean adjacencyOfEdgeDoesExist(int from, int to) {
return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE);
}
public boolean vertexDoesExist(int aVertex) {
if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
return true;
} else {
return false;
}
}
public boolean edgeDoesExist(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
return (this.adjacencyOfEdgeDoesExist(from, to));
}
return false;
}
/**
* This method adds an edge to the graph between two specified vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns true if the edge did not exist, return false if it already did
*/
public boolean addEdge(int from, int to) {
if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) {
if (!this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST;
this.setNumberOfEdges(this.numberOfEdges() + 1);
return true;
}
}
return false;
}
/**
* this method removes an edge from the graph between two specified vertices
*
* @param from the data of the vertex the edge is from
* @param to the data of the vertex the edge is going to
* @return returns false if the edge doesn't exist, returns true if the edge exists and is removed
*/
public boolean removeEdge(int from, int to) {
if (!this.vertexDoesExist(from) || !this.vertexDoesExist(to)) {
if (this.adjacencyOfEdgeDoesExist(from, to)) {
this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE;
this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE;
this.setNumberOfEdges(this.numberOfEdges() - 1);
return true;
}
}
return false;
}
/**
* this gives a list of vertices in the graph and their adjacencies
*
* @return returns a string describing this graph
*/
public String toString() {
String s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
s = s + " \n";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
s = s + String.valueOf(this._adjacency[i][j]) + " ";
}
s = s + "\n";
}
return s;
}
}

View File

@ -1,102 +0,0 @@
package DataStructures.Graphs;
/**
* A Java program for Prim's Minimum Spanning Tree (MST) algorithm. adjacency matrix representation
* of the graph
*/
class PrimMST {
// Number of vertices in the graph
private static final int V = 5;
// A utility function to find the vertex with minimum key
// 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;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min) {
min = key[v];
min_index = v;
}
return min_index;
}
// A utility function to print the constructed MST stored in
// parent[]
void printMST(int parent[], int n, int graph[][]) {
System.out.println("Edge Weight");
for (int i = 1; i < V; i++)
System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]);
}
// Function to construct and print MST for a graph represented
// using adjacency matrix representation
void primMST(int graph[][]) {
// Array to store constructed MST
int parent[] = new int[V];
// Key values used to pick minimum weight edge in cut
int key[] = new int[V];
// To represent set of vertices not yet included in MST
Boolean mstSet[] = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
// Always include first 1st vertex in MST.
key[0] = 0; // Make key 0 so that this vertex is
// picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick thd minimum key vertex from the set of vertices
// not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = true;
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
for (int v = 0; v < V; v++)
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
// print the constructed MST
printMST(parent, V, graph);
}
public static void main(String[] args) {
/* Let us create the following graph
2 3
(0)--(1)--(2)
| / \ |
6| 8/ \5 |7
| / \ |
(3)-------(4)
9 */
PrimMST t = new PrimMST();
int graph[][] =
new int[][] {
{0, 2, 0, 6, 0}, {2, 0, 3, 8, 5}, {0, 3, 0, 0, 7}, {6, 8, 0, 0, 9}, {0, 5, 7, 9, 0},
};
// Print the solution
t.primMST(graph);
}
}

View File

@ -1,42 +0,0 @@
## Graph
Graph is a useful data structure for representing most of the real world problems involving a set of users/candidates/nodes and their relations. A Graph consists of two parameters :
```
V = a set of vertices
E = a set of edges
```
Each edge in `E` connects any two vertices from `V`. Based on the type of edge, graphs can be of two types:
1. **Directed**: The edges are directed in nature which means that when there is an edge from node `A` to `B`, it does not imply that there is an edge from `B` to `A`.
An example of directed edge graph the **follow** feature of social media. If you follow a celebrity, it doesn't imply that s/he follows you.
2. **Undirected**: The edges don't have any direction. So if `A` and `B` are connected, we can assume that there is edge from both `A` to `B` and `B` to `A`.
Example: Social media graph, where if two persons are friend, it implies that both are friend with each other.
### Representation
1. **Adjacency Lists**: Each node is represented as an entry and all the edges are represented as a list emerging from the corresponding node. So if vertex `1` has eadges to 2,3, and 6, the list corresponding to 1 will have 2,3 and 6 as entries. Consider the following graph.
```
0: 1-->2-->3
1: 0-->2
2: 0-->1
3: 0-->4
4: 3
```
It means there are edges from 0 to 1, 2 and 3; from 1 to 0 and 2 and so on.
2. **Adjacency Matrix**: The graph is represented as a matrix of size `|V| x |V|` and an entry 1 in cell `(i,j)` implies that there is an edge from i to j. 0 represents no edge.
The mtrix for the above graph:
```
0 1 2 3 4
0 0 1 1 1 0
1 1 0 1 0 0
2 1 1 0 0 0
3 1 0 0 0 1
4 0 0 0 1 0
```

View File

@ -1,145 +0,0 @@
package DataStructures.HashMap.Hashing;
public class HashMap {
private int hsize;
private LinkedList[] buckets;
public HashMap(int hsize) {
buckets = new LinkedList[hsize];
for (int i = 0; i < hsize; i++) {
buckets[i] = new LinkedList();
// Java requires explicit initialisaton of each object
}
this.hsize = hsize;
}
public int hashing(int key) {
int hash = key % hsize;
if (hash < 0) hash += hsize;
return hash;
}
public void insertHash(int key) {
int hash = hashing(key);
buckets[hash].insert(key);
}
public void deleteHash(int key) {
int hash = hashing(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());
}
}
public static class LinkedList {
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) {
if (n.getNext() == null) {
return n;
} else {
return findEnd(n.getNext());
}
}
public Node findKey(int key) {
if (!isEmpty()) {
return findKey(first, key);
} else {
System.out.println("List is empty");
return null;
}
}
private Node findKey(Node n, int key) {
if (n.getKey() == key) {
return n;
} else if (n.getNext() == null) {
System.out.println("Key not found");
return null;
} else {
return findKey(n.getNext(), key);
}
}
public void delete(int key) {
if (!isEmpty()) {
if (first.getKey() == key) {
first = null;
} else {
delete(first, key);
}
} else {
System.out.println("List is empty");
}
}
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());
}
}
}
public String display() {
return display(first);
}
private String display(Node n) {
if (n == null) {
return "null";
} else {
return n.getKey() + "->" + display(n.getNext());
}
}
public boolean isEmpty() {
return first == null;
}
}
public static class Node {
private Node next;
private int key;
public Node(int key) {
next = null;
this.key = key;
}
public Node getNext() {
return next;
}
public int getKey() {
return key;
}
public void setNext(Node next) {
this.next = next;
}
}
}

View File

@ -1,196 +0,0 @@
package DataStructures.HashMap.Hashing;
import java.util.*;
/**
* This class is an implementation of a hash table using linear probing It uses a dynamic array to
* lengthen the size of the hash table when load factor > .7
*/
public class HashMapLinearProbing {
private int hsize; // size of the hash table
private Integer[] buckets; // array representing the table
private Integer AVAILABLE;
private int size; // amount of elements in the hash table
/**
* Constructor initializes buckets array, hsize, and creates dummy object for AVAILABLE
*
* @param hsize the desired size of the hash map
*/
public HashMapLinearProbing(int hsize) {
this.buckets = new Integer[hsize];
this.hsize = hsize;
this.AVAILABLE = Integer.MIN_VALUE;
this.size = 0;
}
/**
* The Hash Function takes a given key and finds an index based on its data
*
* @param key the desired key to be converted
* @return int an index corresponding to the key
*/
public int hashing(int key) {
int hash = key % hsize;
if (hash < 0) {
hash += hsize;
}
return hash;
}
/**
* inserts the key into the hash map by wrapping it as an Integer object
*
* @param key the desired key to be inserted in the hash map
*/
public void insertHash(int key) {
Integer wrappedInt = key;
int hash = hashing(key);
if (isFull()) {
System.out.println("Hash table is full");
return;
}
for (int i = 0; i < hsize; i++) {
if (buckets[hash] == null || buckets[hash] == AVAILABLE) {
buckets[hash] = wrappedInt;
size++;
return;
}
if (hash + 1 < hsize) {
hash++;
} else {
hash = 0;
}
}
}
/**
* deletes a key from the hash map and adds an available placeholder
*
* @param key the desired key to be deleted
*/
public void deleteHash(int key) {
Integer wrappedInt = key;
int hash = hashing(key);
if (isEmpty()) {
System.out.println("Table is empty");
return;
}
for (int i = 0; i < hsize; i++) {
if (buckets[hash] != null && buckets[hash].equals(wrappedInt)) {
buckets[hash] = AVAILABLE;
size--;
return;
}
if (hash + 1 < hsize) {
hash++;
} else {
hash = 0;
}
}
System.out.println("Key " + key + " not found");
}
/** Displays the hash table line by line */
public void displayHashtable() {
for (int i = 0; i < hsize; i++) {
if (buckets[i] == null || buckets[i] == AVAILABLE) {
System.out.println("Bucket " + i + ": Empty");
} else {
System.out.println("Bucket " + i + ": " + buckets[i].toString());
}
}
}
/**
* Finds the index of location based on an inputed key
*
* @param key the desired key to be found
* @return int the index where the key is located
*/
public int findHash(int key) {
Integer wrappedInt = key;
int hash = hashing(key);
if (isEmpty()) {
System.out.println("Table is empty");
return -1;
}
for (int i = 0; i < hsize; i++) {
try {
if (buckets[hash].equals(wrappedInt)) {
buckets[hash] = AVAILABLE;
return hash;
}
} catch (Exception E) {
}
if (hash + 1 < hsize) {
hash++;
} else {
hash = 0;
}
}
System.out.println("Key " + key + " not found");
return -1;
}
private void lengthenTable() {
buckets = Arrays.copyOf(buckets, hsize * 2);
hsize *= 2;
System.out.println("Table size is now: " + hsize);
}
/**
* Checks the load factor of the hash table if greater than .7, automatically lengthens table to
* prevent further collisions
*/
public void checkLoadFactor() {
double factor = (double) size / hsize;
if (factor > .7) {
System.out.println("Load factor is " + factor + ", lengthening table");
lengthenTable();
} else {
System.out.println("Load factor is " + factor);
}
}
/**
* isFull returns true if the hash map is full and false if not full
*
* @return boolean is Empty
*/
public boolean isFull() {
boolean response = true;
for (int i = 0; i < hsize; i++) {
if (buckets[i] == null || buckets[i] == AVAILABLE) {
response = false;
break;
}
}
return response;
}
/**
* isEmpty returns true if the hash map is empty and false if not empty
*
* @return boolean is Empty
*/
public boolean isEmpty() {
boolean response = true;
for (int i = 0; i < hsize; i++) {
if (buckets[i] != null) {
response = false;
break;
}
}
return response;
}
}

View File

@ -1,64 +0,0 @@
package DataStructures.HashMap.Hashing;
/*
* this is algo which implies common mathematical set theory concept
* called intersection in which result is common values of both the sets
* here metaphor of sets is HashMap
Test Case:
Scanner scn=new Scanner(System.in);
int len =scn.nextInt();
int arr[]=new int[len];
int arr2[]=new int[len];
for(int i=0;i<2*len;i++) {
if(i<len)
arr[i]=scn.nextInt();
if(i>=len) {
arr2[i-len]=scn.nextInt();
}
}
System.out.println(Main(arr,arr2));
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Intersection {
public static ArrayList Main(int arr[],int arr2[]) {
HashMap<Integer,Integer> hmap=new HashMap<>();
HashMap<Integer,Integer> hmap2=new HashMap<>();
for(int i=0;i<arr.length;i++) {
if(hmap.containsKey(arr[i])) {
int val=hmap.get(arr[i]);
hmap.put(arr[i],val+1);
}else
hmap.put(arr[i],1);
}
ArrayList<Integer> res=new ArrayList<>();
for(int i=0;i<arr2.length;i++) {
if(hmap.containsKey(arr2[i])&&hmap.get(arr2[i])>0) {
int val=hmap.get(arr2[i]);
hmap.put(arr2[i],val-1);
res.add(arr2[i]);
}
}
return res;
}
public Intersection() {
}
}

View File

@ -1,51 +0,0 @@
package DataStructures.HashMap.Hashing;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int choice, key;
HashMap h = new HashMap(7);
Scanner In = new Scanner(System.in);
while (true) {
System.out.println("Enter your Choice :");
System.out.println("1. Add Key");
System.out.println("2. Delete Key");
System.out.println("3. Print Table");
System.out.println("4. Exit");
choice = In.nextInt();
switch (choice) {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4:
{
In.close();
return;
}
}
}
}
}

View File

@ -1,65 +0,0 @@
package DataStructures.HashMap.Hashing;
import java.util.Scanner;
public class MainLinearProbing {
public static void main(String[] args) {
int choice, key;
HashMapLinearProbing h = new HashMapLinearProbing(7);
Scanner In = new Scanner(System.in);
while (true) {
System.out.println("Enter your Choice :");
System.out.println("1. Add Key");
System.out.println("2. Delete Key");
System.out.println("3. Print Table");
System.out.println("4. Exit");
System.out.println("5. Search and print key index");
System.out.println("6. Check load factor");
choice = In.nextInt();
switch (choice) {
case 1:
{
System.out.println("Enter the Key: ");
key = In.nextInt();
h.insertHash(key);
break;
}
case 2:
{
System.out.println("Enter the Key delete: ");
key = In.nextInt();
h.deleteHash(key);
break;
}
case 3:
{
System.out.println("Print table");
h.displayHashtable();
break;
}
case 4:
{
In.close();
return;
}
case 5:
{
System.out.println("Enter the Key to find and print: ");
key = In.nextInt();
System.out.println("Key: " + key + " is at index: " + h.findHash(key));
break;
}
case 6:
{
h.checkLoadFactor();
break;
}
}
}
}
}

View File

@ -1,12 +0,0 @@
package DataStructures.Heaps;
/**
* @author Nicolas Renard Exception to be thrown if the getElement method is used on an empty heap.
*/
@SuppressWarnings("serial")
public class EmptyHeapException extends Exception {
public EmptyHeapException(String message) {
super(message);
}
}

View File

@ -1,69 +0,0 @@
import java.util.*;
public class GenericHeap <T extends Comparable <T> >{
ArrayList <T> data=new ArrayList<>();
HashMap<T,Integer> map=new HashMap<>();
public void add(T item) {
this.data.add(item);
map.put(item,this.data.size()-1);//
upHeapify(this.data.size()-1);
}
private void upHeapify(int ci) {
int pi=(ci-1)/2;
if(isLarger(this.data.get(ci),this.data.get(pi))>0) {
swap(pi,ci);
upHeapify(pi);
}
}
public void display() {
System.out.println(this.data);
}
public int size() {
return this.data.size();
}
public boolean isEmpty() {
return this.size()==0;
}
public T remove() {
this.swap(0,this.size()-1);
T rv=this.data.remove(this.size()-1);
downHeapify(0);
map.remove(rv);
return rv;
}
private void downHeapify(int pi) {
int lci=2*pi+1;
int rci=2*pi+2;
int mini=pi;
if(lci<this.size() && isLarger(this.data.get(lci),this.data.get(mini))>0) {
mini=lci;
}
if(rci<this.size() && isLarger(this.data.get(rci),this.data.get(mini))>0) {
mini=rci;
}
if(mini!=pi) {
this.swap(pi,mini);
downHeapify(mini);
}
}
public T get() {
return this.data.get(0);
}
//t has higher property then return +ve
private int isLarger(T t,T o) {
return t.compareTo(o);
}
private void swap(int i,int j) {
T ith=this.data.get(i);
T jth=this.data.get(j);
this.data.set(i,jth);
this.data.set(j,ith);
map.put(ith,j);
map.put(jth,i);
}
public void updatePriority(T item) {
int index=map.get(item);
//because we enter lesser value then old vale
upHeapify(index);
}
}

View File

@ -1,40 +0,0 @@
package DataStructures.Heaps;
/**
* Interface common to heap data structures.<br>
*
* <p>Heaps are tree-like data structures that allow storing elements in a specific way. Each node
* corresponds to an element and has one parent node (except for the root) and at most two children
* nodes. Every element contains a key, and those keys indicate how the tree shall be built. For
* instance, for a min-heap, the key of a node shall be greater than or equal to its parent's and
* lower than or equal to its children's (the opposite rule applies to a max-heap).
*
* <p>All heap-related operations (inserting or deleting an element, extracting the min or max) are
* performed in O(log n) time.
*
* @author Nicolas Renard
*/
public interface Heap {
/**
* @return the top element in the heap, the one with lowest key for min-heap or with the highest
* key for max-heap
* @throws EmptyHeapException if heap is empty
*/
HeapElement getElement() throws EmptyHeapException;
/**
* Inserts an element in the heap. Adds it to then end and toggle it until it finds its right
* position.
*
* @param element an instance of the HeapElement class.
*/
void insertElement(HeapElement element);
/**
* Delete an element in the heap.
*
* @param elementIndex int containing the position in the heap of the element to be deleted.
*/
void deleteElement(int elementIndex);
}

View File

@ -1,124 +0,0 @@
package DataStructures.Heaps;
/**
* Class for heap elements.<br>
*
* <p>A heap element contains two attributes: a key which will be used to build the tree (int or
* double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit to
* carry any information he/she likes. Be aware that the use of a mutable object might jeopardize
* the integrity of this information.
*
* @author Nicolas Renard
*/
public class HeapElement {
private final double key;
private final Object additionalInfo;
// Constructors
/**
* @param key : a number of primitive type 'double'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* @param key : a number of primitive type 'int'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(int key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* @param key : a number of object type 'Integer'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(Integer key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* @param key : a number of object type 'Double'
* @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry
* additional information of use for the user
*/
public HeapElement(Double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/** @param key : a number of primitive type 'double' */
public HeapElement(double key) {
this.key = key;
this.additionalInfo = null;
}
/** @param key : a number of primitive type 'int' */
public HeapElement(int key) {
this.key = key;
this.additionalInfo = null;
}
/** @param key : a number of object type 'Integer' */
public HeapElement(Integer key) {
this.key = key;
this.additionalInfo = null;
}
/** @param key : a number of object type 'Double' */
public HeapElement(Double key) {
this.key = key;
this.additionalInfo = null;
}
// Getters
/** @return the object containing the additional info provided by the user. */
public Object getInfo() {
return additionalInfo;
}
/** @return the key value of the element */
public double getKey() {
return key;
}
// Overridden object methods
public String toString() {
return "Key: " + key + " - " + additionalInfo.toString();
}
/**
* @param otherHeapElement
* @return true if the keys on both elements are identical and the additional info objects are
* identical.
*/
@Override
public boolean equals(Object o) {
if (o != null) {
if (!(o instanceof HeapElement)) return false;
HeapElement otherHeapElement = (HeapElement) o;
return (this.key == otherHeapElement.key)
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo));
}
return false;
}
@Override
public int hashCode() {
int result = 0;
result = 31 * result + (int) key;
result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0);
return result;
}
}

View File

@ -1,125 +0,0 @@
package DataStructures.Heaps;
import java.util.ArrayList;
import java.util.List;
/**
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal to
* its children's.
*
* @author Nicolas Renard
*/
public class MaxHeap implements Heap {
private final List<HeapElement> maxHeap;
public MaxHeap(List<HeapElement> listElements) {
maxHeap = new ArrayList<>();
for (HeapElement heapElement : listElements) {
if (heapElement != null) insertElement(heapElement);
else System.out.println("Null element. Not added to heap");
}
if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap.");
}
/**
* Get the element at a given index. The key for the list is equal to index value - 1
*
* @param elementIndex index
* @return heapElement
*/
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > maxHeap.size()))
throw new IndexOutOfBoundsException("Index out of heap range");
return maxHeap.get(elementIndex - 1);
}
// Get the key of the element at a given index
private double getElementKey(int elementIndex) {
return maxHeap.get(elementIndex - 1).getKey();
}
// Swaps two elements in the heap
private void swap(int index1, int index2) {
HeapElement temporaryElement = maxHeap.get(index1 - 1);
maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
maxHeap.set(index2 - 1, temporaryElement);
}
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) {
swap(elementIndex, (int) Math.floor(elementIndex / 2.0));
elementIndex = (int) Math.floor(elementIndex / 2.0);
}
}
// Toggle an element down to its right place as long as its key is higher
// than any of its children's
private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder =
(key < getElementKey(elementIndex * 2))
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
wrongOrder =
(key < getElementKey(elementIndex * 2))
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
}
}
private HeapElement extractMax() {
HeapElement result = maxHeap.get(0);
deleteElement(0);
return result;
}
@Override
public void insertElement(HeapElement element) {
maxHeap.add(element);
toggleUp(maxHeap.size());
}
@Override
public void deleteElement(int elementIndex) {
if (maxHeap.isEmpty())
try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0))
throw new IndexOutOfBoundsException("Index out of heap range");
// The last element in heap replaces the one to be deleted
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
maxHeap.remove(maxHeap.size());
// Shall the new element be moved up...
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0)))
toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2))))
toggleDown(elementIndex);
}
@Override
public HeapElement getElement() throws EmptyHeapException {
try {
return extractMax();
} catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}

View File

@ -1,120 +0,0 @@
package DataStructures.Heaps;
import java.util.ArrayList;
import java.util.List;
/**
* Heap tree where a node's key is higher than or equal to its parent's and lower than or equal to
* its children's.
*
* @author Nicolas Renard
*/
public class MinHeap implements Heap {
private final List<HeapElement> minHeap;
public MinHeap(List<HeapElement> listElements) {
minHeap = new ArrayList<>();
for (HeapElement heapElement : listElements) {
if (heapElement != null) insertElement(heapElement);
else System.out.println("Null element. Not added to heap");
}
if (minHeap.size() == 0) System.out.println("No element has been added, empty heap.");
}
// Get the element at a given index. The key for the list is equal to index value - 1
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > minHeap.size()))
throw new IndexOutOfBoundsException("Index out of heap range");
return minHeap.get(elementIndex - 1);
}
// Get the key of the element at a given index
private double getElementKey(int elementIndex) {
return minHeap.get(elementIndex - 1).getKey();
}
// Swaps two elements in the heap
private void swap(int index1, int index2) {
HeapElement temporaryElement = minHeap.get(index1 - 1);
minHeap.set(index1 - 1, minHeap.get(index2 - 1));
minHeap.set(index2 - 1, temporaryElement);
}
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) {
swap(elementIndex, (int) Math.floor(elementIndex / 2.0));
elementIndex = (int) Math.floor(elementIndex / 2.0);
}
}
// Toggle an element down to its right place as long as its key is higher
// than any of its children's
private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
boolean wrongOrder =
(key > getElementKey(elementIndex * 2))
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
wrongOrder =
(key > getElementKey(elementIndex * 2))
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
}
}
private HeapElement extractMin() {
HeapElement result = minHeap.get(0);
deleteElement(0);
return result;
}
@Override
public void insertElement(HeapElement element) {
minHeap.add(element);
toggleUp(minHeap.size());
}
@Override
public void deleteElement(int elementIndex) {
if (minHeap.isEmpty())
try {
throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) {
e.printStackTrace();
}
if ((elementIndex > minHeap.size()) || (elementIndex <= 0))
throw new IndexOutOfBoundsException("Index out of heap range");
// The last element in heap replaces the one to be deleted
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
minHeap.remove(minHeap.size());
// Shall the new element be moved up...
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0)))
toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2))))
toggleDown(elementIndex);
}
@Override
public HeapElement getElement() throws EmptyHeapException {
try {
return extractMin();
} catch (Exception e) {
throw new EmptyHeapException("Heap is empty. Error retrieving element");
}
}
}

View File

@ -1,125 +0,0 @@
package DataStructures.Heaps;
/**
* Minimum Priority Queue It is a part of heap data structure A heap is a specific tree based data
* structure in which all the nodes of tree are in a specific order. that is the children are
* arranged in some respect of their parents, can either be greater or less than the parent. This
* makes it a min priority queue or max priority queue.
*
* <p>
*
* <p>Functions: insert, delete, peek, isEmpty, print, heapSort, sink
*/
public class MinPriorityQueue {
private int[] heap;
private int capacity;
private int size;
// calss the constructor and initializes the capacity
MinPriorityQueue(int c) {
this.capacity = c;
this.size = 0;
this.heap = new int[c + 1];
}
// inserts the key at the end and rearranges it
// so that the binary heap is in appropriate order
public void insert(int key) {
if (this.isFull()) return;
this.heap[this.size + 1] = key;
int k = this.size + 1;
while (k > 1) {
if (this.heap[k] < this.heap[k / 2]) {
int temp = this.heap[k];
this.heap[k] = this.heap[k / 2];
this.heap[k / 2] = temp;
}
k = k / 2;
}
this.size++;
}
// returns the highest priority value
public int peek() {
return this.heap[1];
}
// returns boolean value whether the heap is empty or not
public boolean isEmpty() {
if (0 == this.size) return true;
return false;
}
// returns boolean value whether the heap is full or not
public boolean isFull() {
if (this.size == this.capacity) return true;
return false;
}
// prints the heap
public void print() {
for (int i = 1; i <= this.capacity; i++) System.out.print(this.heap[i] + " ");
System.out.println();
}
// heap sorting can be done by performing
// delete function to the number of times of the size of the heap
// it returns reverse sort because it is a min priority queue
public void heapSort() {
for (int i = 1; i < this.capacity; i++) this.delete();
}
// this function reorders the heap after every delete function
private void sink() {
int k = 1;
while (2 * k <= this.size || 2 * k + 1 <= this.size) {
int minIndex;
if (this.heap[2 * k] >= this.heap[k]) {
if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) {
break;
} else if (2 * k + 1 > this.size) {
break;
}
}
if (2 * k + 1 > this.size) {
minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k;
} else {
if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) {
minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1;
} else {
minIndex = k;
}
}
int temp = this.heap[k];
this.heap[k] = this.heap[minIndex];
this.heap[minIndex] = temp;
k = minIndex;
}
}
// deletes the highest priority value from the heap
public int delete() {
int min = this.heap[1];
this.heap[1] = this.heap[this.size];
this.heap[this.size] = min;
this.size--;
this.sink();
return min;
}
public static void main(String[] args) {
// testing
MinPriorityQueue q = new MinPriorityQueue(8);
q.insert(5);
q.insert(2);
q.insert(4);
q.insert(1);
q.insert(7);
q.insert(6);
q.insert(3);
q.insert(8);
q.print(); // [ 1, 2, 3, 5, 7, 6, 4, 8 ]
q.heapSort();
q.print(); // [ 8, 7, 6, 5, 4, 3, 2, 1 ]
}
}

View File

@ -1,103 +0,0 @@
package DataStructures.Lists;
public class CircleLinkedList<E> {
private static class Node<E> {
Node<E> next;
E value;
private Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
// For better O.O design this should be private allows for better black box design
private int size;
// this will point to dummy node;
private Node<E> head = null;
private Node<E> tail = null; // keeping a tail pointer to keep track of the end of list
// constructer for class.. here we will make a dummy node for circly linked list implementation
// with reduced error catching as our list will never be empty;
public CircleLinkedList() {
// creation of the dummy node
head = new Node<E>(null, head);
tail = head;
size = 0;
}
// getter for the size... needed because size is private.
public int getSize() {
return size;
}
// for the sake of simplistiy this class will only contain the append function or addLast other
// add functions can be implemented however this is the basses of them all really.
public void append(E value) {
if (value == null) {
// we do not want to add null elements to the list.
throw new NullPointerException("Cannot add null element to the list");
}
// head.next points to the last element;
if (tail == null){
tail = new Node<E>(value, head);
head.next = tail;
}
else{
tail.next = new Node<E>(value, head);
tail = tail.next;
}
size++;
}
// utility function for teraversing the list
public String toString(){
Node p = head.next;
String s = "[ ";
while(p!=head){
s += p.value;
s += " , ";
p = p.next;
}
return s + " ]";
}
public static void main(String args[]){
CircleLinkedList cl = new CircleLinkedList<Integer>();
cl.append(12);
System.out.println(cl);
cl.append(23);
System.out.println(cl);
cl.append(34);
System.out.println(cl);
cl.append(56);
System.out.println(cl);
cl.remove(3);
System.out.println(cl);
}
public E remove(int pos) {
if (pos > size || pos < 0) {
// catching errors
throw new IndexOutOfBoundsException("position cannot be greater than size or negative");
}
// we need to keep track of the element before the element we want to remove we can see why
// bellow.
Node<E> before = head;
for (int i = 1; i <= pos; i++) {
before = before.next;
}
Node<E> destroy = before.next;
E saved = destroy.value;
// assigning the next reference to the the element following the element we want to remove...
// the last element will be assigned to the head.
before.next = before.next.next;
// scrubbing
if(destroy == tail){
tail = before;
}
destroy = null;
size--;
return saved;
}
}

View File

@ -1,26 +0,0 @@
package DataStructures.Lists;
public class CountSinglyLinkedListRecursion extends SinglyLinkedList {
public static void main(String[] args) {
CountSinglyLinkedListRecursion list = new CountSinglyLinkedListRecursion();
for (int i = 1; i <= 5; ++i) {
list.insert(i);
}
assert list.count() == 5;
}
/**
* Calculate the count of the list manually using recursion.
*
* @param head head of the list.
* @return count of the list.
*/
private int countRecursion(Node head) {
return head == null ? 0 : 1 + countRecursion(head.next);
}
/** Returns the count of the list. */
@Override
public int count() {
return countRecursion(getHead());
}
}

View File

@ -1,95 +0,0 @@
package DataStructures.Lists;
import java.util.Scanner;
public class CreateAndDetectLoop {
/**
* Prints the linked list.
*
* @param head head node of the linked list
*/
static void printList(Node head) {
Node cur = head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
}
/**
* Creates a loop in the linked list.
* @see <a href="https://www.geeksforgeeks.org/make-loop-k-th-position-linked-list/">
* GeeksForGeeks: Make a loop at K-th position</a>
* @param head head node of the linked list
* @param k position of node where loop is to be created
*/
static void createLoop(Node head, int k) {
if (head == null)
return;
Node temp = head;
int count = 1;
while (count < k) { // Traverse the list till the kth node
temp = temp.next;
count++;
}
Node connectedPoint = temp;
while (temp.next != null) // Traverse remaining nodes
temp = temp.next;
temp.next = connectedPoint; // Connect last node to k-th element
}
/**
* Detects the presence of a loop in the linked list.
* @see <a href="https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare">
* Floyd's Cycle Detection Algorithm</a>
*
* @param head the head node of the linked list
*
* @return true if loop exists else false
*/
static boolean detectLoop(Node head) {
Node sptr = head;
Node fptr = head;
while (fptr != null && fptr.next != null) {
sptr = sptr.next;
fptr = fptr.next.next;
if (fptr == sptr)
return true;
}
return false;
}
public static void main(String[] args) {
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements to be inserted: ");
int n = sc.nextInt();
System.out.printf("Enter the %d elements: \n", n);
while (n-- > 0)
singlyLinkedList.insert(sc.nextInt());
System.out.print("Given list: ");
printList(singlyLinkedList.getHead());
System.out.println();
System.out.println("Enter the location to generate loop: ");
int k = sc.nextInt();
createLoop(singlyLinkedList.getHead(), k);
if (detectLoop(singlyLinkedList.getHead()))
System.out.println("Loop found");
else
System.out.println("No loop found");
sc.close();
}
}

View File

@ -1,195 +0,0 @@
package DataStructures.Lists;
import java.util.Objects;
/**
* This class implements a Cursor Linked List.
*
* A CursorLinkedList is an array version of a Linked List. Essentially you have an array of list nodes but instead of
* each node containing a pointer to the next item in the linked list, each node element in the array contains the index for the next node element.
*
*/
public class CursorLinkedList<T> {
private static class Node<T> {
T element;
int next;
Node(T element, int next) {
this.element = element;
this.next = next;
}
}
private final int os;
private int head;
private final Node<T>[] cursorSpace;
private int count;
private static final int CURSOR_SPACE_SIZE = 100;
{
// init at loading time
cursorSpace = new Node[CURSOR_SPACE_SIZE];
for (int i = 0; i < CURSOR_SPACE_SIZE; i++) {
cursorSpace[i] = new Node<>(null, i + 1);
}
cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0;
}
public CursorLinkedList() {
os = 0;
count = 0;
head = -1;
}
public void printList() {
if (head != -1) {
int start = head;
while (start != -1) {
T element = cursorSpace[start].element;
System.out.println(element.toString());
start = cursorSpace[start].next;
}
}
}
/**
* @return the logical index of the element within the list , not the actual index of the
* [cursorSpace] array
*/
public int indexOf(T element) {
Objects.requireNonNull(element);
Node<T> iterator = cursorSpace[head];
for (int i = 0; i < count; i++) {
if (iterator.element.equals(element)) {
return i;
}
iterator = cursorSpace[iterator.next];
}
return -1;
}
/**
* @param position , the logical index of the element , not the actual one within the
* [cursorSpace] array . this method should be used to get the index give by indexOf() method.
* @return
*/
public T get(int position) {
if (position >= 0 && position < count) {
int start = head;
int counter = 0;
while (start != -1) {
T element = cursorSpace[start].element;
if (counter == position) {
return element;
}
start = cursorSpace[start].next;
counter++;
}
}
return null;
}
public void removeByIndex(int index) {
if (index >= 0 && index < count) {
T element = get(index);
remove(element);
}
}
public void remove(T element) {
Objects.requireNonNull(element);
// case element is in the head
T temp_element = cursorSpace[head].element;
int temp_next = cursorSpace[head].next;
if (temp_element.equals(element)) {
free(head);
head = temp_next;
} else { // otherwise cases
int prev_index = head;
int current_index = cursorSpace[prev_index].next;
while (current_index != -1) {
T current_element = cursorSpace[current_index].element;
if (current_element.equals(element)) {
cursorSpace[prev_index].next = cursorSpace[current_index].next;
free(current_index);
break;
}
prev_index = current_index;
current_index = cursorSpace[prev_index].next;
}
}
count--;
}
private void free(int index) {
Node os_node = cursorSpace[os];
int os_next = os_node.next;
cursorSpace[os].next = index;
cursorSpace[index].element = null;
cursorSpace[index].next = os_next;
}
public void append(T element) {
Objects.requireNonNull(element);
int availableIndex = alloc();
cursorSpace[availableIndex].element = element;
if (head == -1) {
head = availableIndex;
}
int iterator = head;
while (cursorSpace[iterator].next != -1) {
iterator = cursorSpace[iterator].next;
}
cursorSpace[iterator].next = availableIndex;
cursorSpace[availableIndex].next = -1;
count++;
}
/** @return the index of the next available node */
private int alloc() {
// 1- get the index at which the os is pointing
int availableNodeIndex = cursorSpace[os].next;
if (availableNodeIndex == 0) {
throw new OutOfMemoryError();
}
// 2- make the os point to the next of the @var{availableNodeIndex}
int availableNext = cursorSpace[availableNodeIndex].next;
cursorSpace[os].next = availableNext;
// this to indicate an end of the list , helpful at testing since any err
// would throw an outOfBoundException
cursorSpace[availableNodeIndex].next = -1;
return availableNodeIndex;
}
}

View File

@ -1,307 +0,0 @@
package DataStructures.Lists;
/**
* This class implements a DoublyLinkedList. This is done using the classes LinkedList and Link.
*
* <p>A linked list is similar to an array, it holds values. However, links in a linked list do not
* have indexes. With a linked list you do not need to predetermine it's size as it grows and
* shrinks as it is edited. This is an example of a double ended, doubly linked list. Each link
* references the next link and the previous one.
*
* @author Unknown
*/
public class DoublyLinkedList {
/** Head refers to the front of the list */
private Link head;
/** Tail refers to the back of the list */
private Link tail;
/** Size refers to the number of elements present in the list */
private int size;
/** Default Constructor */
public DoublyLinkedList() {
head = null;
tail = null;
size = 0;
}
/**
* Constructs a list containing the elements of the array
*
* @param array the array whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public DoublyLinkedList(int[] array) {
if (array == null) throw new NullPointerException();
for (int i : array) {
insertTail(i);
}
size = array.length;
}
/**
* Insert an element at the head
*
* @param x Element to be inserted
*/
public void insertHead(int x) {
Link newLink = new Link(x); // Create a new link with a value attached to it
if (isEmpty()) // Set the first element added to be the tail
tail = newLink;
else head.previous = newLink; // newLink <-- currenthead(head)
newLink.next = head; // newLink <--> currenthead(head)
head = newLink; // newLink(head) <--> oldhead
++size;
}
/**
* Insert an element at the tail
*
* @param x Element to be inserted
*/
public void insertTail(int x) {
Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink -->
if (isEmpty()) { // Check if there are no elements in list then it adds first element
tail = newLink;
head = tail;
} else {
tail.next = newLink; // currentTail(tail) --> newLink -->
newLink.previous = tail; // currentTail(tail) <--> newLink -->
tail = newLink; // oldTail <--> newLink(tail) -->
}
++size;
}
/**
* Insert an element at the index
*
* @param x Element to be inserted
* @param index Index(from start) at which the element x to be inserted
*/
public void insertElementByIndex(int x, int index) {
if (index > size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
if (index == 0) {
insertHead(x);
} else {
if (index == size) {
insertTail(x);
} else {
Link newLink = new Link(x);
Link previousLink = head; //
for (int i = 1; i < index; i++) { // Loop to reach the index
previousLink = previousLink.next;
}
// previousLink is the Link at index - 1 from start
previousLink.next.previous = newLink;
newLink.next = previousLink.next;
newLink.previous = previousLink;
previousLink.next = newLink;
}
}
++size;
}
/**
* Delete the element at the head
*
* @return The new head
*/
public Link deleteHead() {
Link temp = head;
head = head.next; // oldHead <--> 2ndElement(head)
if (head == null) {
tail = null;
} else {
head.previous =
null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
}
--size;
return temp;
}
/**
* Delete the element at the tail
*
* @return The new tail
*/
public Link deleteTail() {
Link temp = tail;
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
if (tail == null) {
head = null;
} else {
tail.next = null; // 2ndLast(tail) --> null
}
--size;
return temp;
}
/**
* Delete the element from somewhere in the list
*
* @param x element to be deleted
* @return Link deleted
*/
public void delete(int x) {
Link current = head;
while (current.value != x) { // Find the position to delete
if (current != tail) {
current = current.next;
} else { // If we reach the tail and the element is still not found
throw new RuntimeException("The element to be deleted does not exist!");
}
}
if (current == head) deleteHead();
else if (current == tail) deleteTail();
else { // Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next; // 1 --> 3
current.next.previous = current.previous; // 1 <--> 3
}
--size;
}
/**
* Inserts element and reorders
*
* @param x Element to be added
*/
public void insertOrdered(int x) {
Link newLink = new Link(x);
Link current = head;
while (current != null && x > current.value) // Find the position to insert
current = current.next;
if (current == head) insertHead(x);
else if (current == null) insertTail(x);
else { // Before: 1 <--> 2(current) <--> 3
newLink.previous = current.previous; // 1 <-- newLink
current.previous.next = newLink; // 1 <--> newLink
newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
}
++size;
}
/**
* Deletes the passed node from the current list
*
* @param z Element to be deleted
*/
public void deleteNode(Link z) {
if (z.next == null) {
deleteTail();
} else if (z == head) {
deleteHead();
} else { // before <-- 1 <--> 2(z) <--> 3 -->
z.previous.next = z.next; // 1 --> 3
z.next.previous = z.previous; // 1 <--> 3
}
--size;
}
public static void removeDuplicates(DoublyLinkedList l) {
Link linkOne = l.head;
while (linkOne.next != null) { // list is present
Link linkTwo = linkOne.next; // second link for comparison
while (linkTwo.next != null) {
if (linkOne.value == linkTwo.value) // if there are duplicates values then
l.delete(linkTwo.value); // delete the link
linkTwo = linkTwo.next; // go to next link
}
linkOne = linkOne.next; // go to link link to iterate the whole list again
}
}
/** Clears List */
public void clearList() {
head = null;
tail = null;
size = 0;
}
/**
* Returns true if list is empty
*
* @return true if list is empty
*/
public boolean isEmpty() {
return (head == null);
}
/** Prints contents of the list */
public void display() { // Prints contents of the list
Link current = head;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println();
}
}
/**
* This class is used to implement the nodes of the linked list.
*
* @author Unknown
*/
class Link {
/** Value of node */
public int value;
/** This points to the link in front of the new link */
public Link next;
/** This points to the link behind the new link */
public Link previous;
/**
* Constructor
*
* @param value Value of node
*/
public Link(int value) {
this.value = value;
}
/** Displays the node */
public void displayLink() {
System.out.print(value + " ");
}
/**
* Main Method
*
* @param args Command line arguments
*/
public static void main(String args[]) {
DoublyLinkedList myList = new DoublyLinkedList();
myList.insertHead(13);
myList.insertHead(7);
myList.insertHead(10);
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.insertTail(11);
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
myList.deleteTail();
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.delete(7);
myList.display(); // <-- 10(head) <--> 13(tail) -->
myList.insertOrdered(23);
myList.insertOrdered(67);
myList.insertOrdered(3);
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
myList.insertElementByIndex(5, 1);
myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
myList.clearList();
myList.display();
myList.insertHead(20);
myList.display();
}
}

View File

@ -1,56 +0,0 @@
package DataStructures.Lists;
import java.util.ArrayList;
import java.util.List;
/** @author https://github.com/shellhub */
public class MergeSortedArrayList {
public static void main(String[] args) {
List<Integer> listA = new ArrayList<>();
List<Integer> listB = new ArrayList<>();
List<Integer> listC = new ArrayList<>();
/* init ListA and List B */
for (int i = 1; i <= 10; i += 2) {
listA.add(i); /* listA: [1, 3, 5, 7, 9] */
listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */
}
/* merge listA and listB to listC */
merge(listA, listB, listC);
System.out.println("listA: " + listA);
System.out.println("listB: " + listB);
System.out.println("listC: " + listC);
}
/**
* merge two sorted ArrayList
*
* @param listA the first list to merge
* @param listB the second list to merge
* @param listC the result list after merging
*/
public static void merge(List<Integer> listA, List<Integer> listB, List<Integer> listC) {
int pa = 0; /* the index of listA */
int pb = 0; /* the index of listB */
while (pa < listA.size() && pb < listB.size()) {
if (listA.get(pa) <= listB.get(pb)) {
listC.add(listA.get(pa++));
} else {
listC.add(listB.get(pb++));
}
}
/* copy left element of listA to listC */
while (pa < listA.size()) {
listC.add(listA.get(pa++));
}
/* copy left element of listB to listC */
while (pb < listB.size()) {
listC.add(listB.get(pb++));
}
}
}

View File

@ -1,51 +0,0 @@
package DataStructures.Lists;
public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
public static void main(String[] args) {
SinglyLinkedList listA = new SinglyLinkedList();
SinglyLinkedList listB = new SinglyLinkedList();
for (int i = 2; i <= 10; i += 2) {
listA.insert(i);
listB.insert(i - 1);
}
assert listA.toString().equals("2->4->6->8->10");
assert listB.toString().equals("1->3->5->7->9");
assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10");
}
/**
* Merge two sorted SingleLinkedList
*
* @param listA the first sorted list
* @param listB the second sored list
* @return merged sorted list
*/
public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) {
Node headA = listA.getHead();
Node headB = listB.getHead();
int size = listA.size() + listB.size();
Node head = new Node();
Node tail = head;
while (headA != null && headB != null) {
if (headA.value <= headB.value) {
tail.next = headA;
headA = headA.next;
} else {
tail.next = headB;
headB = headB.next;
}
tail = tail.next;
}
if (headA == null) {
tail.next = headB;
}
if (headB == null) {
tail.next = headA;
}
return new SinglyLinkedList(head.next, size);
}
}

View File

@ -1,54 +0,0 @@
package DataStructures.Lists;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
/** @author Arun Pandey (https://github.com/pandeyarun709) */
public class Merge_K_SortedLinkedlist {
/**
* This function merge K sorted LinkedList
*
* @param a array of LinkedList
* @param N size of array
* @return node
*/
Node mergeKList(Node[] a, int N) {
// Min Heap
PriorityQueue<Node> min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data));
// adding head of all linkedList in min heap
min.addAll(Arrays.asList(a).subList(0, N));
// Make new head among smallest heads in K linkedList
Node head = min.poll();
min.add(head.next);
Node curr = head;
// merging LinkedList
while (!min.isEmpty()) {
Node temp = min.poll();
curr.next = temp;
curr = temp;
// Add Node in min Heap only if temp.next is not null
if (temp.next != null) {
min.add(temp.next);
}
}
return head;
}
private class Node {
private int data;
private Node next;
public Node(int d) {
this.data = d;
next = null;
}
}
}

View File

@ -1,51 +0,0 @@
package DataStructures.Lists;
public class RemoveDuplicateNodes {
public Node deleteDuplicates(Node head) {
// sentinel
Node sentinel = new Node(0, head);
// predecessor = the last node
// before the sublist of duplicates
Node pred = sentinel;
while (head != null) {
// if it's a beginning of duplicates sublist
// skip all duplicates
if (head.next != null && head.value == head.next.value) {
// move till the end of duplicates sublist
while (head.next != null && head.value == head.next.value) {
head = head.next;
}
// skip all duplicates
pred.next = head.next;
// otherwise, move predecessor
} else {
pred = pred.next;
}
// move forward
head = head.next;
}
return sentinel.next;
}
public void print(Node head) {
Node temp = head;
while (temp != null && temp.next != null) {
System.out.print(temp.value + "->");
temp = temp.next;
}
if (temp != null) {
System.out.print(temp.value);
}
}
public static void main(String arg[]) {
RemoveDuplicateNodes instance = new RemoveDuplicateNodes();
Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
head = instance.deleteDuplicates(head);
instance.print(head);
}
}

View File

@ -1,31 +0,0 @@
package DataStructures.Lists;
public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
public static void main(String[] args) {
SearchSinglyLinkedListRecursion list = new SearchSinglyLinkedListRecursion();
for (int i = 1; i <= 10; ++i) {
list.insert(i);
}
for (int i = 1; i <= 10; ++i) {
assert list.search(i);
}
assert !list.search(-1) && !list.search(100);
}
/**
* Test if the value key is present in the list using recursion.
*
* @param node the head node.
* @param key the value to be searched.
* @return {@code true} if key is present in the list, otherwise {@code false}.
*/
private boolean searchRecursion(Node node, int key) {
return node != null && (node.value == key || searchRecursion(node.next, key));
}
@Override
public boolean search(int key) {
return searchRecursion(getHead(), key);
}
}

View File

@ -1,292 +0,0 @@
package DataStructures.Lists;
import java.util.StringJoiner;
/** https://en.wikipedia.org/wiki/Linked_list */
public class SinglyLinkedList {
/** Head refer to the front of the list */
private Node head;
/** Size of SinglyLinkedList */
private int size;
/** Init SinglyLinkedList */
public SinglyLinkedList() {
head = null;
size = 0;
}
/**
* Init SinglyLinkedList with specified head node and size
*
* @param head the head node of list
* @param size the size of list
*/
public SinglyLinkedList(Node head, int size) {
this.head = head;
this.size = size;
}
/**
* Inserts an element at the head of the list
*
* @param x element to be added
*/
public void insertHead(int x) {
insertNth(x, 0);
}
/**
* Insert an element at the tail of the list
*
* @param data element to be added
*/
public void insert(int data) {
insertNth(data, size);
}
/**
* Inserts a new node at a specified position of the list
*
* @param data data to be stored in a new node
* @param position position at which a new node is to be inserted
*/
public void insertNth(int data, int position) {
checkBounds(position, 0, size);
Node newNode = new Node(data);
if (head == null) {
/* the list is empty */
head = newNode;
size++;
return;
} else if (position == 0) {
/* insert at the head of the list */
newNode.next = head;
head = newNode;
size++;
return;
}
Node cur = head;
for (int i = 0; i < position - 1; ++i) {
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
size++;
}
/** Deletes a node at the head */
public void deleteHead() {
deleteNth(0);
}
/** Deletes an element at the tail */
public void delete() {
deleteNth(size - 1);
}
/** Deletes an element at Nth position */
public void deleteNth(int position) {
checkBounds(position, 0, size - 1);
if (position == 0) {
Node destroy = head;
head = head.next;
destroy = null; /* clear to let GC do its work */
size--;
return;
}
Node cur = head;
for (int i = 0; i < position - 1; ++i) {
cur = cur.next;
}
Node destroy = cur.next;
cur.next = cur.next.next;
destroy = null; // clear to let GC do its work
size--;
}
/**
* @param position to check position
* @param low low index
* @param high high index
* @throws IndexOutOfBoundsException if {@code position} not in range {@code low} to {@code high}
*/
public void checkBounds(int position, int low, int high) {
if (position > high || position < low) {
throw new IndexOutOfBoundsException(position + "");
}
}
/** Clear all nodes in the list */
public void clear() {
Node cur = head;
while (cur != null) {
Node prev = cur;
cur = cur.next;
prev = null; // clear to let GC do its work
}
head = null;
size = 0;
}
/**
* Checks if the list is empty
*
* @return {@code true} if list is empty, otherwise {@code false}.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the size of the linked list.
*
* @return the size of the list.
*/
public int size() {
return size;
}
/**
* Get head of the list.
*
* @return head of the list.
*/
public Node getHead() {
return head;
}
/**
* Calculate the count of the list manually
*
* @return count of the list
*/
public int count() {
int count = 0;
Node cur = head;
while (cur != null) {
cur = cur.next;
count++;
}
return count;
}
/**
* Test if the value key is present in the list.
*
* @param key the value to be searched.
* @return {@code true} if key is present in the list, otherwise {@code false}.
*/
public boolean search(int key) {
Node cur = head;
while (cur != null) {
if (cur.value == key) {
return true;
}
cur = cur.next;
}
return false;
}
/**
* Return element at special index.
*
* @param index given index of element
* @return element at special index.
*/
public int getNth(int index) {
checkBounds(index, 0, size - 1);
Node cur = head;
for (int i = 0; i < index; ++i) {
cur = cur.next;
}
return cur.value;
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner("->");
Node cur = head;
while (cur != null) {
joiner.add(cur.value + "");
cur = cur.next;
}
return joiner.toString();
}
/** Driver Code */
public static void main(String[] arg) {
SinglyLinkedList list = new SinglyLinkedList();
assert list.isEmpty();
assert list.size() == 0 && list.count() == 0;
assert list.toString().equals("");
/* Test insert function */
list.insertHead(5);
list.insertHead(7);
list.insertHead(10);
list.insert(3);
list.insertNth(1, 4);
assert list.toString().equals("10->7->5->3->1");
/* Test search function */
assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
/* Test get function */
assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
/* Test delete function */
list.deleteHead();
list.deleteNth(1);
list.delete();
assert list.toString().equals("7->3");
assert list.size == 2 && list.size() == list.count();
list.clear();
assert list.isEmpty();
try {
list.delete();
assert false; /* this should not happen */
} catch (Exception e) {
assert true; /* this should happen */
}
}
}
/**
* This class is the nodes of the SinglyLinked List. They consist of a value and a pointer to the
* node after them.
*/
class Node {
/** The value of the node */
int value;
/** Point to the next node */
Node next;
Node() {}
/**
* Constructor
*
* @param value Value to be put in the node
*/
Node(int value) {
this(value, null);
}
/**
* Constructor
*
* @param value Value to be put in the node
* @param next Reference to the next node
*/
Node(int value, Node next) {
this.value = value;
this.next = next;
}
}

View File

@ -1,117 +0,0 @@
package DataStructures.Queues;
//This program implements the concept of CircularQueue in Java
//Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer)
public class CircularQueue {
public static void main(String[] args) {
circularQueue cq= new circularQueue(5);
System.out.println(cq.isEmpty());
System.out.println(cq.isFull());
cq.enQueue(1);
cq.enQueue(2);
cq.enQueue(3);
cq.enQueue(4);
cq.enQueue(5);
System.out.println(cq.deQueue());
System.out.println(cq.deQueue());
System.out.println(cq.deQueue());
System.out.println(cq.deQueue());
System.out.println(cq.deQueue());
System.out.println(cq.isFull());
System.out.println(cq.isEmpty());
cq.enQueue(6);
cq.enQueue(7);
cq.enQueue(8);
System.out.println(cq.peek());
System.out.println(cq.peek());
cq.deleteQueue();
}
}
class circularQueue{
int[] arr;
int topOfQueue;
int beginningOfQueue;
int size;
public circularQueue(int size){
arr=new int[size];
topOfQueue=-1;
beginningOfQueue=-1;
this.size=size;
}
public boolean isEmpty(){
if(beginningOfQueue==-1){
return true;
}else{
return false;
}
}
public boolean isFull(){
if(topOfQueue+1==beginningOfQueue){
return true;
}else if(topOfQueue==size-1 && beginningOfQueue==0){
return true;
}else{
return false;
}
}
public void enQueue(int value){
if(isFull()){
System.out.println("The Queue is full!");
}
else if(isEmpty()) {
beginningOfQueue=0;
topOfQueue++;
arr[topOfQueue]=value;
System.out.println(value+" has been successfully inserted!");
}else{
if(topOfQueue+1==size){
topOfQueue=0;
}else{
topOfQueue++;
}
arr[topOfQueue]=value;
System.out.println(value+" has been successfully inserted!");
}
}
public int deQueue(){
if(isEmpty()){
System.out.println("The Queue is Empty!");
return -1;
}else{
int res= arr[beginningOfQueue];
arr[beginningOfQueue]=Integer.MIN_VALUE;
if(beginningOfQueue==topOfQueue){
beginningOfQueue=topOfQueue=-1;
}else if(beginningOfQueue+1==size){
beginningOfQueue=0;
}else{
beginningOfQueue++;
}
return res;
}
}
public int peek(){
if(isEmpty()){
System.out.println("The Queue is Empty!");
return -1;
}else{
return arr[beginningOfQueue];
}
}
public void deleteQueue(){
arr=null;
System.out.println("The Queue is deleted!");
}
}

View File

@ -1,83 +0,0 @@
package DataStructures.Queues;
import java.util.ArrayList;
/**
* This class implements a GenericArrayListQueue.
*
* A GenericArrayListQueue data structure functions the same as any specific-typed queue. The
* GenericArrayListQueue holds elements of types to-be-specified at runtime. The elements that are
* added first are the first to be removed (FIFO). New elements are added to the back/rear of the
* queue.
*/
public class GenericArrayListQueue<T> {
/** The generic ArrayList for the queue T is the generic element */
ArrayList<T> _queue = new ArrayList<>();
/**
* Checks if the queue has elements (not empty).
*
* @return True if the queue has elements. False otherwise.
*/
private boolean hasElements() {
return !_queue.isEmpty();
}
/**
* Checks what's at the front of the queue.
*
* @return If queue is not empty, element at the front of the queue. Otherwise, null
*/
public T peek() {
T result = null;
if (this.hasElements()) {
result = _queue.get(0);
}
return result;
}
/**
* Inserts an element of type T to the queue.
*
* @param element of type T to be added
* @return True if the element was added successfully
*/
public boolean add(T element) {
return _queue.add(element);
}
/**
* Retrieve what's at the front of the queue
*
* @return If queue is not empty, element retrieved. Otherwise, null
*/
public T pull() {
T result = null;
if (this.hasElements()) {
result = _queue.remove(0);
}
return result;
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<>();
System.out.println("Running...");
assert queue.peek() == null;
assert queue.pull() == null;
assert queue.add(1);
assert queue.peek() == 1;
assert queue.add(2);
assert queue.peek() == 1;
assert queue.pull() == 1;
assert queue.peek() == 2;
assert queue.pull() == 2;
assert queue.peek() == null;
assert queue.pull() == null;
System.out.println("Finished.");
}
}

View File

@ -1,159 +0,0 @@
package DataStructures.Queues;
import java.util.NoSuchElementException;
public class LinkedQueue {
class Node {
int data;
Node next;
public Node() {
this(0);
}
public Node(int data) {
this(data, null);
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
/** Front of Queue */
private Node front;
/** Rear of Queue */
private Node rear;
/** Size of Queue */
private int size;
/** Init LinkedQueue */
public LinkedQueue() {
front = rear = new Node();
}
/**
* Check if queue is empty
*
* @return true if queue is empty, otherwise false
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Add element to rear of queue
*
* @param data insert value
* @return true if add successfully
*/
public boolean enqueue(int data) {
Node newNode = new Node(data);
rear.next = newNode;
rear = newNode; /* make rear point at last node */
size++;
return true;
}
/**
* Remove element at the front of queue
*
* @return element at the front of queue
*/
public int dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
Node destroy = front.next;
int retValue = destroy.data;
front.next = front.next.next;
destroy = null; /* clear let GC do it's work */
size--;
if (isEmpty()) {
front = rear;
}
return retValue;
}
/**
* Peek element at the front of queue without removing
*
* @return element at the front
*/
public int peekFront() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
return front.next.data;
}
/**
* Peek element at the rear of queue without removing
*
* @return element at the front
*/
public int peekRear() {
if (isEmpty()) {
throw new NoSuchElementException("queue is empty");
}
return rear.data;
}
/**
* Return size of queue
*
* @return size of queue
*/
public int size() {
return size;
}
/** Clear all nodes in queue */
public void clear() {
while (!isEmpty()) {
dequeue();
}
}
@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
Node cur = front.next;
builder.append("[");
while (cur != null) {
builder.append(cur.data).append(", ");
cur = cur.next;
}
builder.replace(builder.length() - 2, builder.length(), "]");
return builder.toString();
}
/* Driver Code */
public static void main(String[] args) {
LinkedQueue queue = new LinkedQueue();
assert queue.isEmpty();
queue.enqueue(1); /* 1 */
queue.enqueue(2); /* 1 2 */
queue.enqueue(3); /* 1 2 3 */
System.out.println(queue); /* [1, 2, 3] */
assert queue.size() == 3;
assert queue.dequeue() == 1;
assert queue.peekFront() == 2;
assert queue.peekRear() == 3;
queue.clear();
assert queue.isEmpty();
System.out.println(queue); /* [] */
}
}

View File

@ -1,120 +0,0 @@
package DataStructures.Queues;
/**
* This class implements a PriorityQueue.
*
* <p>A priority queue adds elements into positions based on their priority. So the most important
* elements are placed at the front/on the top. In this example I give numbers that are bigger, a
* higher priority. Queues in theory have no fixed size but when using an array implementation it
* does.
*/
class PriorityQueue {
/** The max size of the queue */
private int maxSize;
/** The array for the queue */
private int[] queueArray;
/** How many items are in the queue */
private int nItems;
/**
* Constructor
*
* @param size Size of the queue
*/
public PriorityQueue(int size) {
maxSize = size;
queueArray = new int[size];
nItems = 0;
}
/**
* Inserts an element in it's appropriate place
*
* @param value Value to be inserted
*/
public void insert(int value) {
if (isFull()) {
throw new RuntimeException("Queue is full");
} else {
int j = nItems - 1; // index of last element
while (j >= 0 && queueArray[j] > value) {
queueArray[j + 1] = queueArray[j]; // Shifts every element up to make room for insertion
j--;
}
queueArray[j + 1] = value; // Once the correct position is found the value is inserted
nItems++;
}
}
/**
* Remove the element from the front of the queue
*
* @return The element removed
*/
public int remove() {
return queueArray[--nItems];
}
/**
* Checks what's at the front of the queue
*
* @return element at the front of the queue
*/
public int peek() {
return queueArray[nItems - 1];
}
/**
* Returns true if the queue is empty
*
* @return true if the queue is empty
*/
public boolean isEmpty() {
return (nItems == 0);
}
/**
* Returns true if the queue is full
*
* @return true if the queue is full
*/
public boolean isFull() {
return (nItems == maxSize);
}
/**
* Returns the number of elements in the queue
*
* @return number of elements in the queue
*/
public int getSize() {
return nItems;
}
}
/**
* This class implements the PriorityQueue class above.
*
* @author Unknown
*/
public class PriorityQueues {
/**
* Main method
*
* @param args Command Line Arguments
*/
public static void main(String[] args) {
PriorityQueue myQueue = new PriorityQueue(4);
myQueue.insert(10);
myQueue.insert(2);
myQueue.insert(5);
myQueue.insert(3);
// [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top
for (int i = 3; i >= 0; i--)
System.out.print(
myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2]
// As you can see, a Priority Queue can be used as a sorting algotithm
}
}

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