Add automatic linter (#4214)

This commit is contained in:
acbin 2023-06-09 20:05:14 +08:00 committed by GitHub
parent 00282efd8b
commit 415a04ea7f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
188 changed files with 661 additions and 1133 deletions

135
.clang-format Normal file
View File

@ -0,0 +1,135 @@
---
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
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
...

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@v3
- uses: DoozyX/clang-format-lint-action@v0.13
with:
source: './src'
extensions: 'java'
clangFormatVersion: 12

View File

@ -1,30 +0,0 @@
name: Prettify
on:
push:
paths:
- 'src/**'
- '**.yml'
- '**.xml'
- '**.Dockerfile'
pull_request:
paths:
- 'src/**'
- '**.yml'
- '**.xml'
- '**.Dockerfile'
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

@ -16,6 +16,7 @@
* [NQueens](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/NQueens.java) * [NQueens](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/NQueens.java)
* [Permutation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Permutation.java) * [Permutation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Permutation.java)
* [PowerSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/PowerSum.java) * [PowerSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/PowerSum.java)
* [WordSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/WordSearch.java)
* ciphers * ciphers
* a5 * a5
* [A5Cipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java) * [A5Cipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java)
@ -53,6 +54,7 @@
* [HexaDecimalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java) * [HexaDecimalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java)
* [HexToOct](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexToOct.java) * [HexToOct](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/HexToOct.java)
* [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java) * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/IntegerToRoman.java)
* [OctalToBinary](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToBinary.java)
* [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java) * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java)
* [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java) * [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java)
* [RgbHsvConversion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java) * [RgbHsvConversion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java)
@ -227,6 +229,7 @@
* [NewManShanksPrime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java) * [NewManShanksPrime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java)
* [OptimalJobScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java) * [OptimalJobScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java)
* [PalindromicPartitioning](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java) * [PalindromicPartitioning](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java)
* [PartitionProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java)
* [RegexMatching](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java) * [RegexMatching](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java)
* [RodCutting](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java) * [RodCutting](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java)
* [ShortestCommonSupersequenceLength](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java) * [ShortestCommonSupersequenceLength](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java)
@ -351,7 +354,6 @@
* [Sort012D](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sort012D.java) * [Sort012D](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sort012D.java)
* [Sparcity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparcity.java) * [Sparcity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparcity.java)
* [ThreeSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java) * [ThreeSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java)
* [TwoSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/TwoSumProblem.java)
* [WordBoggle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/WordBoggle.java) * [WordBoggle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/WordBoggle.java)
* others * others
* [ArrayLeftRotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java) * [ArrayLeftRotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/ArrayLeftRotation.java)
@ -410,6 +412,7 @@
* [Verhoeff](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Verhoeff.java) * [Verhoeff](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Verhoeff.java)
* scheduling * scheduling
* [FCFSScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java) * [FCFSScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java)
* [RRScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/RRScheduling.java)
* [SJFScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java) * [SJFScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java)
* searches * searches
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/BinarySearch.java) * [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/BinarySearch.java)
@ -521,6 +524,7 @@
* [MazeRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java) * [MazeRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java)
* [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java) * [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java)
* [PowerSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java) * [PowerSumTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java)
* [WordSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java)
* ciphers * ciphers
* a5 * a5
* [LFSRTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java) * [LFSRTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java)
@ -541,6 +545,7 @@
* [HexaDecimalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java) * [HexaDecimalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java)
* [HexToOctTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexToOctTest.java) * [HexToOctTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/HexToOctTest.java)
* [IntegerToRomanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java) * [IntegerToRomanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/IntegerToRomanTest.java)
* [OctalToBinaryTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java)
* [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java) * [OctalToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToDecimalTest.java)
* [OctalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java) * [OctalToHexadecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/OctalToHexadecimalTest.java)
* [RomanToIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java) * [RomanToIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java)
@ -578,9 +583,11 @@
* [BinaryTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java) * [BinaryTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java)
* [BSTFromSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java) * [BSTFromSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java)
* [BSTIterativeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java) * [BSTIterativeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java)
* [BSTRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java)
* [CeilInBinarySearchTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java) * [CeilInBinarySearchTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java)
* [CheckBinaryTreeIsValidBSTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java) * [CheckBinaryTreeIsValidBSTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java)
* [CheckTreeIsSymmetricTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java) * [CheckTreeIsSymmetricTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java)
* [CreateBinaryTreeFromInorderPreorderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java)
* [InorderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java) * [InorderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java)
* [KDTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java) * [KDTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java)
* [LazySegmentTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java) * [LazySegmentTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java)
@ -601,6 +608,7 @@
* [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java) * [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java)
* [LevenshteinDistanceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java) * [LevenshteinDistanceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java)
* [OptimalJobSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java) * [OptimalJobSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java)
* [PartitionProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java)
* [SubsetCountTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java) * [SubsetCountTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java)
* geometry * geometry
* [GrahamScanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java) * [GrahamScanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java)
@ -644,6 +652,7 @@
* [LucasSeriesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java) * [LucasSeriesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java)
* [MedianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MedianTest.java) * [MedianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MedianTest.java)
* [MobiusFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java) * [MobiusFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java)
* [NthUglyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java)
* [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java) * [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java)
* [PerfectCubeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PerfectCubeTest.java) * [PerfectCubeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PerfectCubeTest.java)
* [PerfectNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java) * [PerfectNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java)
@ -654,6 +663,7 @@
* [PrimeFactorizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java) * [PrimeFactorizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java)
* [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java) * [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java)
* [PythagoreanTripleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java) * [PythagoreanTripleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java)
* [ReverseNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java)
* [SquareFreeIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java) * [SquareFreeIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java)
* [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java) * [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java)
* [SquareRootWithNewtonRaphsonTestMethod](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java) * [SquareRootWithNewtonRaphsonTestMethod](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java)
@ -674,20 +684,24 @@
* [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java) * [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java)
* [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java) * [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
* [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java) * [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java)
* [CountWordsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountWordsTest.java)
* [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java) * [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java)
* [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java) * [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java)
* [FirstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java) * [FirstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java)
* [KadaneAlogrithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java) * [KadaneAlogrithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java)
* [LineSweepTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LineSweepTest.java) * [LineSweepTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LineSweepTest.java)
* [LinkListSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkListSortTest.java) * [LinkListSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkListSortTest.java)
* [LowestBasePalindromeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java)
* [NewManShanksPrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java) * [NewManShanksPrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java)
* [NextFitTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NextFitTest.java) * [NextFitTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NextFitTest.java)
* [PasswordGenTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/PasswordGenTest.java) * [PasswordGenTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/PasswordGenTest.java)
* [TestPrintMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java) * [TestPrintMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java)
* [TwoPointersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TwoPointersTest.java)
* [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/UniquePathsTests.java) * [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/UniquePathsTests.java)
* [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java) * [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java)
* scheduling * scheduling
* [FCFSSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java) * [FCFSSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java)
* [RRSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java)
* [SJFSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java) * [SJFSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java)
* searches * searches
* [BinarySearch2dArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java) * [BinarySearch2dArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java)

View File

@ -47,8 +47,7 @@ public class IIRFilter {
*/ */
public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException { public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
if (aCoeffs.length != order) { if (aCoeffs.length != order) {
throw new IllegalArgumentException( throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length);
"aCoeffs must be of size " + order + ", got " + aCoeffs.length);
} }
if (aCoeffs[0] == 0.0) { if (aCoeffs[0] == 0.0) {
@ -56,8 +55,7 @@ public class IIRFilter {
} }
if (bCoeffs.length != order) { if (bCoeffs.length != order) {
throw new IllegalArgumentException( throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length);
"bCoeffs must be of size " + order + ", got " + bCoeffs.length);
} }
for (int i = 0; i <= order; i++) { for (int i = 0; i <= order; i++) {

View File

@ -58,8 +58,7 @@ public class AllPathsFromSourceToTarget {
// A recursive function to print all paths from 'u' to 'd'. // A recursive function to print all paths from 'u' to 'd'.
// isVisited[] keeps track of vertices in current path. // isVisited[] keeps track of vertices in current path.
// localPathList<> stores actual vertices in the current path // localPathList<> stores actual vertices in the current path
private void storeAllPathsUtil( private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) {
Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) {
if (u.equals(d)) { if (u.equals(d)) {
nm.add(new ArrayList<>(localPathList)); nm.add(new ArrayList<>(localPathList));
@ -87,8 +86,7 @@ public class AllPathsFromSourceToTarget {
} }
// Driver program // Driver program
public static List<List<Integer>> allPathsFromSourceToTarget( public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) {
int vertices, int[][] a, int source, int destination) {
// Create a sample graph // Create a sample graph
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices); AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {

View File

@ -37,8 +37,7 @@ public class Combination {
* @param result the list contains all combination. * @param result the list contains all combination.
* @param <T> the type of elements in the array. * @param <T> the type of elements in the array.
*/ */
private static <T> void backtracking( private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
if (index + length - currSet.size() > arr.length) return; if (index + length - currSet.size() > arr.length) return;
if (length - 1 == currSet.size()) { if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) { for (int i = index; i < arr.length; i++) {

View File

@ -47,8 +47,7 @@ public class NQueens {
List<List<String>> arrangements = new ArrayList<List<String>>(); List<List<String>> arrangements = new ArrayList<List<String>>();
getSolution(queens, arrangements, new int[queens], 0); getSolution(queens, arrangements, new int[queens], 0);
if (arrangements.isEmpty()) { if (arrangements.isEmpty()) {
System.out.println("There is no way to place " + queens + " queens on board of size " System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens);
+ queens + "x" + queens);
} else { } else {
System.out.println("Arrangement for placing " + queens + " queens"); System.out.println("Arrangement for placing " + queens + " queens");
} }
@ -66,8 +65,7 @@ public class NQueens {
* @param columns: columns[i] = rowId where queen is placed in ith column. * @param columns: columns[i] = rowId where queen is placed in ith column.
* @param columnIndex: This is the column in which queen is being placed * @param columnIndex: This is the column in which queen is being placed
*/ */
private static void getSolution( private static void getSolution(int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) {
int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) {
if (columnIndex == boardSize) { if (columnIndex == boardSize) {
// this means that all queens have been placed // this means that all queens have been placed
List<String> sol = new ArrayList<String>(); List<String> sol = new ArrayList<String>();

View File

@ -2413,8 +2413,7 @@ public class AES {
} }
// replace bytes in original string // replace bytes in original string
rBytes = new StringBuilder( rBytes = new StringBuilder(rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
} }
// t = new BigInteger(rBytes, 16); // t = new BigInteger(rBytes, 16);
@ -2453,12 +2452,8 @@ public class AES {
// split previous key into 8-bit segments // split previous key into 8-bit segments
BigInteger[] prevKey = { BigInteger[] prevKey = {
roundKeys[i - 1].remainder(new BigInteger("100000000", 16)), roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
roundKeys[i - 1] roundKeys[i - 1].remainder(new BigInteger("10000000000000000", 16)).divide(new BigInteger("100000000", 16)),
.remainder(new BigInteger("10000000000000000", 16)) roundKeys[i - 1].remainder(new BigInteger("1000000000000000000000000", 16)).divide(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)), roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
}; };
@ -2677,12 +2672,9 @@ public class AES {
}; };
outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]]; outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]];
outputCells[i * 4 + 1] outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
= 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 + 2] outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
= 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); return mergeCellsIntoBlock(outputCells);
} }

View File

@ -57,9 +57,7 @@ public class AESEncryption {
* @throws BadPaddingException (from Cipher) * @throws BadPaddingException (from Cipher)
* @throws IllegalBlockSizeException (from Cipher) * @throws IllegalBlockSizeException (from Cipher)
*/ */
public static byte[] encryptText(String plainText, SecretKey secKey) public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7 // AES defaults to AES/ECB/PKCS5Padding in Java 7
aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey); aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
@ -71,9 +69,7 @@ public class AESEncryption {
* *
* @return plainText * @return plainText
*/ */
public static String decryptText(byte[] byteCipherText, SecretKey secKey) public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7 // AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding"); Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV()); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());

View File

@ -1120,8 +1120,7 @@ public class Blowfish {
a = hexToBin(a); a = hexToBin(a);
b = hexToBin(b); b = hexToBin(b);
String ans = ""; String ans = "";
for (int i = 0; i < a.length(); i++) for (int i = 0; i < a.length(); i++) ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
ans = binToHex(ans); ans = binToHex(ans);
return ans; return ans;
} }

View File

@ -30,12 +30,10 @@ public class Caesar {
if (isCapitalLatinLetter(current)) { if (isCapitalLatinLetter(current)) {
current += shift; current += shift;
encoded.append(( encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) { } else if (isSmallLatinLetter(current)) {
current += shift; current += shift;
encoded.append(( encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else { } else {
encoded.append(current); encoded.append(current);
} }
@ -59,12 +57,10 @@ public class Caesar {
char current = encryptedMessage.charAt(i); char current = encryptedMessage.charAt(i);
if (isCapitalLatinLetter(current)) { if (isCapitalLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append(( decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) { } else if (isSmallLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append(( decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else { } else {
decoded.append(current); decoded.append(current);
} }

View File

@ -51,8 +51,7 @@ public class ColumnarTranspositionCipher {
*/ */
public static String encrpyter(String word, String keyword, String abecedarium) { public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.keyword = keyword;
ColumnarTranspositionCipher.abecedarium ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
= Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder(); StringBuilder wordEncrypted = new StringBuilder();
@ -164,8 +163,7 @@ public class ColumnarTranspositionCipher {
return columnArray; return columnArray;
} }
private static void switchColumns( private static void switchColumns(Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
for (int i = 0; i < table.length; i++) { for (int i = 0; i < table.length; i++) {
table[i][secondColumnIndex] = table[i][firstColumnIndex]; table[i][secondColumnIndex] = table[i][firstColumnIndex];
table[i][firstColumnIndex] = columnToSwitch[i]; table[i][firstColumnIndex] = columnToSwitch[i];
@ -199,8 +197,7 @@ public class ColumnarTranspositionCipher {
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
System.out.println("### Example of Columnar Transposition Cipher ###\n"); System.out.println("### Example of Columnar Transposition Cipher ###\n");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted); System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
System.out.println("Word encrypted ->>> " System.out.println("Word encrypted ->>> " + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()); System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###"); System.out.println("\n### Encrypted Table ###");
showTable(); showTable();

View File

@ -13,8 +13,7 @@ public class DES {
private void sanitize(String key) { private void sanitize(String key) {
int length = key.length(); int length = key.length();
if (length != 64) { if (length != 64) {
throw new IllegalArgumentException( throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string");
"DES key must be supplied as a 64 character binary string");
} }
} }
@ -34,79 +33,44 @@ public class DES {
} }
// Permutation table to convert initial 64 bit key to 56 bit key // Permutation table to convert initial 64 bit key to 56 bit key
private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30,
22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
// Lookup table used to shift the initial key, in order to generate the subkeys // Lookup table used to shift the initial key, in order to generate the subkeys
private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1}; private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
// Table to convert the 56 bit subkeys to 48 bit subkeys // Table to convert the 56 bit subkeys to 48 bit subkeys
private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32};
16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34,
53, 46, 42, 50, 36, 29, 32};
// Initial permutatation of each 64 but message block // Initial permutatation of each 64 but message block
private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51,
43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
// Expansion table to convert right half of message blocks from 32 bits to 48 bits // Expansion table to convert right half of message blocks from 32 bits to 48 bits
private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1};
13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1};
// The eight substitution boxes are defined below // The eight substitution boxes are defined below
private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8}; private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
// Permutation table, used in the feistel function post s-box usage // Permutation table, used in the feistel function post s-box usage
static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
// Table used for final inversion of the message box after 16 rounds of Feistel Function // Table used for final inversion of the message box after 16 rounds of Feistel Function
static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3,
43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
private String[] getSubkeys(String originalKey) { private String[] getSubkeys(String originalKey) {
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1 StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
@ -182,8 +146,7 @@ public class DES {
for (i = 0; i < 48; i += 6) { for (i = 0; i < 48; i += 6) {
String block = mixedKey.substring(i, i + 6); String block = mixedKey.substring(i, i + 6);
int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48); int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
+ (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4); String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
substitutedString.append(substitutedBlock); substitutedString.append(substitutedBlock);
} }
@ -262,8 +225,7 @@ public class DES {
StringBuilder decryptedMessage = new StringBuilder(); StringBuilder decryptedMessage = new StringBuilder();
int l = message.length(), i, j; int l = message.length(), i, j;
if (l % 64 != 0) { if (l % 64 != 0) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
"Encrypted message should be a multiple of 64 characters in length");
} }
for (i = 0; i < l; i += 64) { for (i = 0; i < l; i += 64) {
String block = message.substring(i, i + 64); String block = message.substring(i, i + 64);
@ -274,7 +236,6 @@ public class DES {
} }
decryptedMessage.append(new String(res)); decryptedMessage.append(new String(res));
} }
return decryptedMessage.toString().replace( return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
"\0", ""); // Get rid of the null bytes used for padding
} }
} }

View File

@ -34,8 +34,7 @@ public class RSA {
* @return plain message * @return plain message
*/ */
public synchronized String decrypt(String encryptedMessage) { public synchronized String decrypt(String encryptedMessage) {
return new String( return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
(new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
} }
/** /**

View File

@ -6,8 +6,7 @@ import java.util.BitSet;
public class A5Cipher { public class A5Cipher {
private final A5KeyStreamGenerator keyStreamGenerator; private final A5KeyStreamGenerator keyStreamGenerator;
private static final int KEY_STREAM_LENGTH private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
= 228; // 28.5 bytes so we need to pad bytes or something
public A5Cipher(BitSet sessionKey, BitSet frameCounter) { public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
keyStreamGenerator = new A5KeyStreamGenerator(); keyStreamGenerator = new A5KeyStreamGenerator();

View File

@ -9,8 +9,7 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
private BitSet frameCounter; private BitSet frameCounter;
private BitSet sessionKey; private BitSet sessionKey;
private static final int INITIAL_CLOCKING_CYCLES = 100; private static final int INITIAL_CLOCKING_CYCLES = 100;
private static final int KEY_STREAM_LENGTH private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
= 228; // 28.5 bytes so we need to pad bytes or something
@Override @Override
public void initialize(BitSet sessionKey, BitSet frameCounter) { public void initialize(BitSet sessionKey, BitSet frameCounter) {

View File

@ -29,8 +29,7 @@ public abstract class CompositeLFSR implements BaseLFSR {
bitCount.put(false, 0); bitCount.put(false, 0);
bitCount.put(true, 0); bitCount.put(true, 0);
registers.forEach( registers.forEach(lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
return bitCount.get(false) <= bitCount.get(true); return bitCount.get(false) <= bitCount.get(true);
} }
} }

View File

@ -30,8 +30,7 @@ public class AnyBaseToAnyBase {
try { try {
System.out.print("Enter number: "); System.out.print("Enter number: ");
n = in.next(); n = in.next();
System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
+ MAXIMUM_BASE + "): ");
b1 = in.nextInt(); b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!"); System.out.println("Invalid base!");
@ -41,8 +40,7 @@ public class AnyBaseToAnyBase {
System.out.println("The number is invalid for this base!"); System.out.println("The number is invalid for this base!");
continue; continue;
} }
System.out.print( System.out.print("Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b2 = in.nextInt(); b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!"); System.out.println("Invalid base!");

View File

@ -22,8 +22,7 @@ public class DecimalToAnyBase {
System.out.println("Decimal Input" System.out.println("Decimal Input"
+ " is: " + decInput); + " is: " + decInput);
System.out.println("Value of " + decInput + " in base " + base System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
+ " is: " + convertToAnyBase(decInput, base));
br.close(); br.close();
} }

View File

@ -61,8 +61,7 @@ public class HexToOct {
hexadecnum = scan.nextLine(); hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal // first convert hexadecimal to decimal
decnum = hex2decimal( decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum // variable decnum
// convert decimal to octal // convert decimal to octal

View File

@ -126,8 +126,7 @@ public class RgbHsvConversion {
return bHue && bSaturation && bValue; return bHue && bSaturation && bValue;
} }
private static int[] getRgbBySection( private static int[] getRgbBySection(double hueSection, double chroma, double matchValue, double secondLargestComponent) {
double hueSection, double chroma, double matchValue, double secondLargestComponent) {
int red; int red;
int green; int green;
int blue; int blue;

View File

@ -58,8 +58,7 @@ public class TurkishToLatinConversion {
'G', 'G',
}; };
for (int i = 0; i < turkishChars.length; i++) { for (int i = 0; i < turkishChars.length; i++) {
param = param.replaceAll( param = param.replaceAll(new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
} }
return param; return param;
} }

View File

@ -27,10 +27,8 @@ public class A_Star {
// Graph is bidirectional, for just one direction remove second instruction of this method. // Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) { private void addEdge(Edge edge) {
this.graph.get(edge.getFrom()) this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
.add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
this.graph.get(edge.getTo())
.add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
} }
} }
@ -64,8 +62,7 @@ public class A_Star {
private int distance; // distance advanced so far. private int distance; // distance advanced so far.
private ArrayList<Integer> path; // list of visited nodes in this path. private ArrayList<Integer> path; // list of visited nodes in this path.
private int private int estimated; // heuristic value associated to the last node od the path (current node).
estimated; // heuristic value associated to the last node od the path (current node).
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) { public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
this.distance = distance; this.distance = distance;
@ -153,12 +150,8 @@ public class A_Star {
}; };
Graph graph = new Graph(20); Graph graph = new Graph(20);
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140, 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,
null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10, 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));
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); initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic); PathAndDistance solution = aStar(3, 1, graph, heuristic);
@ -169,8 +162,7 @@ public class A_Star {
// nodes are prioritised by the less value of the current distance of their paths, and the // nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value // estimated value
// given by the heuristic function to reach the destination point from the current point. // given by the heuristic function to reach the destination point from the current point.
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>( PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point // dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0)); queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
@ -179,19 +171,16 @@ public class A_Star {
PathAndDistance currentData = new PathAndDistance(-1, null, -1); PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) { while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring. currentData = queue.poll(); // first in the queue, best node so keep exploring.
int currentPosition int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); // current node.
= currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) { if (currentPosition == to) {
solutionFound = true; solutionFound = true;
} else { } else {
for (Edge edge : graph.getNeighbours(currentPosition)) { for (Edge edge : graph.getNeighbours(currentPosition)) {
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath()); ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
updatedPath.add( updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path. // and the heuristic function value associated to that path.
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), updatedPath, heuristic[edge.getTo()]));
updatedPath, heuristic[edge.getTo()]));
} }
} }
} }

View File

@ -77,8 +77,7 @@ number between 0 and total number of vertices-1,both inclusive*/
p[0] = -1; p[0] = -1;
for (i = 0; i < v - 1; i++) { for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if (dist[arr[j].u] != Integer.MAX_VALUE if (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) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u; p[arr[j].v] = arr[j].u;
} }
@ -128,8 +127,7 @@ number between 0 and total number of vertices-1,both inclusive*/
p[source] = -1; p[source] = -1;
for (i = 0; i < v - 1; i++) { for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE 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) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u; p[arr[j].v] = arr[j].u;
} }
@ -137,8 +135,7 @@ number between 0 and total number of vertices-1,both inclusive*/
} }
// Final cycle for negative checking // Final cycle for negative checking
for (j = 0; j < e; j++) { for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE 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) {
neg = 1; neg = 1;
System.out.println("Negative cycle"); System.out.println("Negative cycle");
break; break;

View File

@ -16,8 +16,7 @@ import java.util.Arrays;
*/ */
public class BipartiteGrapfDFS { public class BipartiteGrapfDFS {
private static boolean bipartite( private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
if (color[node] == -1) { if (color[node] == -1) {
color[node] = 1; color[node] = 1;
} }

View File

@ -45,8 +45,7 @@ class dijkstras {
Set[u] = true; Set[u] = true;
for (int v = 0; v < k; v++) { for (int v = 0; v < k; v++) {
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
&& dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v]; dist[v] = dist[u] + graph[u][v];
} }
} }

View File

@ -9,15 +9,13 @@ public class FloydWarshall {
public static final int INFINITY = 999; public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) { public FloydWarshall(int numberofvertices) {
DistanceMatrix = new int[numberofvertices + 1][numberofvertices DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
+ 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex // vertex to destination vertex
// The matrix is initialized with 0's by default // The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices; this.numberofvertices = numberofvertices;
} }
public void floydwarshall( public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) { for (int destination = 1; destination <= numberofvertices; destination++) {
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
@ -26,15 +24,11 @@ public class FloydWarshall {
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) { for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) { for (int destination = 1; destination <= numberofvertices; destination++) {
if (DistanceMatrix[source][intermediate] if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] < DistanceMatrix[source][destination]) { // calculated distance it get replaced as
+ DistanceMatrix[intermediate][destination] // new shortest distance // if the new
< DistanceMatrix[source] // distance calculated is less then the
[destination]) { // calculated distance it get replaced as // earlier shortest
// new shortest distance // if the new DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
// distance calculated is less then the
// earlier shortest
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
+ DistanceMatrix[intermediate][destination];
} }
} }
} }

View File

@ -1,7 +1,9 @@
package com.thealgorithms.datastructures.graphs; package com.thealgorithms.datastructures.graphs;
/** /**
* Java program for Hamiltonian Cycle (https://en.wikipedia.org/wiki/Hamiltonian_path) * Java program for Hamiltonian Cycle
* (https://en.wikipedia.org/wiki/Hamiltonian_path)
*
* @author Akshay Dubey (https://github.com/itsAkshayDubey) * @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/ */
public class HamiltonianCycle { public class HamiltonianCycle {
@ -12,10 +14,11 @@ public class HamiltonianCycle {
/** /**
* Find hamiltonian cycle for given graph G(V,E) * Find hamiltonian cycle for given graph G(V,E)
*
* @param graph Adjacency matrix of a graph G(V, E) * @param graph Adjacency matrix of a graph G(V, E)
* for which hamiltonian path is to be found * for which hamiltonian path is to be found
* @return Array containing hamiltonian cycle * @return Array containing hamiltonian cycle
* else returns 1D array with value -1. * else returns 1D array with value -1.
*/ */
public int[] findHamiltonianCycle(int[][] graph) { public int[] findHamiltonianCycle(int[][] graph) {
this.V = graph.length; this.V = graph.length;
@ -44,12 +47,12 @@ public class HamiltonianCycle {
/** /**
* function to find paths recursively * function to find paths recursively
* Find paths recursively from given vertex * Find paths recursively from given vertex
*
* @param vertex Vertex from which path is to be found * @param vertex Vertex from which path is to be found
* @returns true if path is found false otherwise * @returns true if path is found false otherwise
*/ */
public boolean isPathFound(int vertex) { public boolean isPathFound(int vertex) {
boolean isLastVertexConnectedToStart boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
= this.graph[vertex][0] == 1 && this.pathCount == this.V;
if (isLastVertexConnectedToStart) { if (isLastVertexConnectedToStart) {
return true; return true;
} }
@ -69,7 +72,7 @@ public class HamiltonianCycle {
this.graph[vertex][v] = 0; this.graph[vertex][v] = 0;
this.graph[v][vertex] = 0; this.graph[v][vertex] = 0;
/** if vertex not already selected solve recursively **/ /** if vertex not already selected solve recursively **/
if (!isPresent(v)) { if (!isPresent(v)) {
return isPathFound(v); return isPathFound(v);
} }
@ -88,6 +91,7 @@ public class HamiltonianCycle {
/** /**
* function to check if path is already selected * function to check if path is already selected
* Check if path is already selected * Check if path is already selected
*
* @param vertex Starting vertex * @param vertex Starting vertex
*/ */
public boolean isPresent(int vertex) { public boolean isPresent(int vertex) {

View File

@ -74,8 +74,7 @@ public class Kruskal {
// captain of i, stores the set with all the connected nodes to i // captain of i, stores the set with all the connected nodes to i
HashSet<Integer>[] connectedGroups = new HashSet[nodes]; HashSet<Integer>[] connectedGroups = new HashSet[nodes];
HashSet<Edge>[] minGraph = new HashSet[nodes]; HashSet<Edge>[] minGraph = new HashSet[nodes];
PriorityQueue<Edge> edges PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
= new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
for (int i = 0; i < nodes; i++) { for (int i = 0; i < nodes; i++) {
minGraph[i] = new HashSet<>(); minGraph[i] = new HashSet<>();
connectedGroups[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>();
@ -88,8 +87,7 @@ public class Kruskal {
while (connectedElements != nodes && !edges.isEmpty()) { while (connectedElements != nodes && !edges.isEmpty()) {
Edge edge = edges.poll(); Edge edge = edges.poll();
// This if avoids cycles // This if avoids cycles
if (!connectedGroups[captain[edge.from]].contains(edge.to) if (!connectedGroups[captain[edge.from]].contains(edge.to) && !connectedGroups[captain[edge.to]].contains(edge.from)) {
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
// merge sets of the captains of each point connected by the edge // merge sets of the captains of each point connected by the edge
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
// update captains of the elements merged // update captains of the elements merged

View File

@ -258,9 +258,8 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for this vertex // Get the adjacency array for this vertex
int[] adjacent = _adjacency[currentVertex]; int[] adjacent = _adjacency[currentVertex];
for (int i = 0; i < adjacent.length; for (int i = 0; i < adjacent.length; i++) { // we are considering exploring, recurse on it // If an edge exists between the
i++) { // we are considering exploring, recurse on it // If an edge exists between the // currentVertex and the vertex
// currentVertex and the vertex
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) { if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
depthFirstOrder(i, visited, orderList); depthFirstOrder(i, visited, orderList);
} }
@ -309,9 +308,8 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for the currentVertex and // Get the adjacency array for the currentVertex and
// check each node // check each node
int[] adjacent = _adjacency[currentVertex]; int[] adjacent = _adjacency[currentVertex];
for (int vertex = 0; vertex < adjacent.length; for (int vertex = 0; vertex < adjacent.length; vertex++) { // vertex we are considering exploring, we add it to the queue // If an
vertex++) { // vertex we are considering exploring, we add it to the queue // If an // edge exists between the current vertex and the
// edge exists between the current vertex and the
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) { if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
queue.add(vertex); queue.add(vertex);
} }

View File

@ -70,10 +70,9 @@ class PrimMST {
// Update key value and parent index of the adjacent // Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those // vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST // vertices which are not yet included in MST
for (int v = 0; v < V; for (int v = 0; v < V; v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is
v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is // false for vertices not yet included in MST // graph[u][v] is non zero only
// false for vertices not yet included in MST // graph[u][v] is non zero only // for adjacent vertices of m
// for adjacent vertices of m
{ {
if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) { if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u; parent[v] = u;

View File

@ -83,15 +83,13 @@ public class TarjansAlgorithm {
Stack<Integer> st = new Stack<Integer>(); Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < V; i++) { for (int i = 0; i < V; i++) {
if (insertionTime[i] == -1) if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
} }
return SCClist; return SCClist;
} }
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
// Initialize insertion time and lowTime value of current node // Initialize insertion time and lowTime value of current node
insertionTime[u] = Time; insertionTime[u] = Time;

View File

@ -204,8 +204,7 @@ public class HashMapCuckooHashing {
* @return int the index where the key is located * @return int the index where the key is located
*/ */
public boolean checkTableContainsKey(int key) { public boolean checkTableContainsKey(int key) {
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
|| (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
} }
/** /**

View File

@ -143,8 +143,7 @@ public class FibonacciHeap {
if (this.empty()) { if (this.empty()) {
return new int[0]; /// return an empty array return new int[0]; /// return an empty array
} }
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
+ 1]; // creates the array
rankArray[this.min.rank]++; rankArray[this.min.rank]++;
HeapNode curr = this.min.next; HeapNode curr = this.min.next;
while (curr != this.min) { while (curr != this.min) {
@ -284,8 +283,7 @@ public class FibonacciHeap {
* *
*/ */
private HeapNode[] toBuckets(HeapNode curr) { private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
= new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null; curr.prev.next = null;
HeapNode tmpCurr; HeapNode tmpCurr;
while (curr != null) { while (curr != null) {

View File

@ -122,8 +122,7 @@ public class HeapElement {
return false; return false;
} }
HeapElement otherHeapElement = (HeapElement) o; HeapElement otherHeapElement = (HeapElement) o;
return ((this.key == otherHeapElement.key) return ((this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
} }
return false; return false;
} }

View File

@ -70,20 +70,17 @@ public class MaxHeap implements Heap {
// than any of its children's // than any of its children's
private void toggleDown(int elementIndex) { private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey(); double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key < getElementKey(elementIndex * 2)) boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any. // Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < maxHeap.size()) if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1); swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1; elementIndex = 2 * elementIndex + 1;
} else { } else {
swap(elementIndex, 2 * elementIndex); swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex; elementIndex = 2 * elementIndex;
} }
wrongOrder = (key < getElementKey(elementIndex * 2)) wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
} }
} }
@ -116,10 +113,7 @@ public class MaxHeap implements Heap {
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) { if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex); toggleUp(elementIndex);
} // ... or down ? } // ... or down ?
else if (((2 * elementIndex <= maxHeap.size()) else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex); toggleDown(elementIndex);
} }
} }

View File

@ -64,20 +64,17 @@ public class MinHeap implements Heap {
// than any of its children's // than any of its children's
private void toggleDown(int elementIndex) { private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey(); double key = minHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key > getElementKey(elementIndex * 2)) boolean wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any. // Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < minHeap.size()) if ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1); swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1; elementIndex = 2 * elementIndex + 1;
} else { } else {
swap(elementIndex, 2 * elementIndex); swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex; elementIndex = 2 * elementIndex;
} }
wrongOrder = (key > getElementKey(elementIndex * 2)) wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
} }
} }
@ -110,10 +107,7 @@ public class MinHeap implements Heap {
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) { if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex); toggleUp(elementIndex);
} // ... or down ? } // ... or down ?
else if (((2 * elementIndex <= minHeap.size()) else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex); toggleDown(elementIndex);
} }
} }

View File

@ -217,8 +217,7 @@ class LinkOperations {
public void insertTail(int x, DoublyLinkedList doublyLinkedList) { public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x); Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink --> newLink.next = null; // currentTail(tail) newlink -->
if (doublyLinkedList if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
.isEmpty()) { // Check if there are no elements in list then it adds first element
tail = newLink; tail = newLink;
head = tail; head = tail;
} else { } else {

View File

@ -203,9 +203,7 @@ public class SkipList<E extends Comparable<E>> {
return acc.toString(); return acc.toString();
}) })
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
String positions = IntStream.range(0, sizeWithHeader - 1) String positions = IntStream.range(0, sizeWithHeader - 1).mapToObj(i -> String.format("%3d", i)).collect(Collectors.joining(" "));
.mapToObj(i -> String.format("%3d", i))
.collect(Collectors.joining(" "));
return result + String.format("%n H %s%n", positions); return result + String.format("%n H %s%n", positions);
} }
@ -296,8 +294,7 @@ public class SkipList<E extends Comparable<E>> {
public BernoulliHeightStrategy(double probability) { public BernoulliHeightStrategy(double probability) {
if (probability <= 0 || probability >= 1) { if (probability <= 0 || probability >= 1) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability);
"Probability should be from 0 to 1. But was: " + probability);
} }
this.probability = probability; this.probability = probability;
} }

View File

@ -123,8 +123,7 @@ public class LinkedQueue<T> implements Iterable<T> {
*/ */
public T peek(int pos) { public T peek(int pos) {
if (pos > size) if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
Node<T> node = front; Node<T> node = front;
while (pos-- > 0) node = node.next; while (pos-- > 0) node = node.next;
return node.data; return node.data;

View File

@ -23,8 +23,7 @@ public class DecimalToAnyUsingStack {
*/ */
private static String convert(int number, int radix) { private static String convert(int number, int radix) {
if (radix < 2 || radix > 16) { if (radix < 2 || radix > 16) {
throw new ArithmeticException( throw new ArithmeticException(String.format("Invalid input -> number:%d,radius:%d", number, radix));
String.format("Invalid input -> number:%d,radius:%d", number, radix));
} }
char[] tables = { char[] tables = {
'0', '0',

View File

@ -23,7 +23,6 @@ public class CheckBinaryTreeIsValidBST {
return false; return false;
} }
return ( return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
} }
} }

View File

@ -48,12 +48,10 @@ public class CheckTreeIsSymmetric {
return false; return false;
} }
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
&& isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
} }
private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) { private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
return leftSubtreeRoot == null || rightSubtreeRoot == null return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
|| leftSubtreeRoot.data != rightSubtreeRoot.data;
} }
} }

View File

@ -36,8 +36,7 @@ public class CreateBinaryTreeFromInorderPreorder {
return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length); return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length);
} }
private static Node createTree(final Integer[] preorder, final Integer[] inorder, private static Node createTree(final Integer[] preorder, final Integer[] inorder, final int preStart, final int inStart, final int size) {
final int preStart, final int inStart, final int size) {
if (size == 0) { if (size == 0) {
return null; return null;
} }
@ -50,14 +49,11 @@ public class CreateBinaryTreeFromInorderPreorder {
int leftNodesCount = i - inStart; int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1; int rightNodesCount = size - leftNodesCount - 1;
root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount); root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
root.right root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
= createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root; return root;
} }
private static Node createTreeOptimized(final Integer[] preorder, private static Node createTreeOptimized(final Integer[] preorder, final Map<Integer, Integer> inorderMap, final int preStart, final int inStart, final int size) {
final Map<Integer, Integer> inorderMap, final int preStart, final int inStart,
final int size) {
if (size == 0) { if (size == 0) {
return null; return null;
} }
@ -66,10 +62,8 @@ public class CreateBinaryTreeFromInorderPreorder {
int i = inorderMap.get(preorder[preStart]); int i = inorderMap.get(preorder[preStart]);
int leftNodesCount = i - inStart; int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1; int rightNodesCount = size - leftNodesCount - 1;
root.left root.left = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
= createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount); root.right = createTreeOptimized(preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
root.right = createTreeOptimized(
preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root; return root;
} }
} }

View File

@ -37,8 +37,7 @@ public class KDTree {
if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty"); if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
this.k = points[0].getDimension(); this.k = points[0].getDimension();
for (Point point : points) for (Point point : points)
if (point.getDimension() != k) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0); this.root = build(points, 0);
} }
@ -49,13 +48,11 @@ public class KDTree {
* *
*/ */
KDTree(int[][] pointsCoordinates) { KDTree(int[][] pointsCoordinates) {
if (pointsCoordinates.length == 0) if (pointsCoordinates.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
throw new IllegalArgumentException("Points array cannot be empty");
this.k = pointsCoordinates[0].length; this.k = pointsCoordinates[0].length;
Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new); Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
for (Point point : points) for (Point point : points)
if (point.getDimension() != k) if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0); this.root = build(points, 0);
} }
@ -224,8 +221,7 @@ public class KDTree {
* *
*/ */
public void insert(Point point) { public void insert(Point point) {
if (point.getDimension() != k) if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
throw new IllegalArgumentException("Point has wrong dimension");
root = insert(root, point, 0); root = insert(root, point, 0);
} }
@ -257,8 +253,7 @@ public class KDTree {
* @return The Node corresponding to the specified point * @return The Node corresponding to the specified point
*/ */
public Optional<Node> search(Point point) { public Optional<Node> search(Point point) {
if (point.getDimension() != k) if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
throw new IllegalArgumentException("Point has wrong dimension");
return search(root, point); return search(root, point);
} }
@ -304,10 +299,7 @@ public class KDTree {
Node left = findMin(root.left, axis); Node left = findMin(root.left, axis);
Node right = findMin(root.right, axis); Node right = findMin(root.right, axis);
Node[] candidates = {left, root, right}; Node[] candidates = {left, root, right};
return Arrays.stream(candidates) return Arrays.stream(candidates).filter(Objects::nonNull).min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
.filter(Objects::nonNull)
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
} }
} }
@ -339,10 +331,7 @@ public class KDTree {
Node left = findMax(root.left, axis); Node left = findMax(root.left, axis);
Node right = findMax(root.right, axis); Node right = findMax(root.right, axis);
Node[] candidates = {left, root, right}; Node[] candidates = {left, root, right};
return Arrays.stream(candidates) return Arrays.stream(candidates).filter(Objects::nonNull).max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
.filter(Objects::nonNull)
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
} }
} }
@ -352,8 +341,7 @@ public class KDTree {
* @param point the point to delete * @param point the point to delete
* */ * */
public void delete(Point point) { public void delete(Point point) {
Node node Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
= search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
root = delete(root, node); root = delete(root, node);
} }
@ -406,12 +394,10 @@ public class KDTree {
if (root == null) return nearest; if (root == null) return nearest;
if (root.point.equals(point)) return root; if (root.point.equals(point)) return root;
int distance = Point.comparableDistance(root.point, point); int distance = Point.comparableDistance(root.point, point);
int distanceExceptAxis int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
= Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
if (distance < Point.comparableDistance(nearest.point, point)) nearest = root; if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
nearest = findNearest(root.getNearChild(point), point, nearest); nearest = findNearest(root.getNearChild(point), point, nearest);
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) nearest = findNearest(root.getFarChild(point), point, nearest);
nearest = findNearest(root.getFarChild(point), point, nearest);
return nearest; return nearest;
} }
} }

View File

@ -53,8 +53,7 @@ public class LCA {
* @param parent An array to store parents of all vertices * @param parent An array to store parents of all vertices
* @param depth An array to store depth of all vertices * @param depth An array to store depth of all vertices
*/ */
private static void dfs( private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
for (int adjacent : adj.get(s)) { for (int adjacent : adj.get(s)) {
if (adjacent != p) { if (adjacent != p) {
parent[adjacent] = s; parent[adjacent] = s;

View File

@ -28,8 +28,7 @@ public class RedBlackBST {
return; return;
} }
printTree(node.left); printTree(node.left);
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
+ " Parent: " + node.p.key + "\n");
printTree(node.right); printTree(node.right);
} }
@ -37,8 +36,7 @@ public class RedBlackBST {
if (node == nil) { if (node == nil) {
return; return;
} }
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
+ " Parent: " + node.p.key + "\n");
printTreepre(node.left); printTreepre(node.left);
printTreepre(node.right); printTreepre(node.right);
} }

View File

@ -26,8 +26,7 @@ public class SegmentTree {
} }
int mid = start + (end - start) / 2; int mid = start + (end - start) / 2;
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) + constructTree(arr, mid + 1, end, index * 2 + 2);
+ constructTree(arr, mid + 1, end, index * 2 + 2);
return this.seg_t[index]; return this.seg_t[index];
} }
@ -69,8 +68,7 @@ public class SegmentTree {
} }
int mid = start + (end - start) / 2; int mid = start + (end - start) / 2;
return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
+ getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
} }
/* A function to query the sum of the subarray [start...end]*/ /* A function to query the sum of the subarray [start...end]*/

View File

@ -53,8 +53,7 @@ public class LargeTreeNode<E> extends TreeNode<E> {
* @param childNodes {@link Collection} of child Nodes. * @param childNodes {@link Collection} of child Nodes.
* @see TreeNode#TreeNode(Object, Node) * @see TreeNode#TreeNode(Object, Node)
*/ */
public LargeTreeNode( public LargeTreeNode(E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) {
E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) {
super(data, parentNode); super(data, parentNode);
this.childNodes = childNodes; this.childNodes = childNodes;
} }

View File

@ -57,8 +57,7 @@ public class SimpleTreeNode<E> extends TreeNode<E> {
* @param rightNode Value to which the nodes' right child reference will be * @param rightNode Value to which the nodes' right child reference will be
* set. * set.
*/ */
public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode, public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode, SimpleTreeNode<E> rightNode) {
SimpleTreeNode<E> rightNode) {
super(data, parentNode); super(data, parentNode);
this.leftNode = leftNode; this.leftNode = leftNode;
this.rightNode = rightNode; this.rightNode = rightNode;

View File

@ -24,8 +24,7 @@ public class BoundaryFill {
* @param x_co_ordinate The x co-ordinate at which color is to be filled * @param x_co_ordinate The x co-ordinate at which color is to be filled
* @param y_co_ordinate The y co-ordinate at which color is to be filled * @param y_co_ordinate The y co-ordinate at which color is to be filled
*/ */
public static void putPixel( public static void putPixel(int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) {
int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) {
image[x_co_ordinate][y_co_ordinate] = new_color; image[x_co_ordinate][y_co_ordinate] = new_color;
} }
@ -38,11 +37,8 @@ public class BoundaryFill {
* @param new_color The new color which to be filled in the image * @param new_color The new color which to be filled in the image
* @param boundary_color The old color which is to be replaced in the image * @param boundary_color The old color which is to be replaced in the image
*/ */
public static void boundaryFill( public static void boundaryFill(int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) {
int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color, int boundary_color) { if (x_co_ordinate >= 0 && y_co_ordinate >= 0 && getPixel(image, x_co_ordinate, y_co_ordinate) != new_color && getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) {
if (x_co_ordinate >= 0 && y_co_ordinate >= 0
&& getPixel(image, x_co_ordinate, y_co_ordinate) != new_color
&& getPixel(image, x_co_ordinate, y_co_ordinate) != boundary_color) {
putPixel(image, x_co_ordinate, y_co_ordinate, new_color); putPixel(image, x_co_ordinate, y_co_ordinate, new_color);
boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color); boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color);
boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color); boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color);

View File

@ -22,8 +22,7 @@ public class BruteForceKnapsack {
// (1) nth item included // (1) nth item included
// (2) not included // (2) not included
else { else {
return Math.max( return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
} }
} }

View File

@ -10,10 +10,8 @@ public class CoinChange {
int amount = 12; int amount = 12;
int[] coins = {2, 4, 5}; int[] coins = {2, 4, 5};
System.out.println("Number of combinations of getting change for " + amount System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
+ " is: " + change(coins, amount)); System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount));
System.out.println("Minimum number of coins required for amount :" + amount
+ " is: " + minimumCoins(coins, amount));
} }
/** /**

View File

@ -76,8 +76,7 @@ public class EditDistance {
s2 = input.nextLine(); s2 = input.nextLine();
// ans stores the final Edit Distance between the two strings // ans stores the final Edit Distance between the two strings
int ans = minDistance(s1, s2); int ans = minDistance(s1, s2);
System.out.println( System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
"The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
input.close(); input.close();
} }

View File

@ -25,8 +25,7 @@ public class KnapsackMemoization {
} }
// Returns the value of maximum profit using recursive approach // Returns the value of maximum profit using recursive approach
int solveKnapsackRecursive( int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
// Base condition // Base condition
if (numOfItems == 0 || capacity == 0) { if (numOfItems == 0 || capacity == 0) {
return 0; return 0;
@ -38,16 +37,11 @@ public class KnapsackMemoization {
if (weights[numOfItems - 1] > capacity) { if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table // Store the value of function call stack in table
dpTable[numOfItems][capacity] dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
= solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
return dpTable[numOfItems][capacity]; return dpTable[numOfItems][capacity];
} else { } else {
// Return value of table after storing // Return value of table after storing
return dpTable[numOfItems][capacity] return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)), solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable));
= Math.max((profits[numOfItems - 1]
+ solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights,
profits, numOfItems - 1, dpTable)),
solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable));
} }
} }
} }

View File

@ -32,9 +32,7 @@ public class LevenshteinDistance {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
distanceMat[i][j] = distanceMat[i - 1][j - 1]; distanceMat[i][j] = distanceMat[i - 1][j - 1];
} else { } else {
distanceMat[i][j] = 1 distanceMat[i][j] = 1 + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1], distanceMat[i][j - 1]);
+ minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1],
distanceMat[i][j - 1]);
} }
} }
} }

View File

@ -32,8 +32,7 @@ public class LongestPalindromicSubsequence {
} else { } else {
// if the last chars match, then remove it from both strings and recur // if the last chars match, then remove it from both strings and recur
if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) { if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1));
reverse.substring(0, reverse.length() - 1));
bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
} else { } else {
@ -42,10 +41,8 @@ public class LongestPalindromicSubsequence {
// updated original and reverse again then select the best result from these two // updated original and reverse again then select the best result from these two
// subproblems. // subproblems.
String bestSubResult1 String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
= recursiveLPS(original, reverse.substring(0, reverse.length() - 1)); String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse);
String bestSubResult2
= recursiveLPS(original.substring(0, original.length() - 1), reverse);
if (bestSubResult1.length() > bestSubResult2.length()) { if (bestSubResult1.length() > bestSubResult2.length()) {
bestResult = bestSubResult1; bestResult = bestSubResult1;
} else { } else {

View File

@ -28,8 +28,7 @@ public class MatrixChainRecursiveTopDownMemoisation {
return m[i][j]; return m[i][j];
} else { } else {
for (int k = i; k < j; k++) { for (int k = i; k < j; k++) {
int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) + (p[i - 1] * p[k] * p[j]);
+ (p[i - 1] * p[k] * p[j]);
if (q < m[i][j]) { if (q < m[i][j]) {
m[i][j] = q; m[i][j] = q;
} }

View File

@ -25,8 +25,7 @@ public class OptimalJobScheduling {
* @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of
* machines * machines
*/ */
public OptimalJobScheduling( public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
this.numberProcesses = numberProcesses; this.numberProcesses = numberProcesses;
this.numberMachines = numberMachines; this.numberMachines = numberMachines;
this.Run = Run; this.Run = Run;
@ -75,15 +74,13 @@ public class OptimalJobScheduling {
return Run[process][machine]; return Run[process][machine];
else { else {
int[] runningCosts int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on
= new int[numberMachines]; // stores the costs of executing our Process depending on // the Machine the previous one was executed
// the Machine the previous one was executed
for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous
// process to each and every Machine // process to each and every Machine
runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine] runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine] + Run[process][machine]; // transferring the result to our Machine and executing
+ Run[process][machine]; // transferring the result to our Machine and executing // the Process to our Machine
// the Process to our Machine
return findMin(runningCosts); // returns the minimum running cost return findMin(runningCosts); // returns the minimum running cost
} }

View File

@ -49,8 +49,7 @@ public class PalindromicPartitioning {
if (L == 2) { if (L == 2) {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)); isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
} else { } else {
isPalindrome[i][j] isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];
= (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];
} }
} }
} }
@ -81,8 +80,7 @@ public class PalindromicPartitioning {
word = input.nextLine(); word = input.nextLine();
// ans stores the final minimal cut count needed for partitioning // ans stores the final minimal cut count needed for partitioning
int ans = minimalpartitions(word); int ans = minimalpartitions(word);
System.out.println( System.out.println("The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans);
"The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans);
input.close(); input.close();
} }
} }

View File

@ -159,8 +159,7 @@ public class RegexMatching {
String pat = "*"; String pat = "*";
System.out.println("Method 1: " + regexRecursion(src, pat)); System.out.println("Method 1: " + regexRecursion(src, pat));
System.out.println("Method 2: " + regexRecursion(src, pat, 0, 0)); System.out.println("Method 2: " + regexRecursion(src, pat, 0, 0));
System.out.println( System.out.println("Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]));
"Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]));
System.out.println("Method 4: " + regexBU(src, pat)); System.out.println("Method 4: " + regexBU(src, pat));
} }
} }

View File

@ -75,8 +75,7 @@ public class WineProblem {
public static void main(String[] args) { public static void main(String[] args) {
int[] arr = {2, 3, 5, 1, 4}; int[] arr = {2, 3, 5, 1, 4};
System.out.println("Method 1: " + WPRecursion(arr, 0, arr.length - 1)); System.out.println("Method 1: " + WPRecursion(arr, 0, arr.length - 1));
System.out.println( System.out.println("Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]));
"Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]));
System.out.println("Method 3: " + WPBU(arr)); System.out.println("Method 3: " + WPBU(arr));
} }
} }

View File

@ -43,8 +43,7 @@ public class BufferedReader {
public BufferedReader(InputStream input, int bufferSize) throws IOException { public BufferedReader(InputStream input, int bufferSize) throws IOException {
this.input = input; this.input = input;
if (input.available() == -1) if (input.available() == -1) throw new IOException("Empty or already closed stream provided");
throw new IOException("Empty or already closed stream provided");
this.bufferSize = bufferSize; this.bufferSize = bufferSize;
buffer = new byte[bufferSize]; buffer = new byte[bufferSize];
@ -90,14 +89,10 @@ public class BufferedReader {
public int peek(int n) throws IOException { public int peek(int n) throws IOException {
int available = available(); int available = available();
if (n >= available) if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
throw new IOException(
"Out of range, available %d, but trying with %d".formatted(available, n));
pushRefreshData(); pushRefreshData();
if (n >= bufferSize) if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
throw new IllegalAccessError(
"Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
return buffer[n]; return buffer[n];
} }

View File

@ -21,8 +21,7 @@ public record ADTFraction(int numerator, int denominator) {
* @return A new {@code ADTFraction} containing the result of the operation * @return A new {@code ADTFraction} containing the result of the operation
*/ */
public ADTFraction plus(ADTFraction fraction) { public ADTFraction plus(ADTFraction fraction) {
var numerator var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
= this.denominator * fraction.numerator + this.numerator * fraction.denominator;
var denominator = this.denominator * fraction.denominator; var denominator = this.denominator * fraction.denominator;
return new ADTFraction(numerator, denominator); return new ADTFraction(numerator, denominator);
} }

View File

@ -17,10 +17,7 @@ public class AbsoluteMin {
var absMinWrapper = new Object() { int value = numbers[0]; }; var absMinWrapper = new Object() { int value = numbers[0]; };
Arrays.stream(numbers) Arrays.stream(numbers).skip(1).filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)).forEach(number -> absMinWrapper.value = number);
.skip(1)
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
.forEach(number -> absMinWrapper.value = number);
return absMinWrapper.value; return absMinWrapper.value;
} }

View File

@ -20,10 +20,7 @@ public class AliquotSum {
public static int getAliquotValue(int number) { public static int getAliquotValue(int number) {
var sumWrapper = new Object() { int value = 0; }; var sumWrapper = new Object() { int value = 0; };
IntStream.iterate(1, i -> ++i) IntStream.iterate(1, i -> ++i).limit(number / 2).filter(i -> number % i == 0).forEach(i -> sumWrapper.value += i);
.limit(number / 2)
.filter(i -> number % i == 0)
.forEach(i -> sumWrapper.value += i);
return sumWrapper.value; return sumWrapper.value;
} }

View File

@ -47,9 +47,7 @@ public class AmicableNumber {
} }
} }
} }
res.insert(0, res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n ");
"Int Range of " + startValue + " till " + stopValue + " there are " + countofRes
+ " Amicable_numbers.These are \n ");
System.out.println(res); System.out.println(res);
} }
@ -61,8 +59,7 @@ public class AmicableNumber {
* otherwise false * otherwise false
*/ */
static boolean isAmicableNumber(int numberOne, int numberTwo) { static boolean isAmicableNumber(int numberOne, int numberTwo) {
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
&& numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
} }
/** /**

View File

@ -135,8 +135,7 @@ public class Area {
* @param height height of trapezium * @param height height of trapezium
* @return area of given trapezium * @return area of given trapezium
*/ */
public static double surfaceAreaTrapezium( public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) {
final double base1, final double base2, final double height) {
if (base1 <= 0) { if (base1 <= 0) {
throw new IllegalArgumentException(POSITIVE_BASE + 1); throw new IllegalArgumentException(POSITIVE_BASE + 1);
} }

View File

@ -27,8 +27,7 @@ public class AutomorphicNumber {
numberOfdigits++; // Calculating number of digits in n numberOfdigits++; // Calculating number of digits in n
t /= 10; t /= 10;
} }
long lastDigits long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
= square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
return n == lastDigits; return n == lastDigits;
} }

View File

@ -33,7 +33,6 @@ public class BinomialCoefficient {
} }
// Recursive Call // Recursive Call
return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1) return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + binomialCoefficient(totalObjects - 1, numberOfObjects));
+ binomialCoefficient(totalObjects - 1, numberOfObjects));
} }
} }

View File

@ -38,10 +38,8 @@ public class CircularConvolutionFFT {
* @param b The other signal. * @param b The other signal.
* @return The convolved signal. * @return The convolved signal.
*/ */
public static ArrayList<FFT.Complex> fftCircularConvolution( public static ArrayList<FFT.Complex> fftCircularConvolution(ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) { int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one
int convolvedSize = Math.max(
a.size(), b.size()); // The two signals must have the same size equal to the bigger one
padding(a, convolvedSize); // Zero padding the smaller signal padding(a, convolvedSize); // Zero padding the smaller signal
padding(b, convolvedSize); padding(b, convolvedSize);

View File

@ -42,8 +42,7 @@ public class ConvolutionFFT {
* @param b The other signal. * @param b The other signal.
* @return The convolved signal. * @return The convolved signal.
*/ */
public static ArrayList<FFT.Complex> convolutionFFT( public static ArrayList<FFT.Complex> convolutionFFT(ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal
padding(a, convolvedSize); // Zero padding both signals padding(a, convolvedSize); // Zero padding both signals
padding(b, convolvedSize); padding(b, convolvedSize);
@ -58,9 +57,8 @@ public class ConvolutionFFT {
convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b) convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b)
} }
FFT.fft(convolved, true); // IFFT FFT.fft(convolved, true); // IFFT
convolved.subList(convolvedSize, convolved.size()) convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came
.clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came // from
// from
// paddingPowerOfTwo() method inside the fft() method. // paddingPowerOfTwo() method inside the fft() method.
return convolved; return convolved;

View File

@ -53,8 +53,7 @@ public class EulerMethod {
* @param differentialEquation The differential equation to be solved. * @param differentialEquation The differential equation to be solved.
* @return The next y-value. * @return The next y-value.
*/ */
public static double eulerStep(double xCurrent, double stepSize, double yCurrent, public static double eulerStep(double xCurrent, double stepSize, double yCurrent, BiFunction<Double, Double, Double> differentialEquation) {
BiFunction<Double, Double, Double> differentialEquation) {
if (stepSize <= 0) { if (stepSize <= 0) {
throw new IllegalArgumentException("stepSize should be greater than zero"); throw new IllegalArgumentException("stepSize should be greater than zero");
} }
@ -73,8 +72,7 @@ public class EulerMethod {
* @return The points constituting the solution of the differential * @return The points constituting the solution of the differential
* equation. * equation.
*/ */
public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize, public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize, double yStart, BiFunction<Double, Double, Double> differentialEquation) {
double yStart, BiFunction<Double, Double, Double> differentialEquation) {
if (xStart >= xEnd) { if (xStart >= xEnd) {
throw new IllegalArgumentException("xEnd should be greater than xStart"); throw new IllegalArgumentException("xEnd should be greater than xStart");
} }

View File

@ -25,24 +25,15 @@ public class FibonacciJavaStreams {
return Optional.of(BigDecimal.ONE); return Optional.of(BigDecimal.ONE);
} }
final List<BigDecimal> results final List<BigDecimal> results = Stream.iterate(index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE))
= Stream .reduce(List.of(), (list, current) -> list.isEmpty() || list.size() < 2 ? List.of(BigDecimal.ZERO, BigDecimal.ONE) : List.of(list.get(1), list.get(0).add(list.get(1))), (list1, list2) -> list1);
.iterate(
index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE))
.reduce(List.of(),
(list, current)
-> list.isEmpty() || list.size() < 2
? List.of(BigDecimal.ZERO, BigDecimal.ONE)
: List.of(list.get(1), list.get(0).add(list.get(1))),
(list1, list2) -> list1);
return results.isEmpty() ? Optional.empty() : Optional.of(results.get(results.size() - 1)); return results.isEmpty() ? Optional.empty() : Optional.of(results.get(results.size() - 1));
} }
public static void assertThat(final Object actual, final Object expected) { public static void assertThat(final Object actual, final Object expected) {
if (!Objects.equals(actual, expected)) { if (!Objects.equals(actual, expected)) {
throw new AssertionError( throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual));
String.format("expected=%s but was actual=%s", expected, actual));
} }
} }
@ -104,8 +95,7 @@ public class FibonacciJavaStreams {
{ {
final Optional<BigDecimal> result = calculate(new BigDecimal(200)); final Optional<BigDecimal> result = calculate(new BigDecimal(200));
assertThat(result.isPresent(), true); assertThat(result.isPresent(), true);
result.ifPresent(value result.ifPresent(value -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525")));
-> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525")));
} }
} }
} }

View File

@ -34,13 +34,10 @@ public class KaprekarNumbers {
BigInteger leftDigits1 = BigInteger.ZERO; BigInteger leftDigits1 = BigInteger.ZERO;
BigInteger leftDigits2; BigInteger leftDigits2;
if (numberSquared.toString().contains("0")) { if (numberSquared.toString().contains("0")) {
leftDigits1 = new BigInteger( leftDigits1 = new BigInteger(numberSquared.toString().substring(0, numberSquared.toString().indexOf("0")));
numberSquared.toString().substring(0, numberSquared.toString().indexOf("0")));
} }
leftDigits2 = new BigInteger(numberSquared.toString().substring( leftDigits2 = new BigInteger(numberSquared.toString().substring(0, (numberSquared.toString().length() - number.length())));
0, (numberSquared.toString().length() - number.length()))); BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(numberSquared.toString().length() - number.length()));
BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(
numberSquared.toString().length() - number.length()));
String x = leftDigits1.add(rightDigits).toString(); String x = leftDigits1.add(rightDigits).toString();
String y = leftDigits2.add(rightDigits).toString(); String y = leftDigits2.add(rightDigits).toString();
return (number.equals(x)) || (number.equals(y)); return (number.equals(x)) || (number.equals(y));

View File

@ -27,8 +27,7 @@ public final class LinearDiophantineEquationsSolver {
return toReturn; return toReturn;
} }
private static GcdSolutionWrapper gcd( private static GcdSolutionWrapper gcd(final int a, final int b, final GcdSolutionWrapper previous) {
final int a, final int b, final GcdSolutionWrapper previous) {
if (b == 0) { if (b == 0) {
return new GcdSolutionWrapper(a, new Solution(1, 0)); return new GcdSolutionWrapper(a, new Solution(1, 0));
} }
@ -36,18 +35,15 @@ public final class LinearDiophantineEquationsSolver {
final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0)); final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0));
final var next = /* recursive call */ gcd(b, a % b, stubWrapper); final var next = /* recursive call */ gcd(b, a % b, stubWrapper);
previous.getSolution().setX(next.getSolution().getY()); previous.getSolution().setX(next.getSolution().getY());
previous.getSolution().setY( previous.getSolution().setY(next.getSolution().getX() - (a / b) * (next.getSolution().getY()));
next.getSolution().getX() - (a / b) * (next.getSolution().getY()));
previous.setGcd(next.getGcd()); previous.setGcd(next.getGcd());
return new GcdSolutionWrapper(next.getGcd(), previous.getSolution()); return new GcdSolutionWrapper(next.getGcd(), previous.getSolution());
} }
public static final class Solution { public static final class Solution {
public static final Solution NO_SOLUTION public static final Solution NO_SOLUTION = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE);
= new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE); public static final Solution INFINITE_SOLUTIONS = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE);
public static final Solution INFINITE_SOLUTIONS
= new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE);
private int x; private int x;
private int y; private int y;

View File

@ -17,19 +17,15 @@ public class MatrixUtil {
return matrix != null && matrix.length > 0 && matrix[0].length > 0; return matrix != null && matrix.length > 0 && matrix[0].length > 0;
} }
public static boolean hasEqualSizes( public static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return (isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length && matrix1[0].length == matrix2[0].length);
return (isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length
&& matrix1[0].length == matrix2[0].length);
} }
public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length); return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length);
} }
public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
final BigDecimal[][] matrix2,
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
if (!hasEqualSizes(matrix1, matrix2)) { if (!hasEqualSizes(matrix1, matrix2)) {
return Optional.empty(); return Optional.empty();
} }
@ -39,29 +35,25 @@ public class MatrixUtil {
final BigDecimal[][] result = new BigDecimal[rowSize][columnSize]; final BigDecimal[][] result = new BigDecimal[rowSize][columnSize];
IntStream.range(0, rowSize) IntStream.range(0, rowSize).forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> {
.forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> { final BigDecimal value1 = matrix1[rowIndex][columnIndex];
final BigDecimal value1 = matrix1[rowIndex][columnIndex]; final BigDecimal value2 = matrix2[rowIndex][columnIndex];
final BigDecimal value2 = matrix2[rowIndex][columnIndex];
result[rowIndex][columnIndex] = operation.apply(value1, value2); result[rowIndex][columnIndex] = operation.apply(value1, value2);
})); }));
return Optional.of(result); return Optional.of(result);
} }
public static Optional<BigDecimal[][]> add( public static Optional<BigDecimal[][]> add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return operate(matrix1, matrix2, BigDecimal::add); return operate(matrix1, matrix2, BigDecimal::add);
} }
public static Optional<BigDecimal[][]> subtract( public static Optional<BigDecimal[][]> subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return operate(matrix1, matrix2, BigDecimal::subtract); return operate(matrix1, matrix2, BigDecimal::subtract);
} }
public static Optional<BigDecimal[][]> multiply( public static Optional<BigDecimal[][]> multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
if (!canMultiply(matrix1, matrix2)) { if (!canMultiply(matrix1, matrix2)) {
return Optional.empty(); return Optional.empty();
} }
@ -77,23 +69,21 @@ public class MatrixUtil {
.forEach(rowIndex .forEach(rowIndex
-> IntStream.range(0, matrix2ColumnSize) -> IntStream.range(0, matrix2ColumnSize)
.forEach(columnIndex .forEach(columnIndex
-> result[rowIndex][columnIndex] -> result[rowIndex][columnIndex] = IntStream.range(0, size)
= IntStream.range(0, size) .mapToObj(index -> {
.mapToObj(index -> { final BigDecimal value1 = matrix1[rowIndex][index];
final BigDecimal value1 = matrix1[rowIndex][index]; final BigDecimal value2 = matrix2[index][columnIndex];
final BigDecimal value2 = matrix2[index][columnIndex];
return value1.multiply(value2); return value1.multiply(value2);
}) })
.reduce(BigDecimal.ZERO, BigDecimal::add))); .reduce(BigDecimal.ZERO, BigDecimal::add)));
return Optional.of(result); return Optional.of(result);
} }
public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) { public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) {
if (!Objects.deepEquals(actual, expected)) { if (!Objects.deepEquals(actual, expected)) {
throw new AssertionError(String.format("expected=%s but was actual=%s", throw new AssertionError(String.format("expected=%s but was actual=%s", Arrays.deepToString(expected), Arrays.deepToString(actual)));
Arrays.deepToString(expected), Arrays.deepToString(actual)));
} }
} }
@ -109,9 +99,7 @@ public class MatrixUtil {
{new BigDecimal(2), new BigDecimal(0)}, {new BigDecimal(2), new BigDecimal(0)},
}; };
final BigDecimal[][] actual final BigDecimal[][] actual = add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
= add(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
final BigDecimal[][] expected = { final BigDecimal[][] expected = {
{new BigDecimal(4), new BigDecimal(5)}, {new BigDecimal(4), new BigDecimal(5)},
@ -132,9 +120,7 @@ public class MatrixUtil {
{new BigDecimal(-2), new BigDecimal(-3)}, {new BigDecimal(-2), new BigDecimal(-3)},
}; };
final BigDecimal[][] actual final BigDecimal[][] actual = subtract(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
= subtract(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
final BigDecimal[][] expected = { final BigDecimal[][] expected = {
{new BigDecimal(-1), new BigDecimal(4)}, {new BigDecimal(-1), new BigDecimal(4)},
@ -157,9 +143,7 @@ public class MatrixUtil {
{new BigDecimal(5), new BigDecimal(6)}, {new BigDecimal(5), new BigDecimal(6)},
}; };
final BigDecimal[][] actual final BigDecimal[][] actual = multiply(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
= multiply(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
final BigDecimal[][] expected = { final BigDecimal[][] expected = {
{new BigDecimal(22), new BigDecimal(28)}, {new BigDecimal(22), new BigDecimal(28)},

View File

@ -15,7 +15,6 @@ public class Median {
public static double median(int[] values) { public static double median(int[] values) {
Arrays.sort(values); Arrays.sort(values);
int length = values.length; int length = values.length;
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2];
: values[length / 2];
} }
} }

View File

@ -21,8 +21,7 @@ public class NonRepeatingElement {
} }
int[] arr = new int[n]; int[] arr = new int[n];
System.out.println( System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
"Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
for (i = 0; i < n; i++) { for (i = 0; i < n; i++) {
arr[i] = sc.nextInt(); arr[i] = sc.nextInt();
} }

View File

@ -27,8 +27,7 @@ public class Perimeter {
* @param sides for length of remaining sides * @param sides for length of remaining sides
* @return Perimeter of given trapezoid. * @return Perimeter of given trapezoid.
*/ */
public static float perimeterIrregularPolygon( public static float perimeterIrregularPolygon(float side1, float side2, float side3, float... sides) {
float side1, float side2, float side3, float... sides) {
float perimeter = side1 + side2 + side3; float perimeter = side1 + side2 + side3;
for (float side : sides) { for (float side : sides) {
perimeter += side; perimeter += side;

View File

@ -63,11 +63,9 @@ public class RomanNumeralUtil {
public static String generate(int number) { public static String generate(int number) {
if (number < MIN_VALUE || number > MAX_VALUE) { if (number < MIN_VALUE || number > MAX_VALUE) {
throw new IllegalArgumentException( throw new IllegalArgumentException(String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE));
String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE));
} }
return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] + RN_I[number % 10]);
+ RN_I[number % 10]);
} }
} }

View File

@ -22,9 +22,8 @@ public class SquareRootWithNewtonRaphsonMethod {
double x = n; // initially taking a guess that x = n. double x = n; // initially taking a guess that x = n.
double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. double root = 0.5 * (x + n / x); // applying Newton-Raphson Method.
while ( while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001
Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 // is the precision value taken over here.
// is the precision value taken over here.
x = root; // decreasing the value of x to root, i.e. decreasing the guess. x = root; // decreasing the value of x to root, i.e. decreasing the guess.
root = 0.5 * (x + n / x); root = 0.5 * (x + n / x);
} }

View File

@ -3,13 +3,11 @@ package com.thealgorithms.maths;
public class SumOfDigits { public class SumOfDigits {
public static void main(String[] args) { public static void main(String[] args) {
assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6;
&& sumOfDigitsFast(-123) == 6;
assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0; assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0;
assert sumOfDigits(12345) == 15 && sumOfDigitsRecursion(12345) == 15 assert sumOfDigits(12345) == 15 && sumOfDigitsRecursion(12345) == 15 && sumOfDigitsFast(12345) == 15;
&& sumOfDigitsFast(12345) == 15;
} }
/** /**

View File

@ -18,8 +18,7 @@ public class TrinomialTriangle {
return 0; return 0;
} }
return ( return (TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1));
TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1));
} }
public static void printTrinomial(int n) { public static void printTrinomial(int n) {

View File

@ -35,10 +35,8 @@ public class Fibonacci {
for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) { for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) {
for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) { for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) {
int matrixEntry = 0; int matrixEntry = 0;
for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; intermediateIndex++) {
intermediateIndex++) { matrixEntry += matrix1[rowIndex][intermediateIndex] * matrix2[intermediateIndex][colIndex];
matrixEntry += matrix1[rowIndex][intermediateIndex]
* matrix2[intermediateIndex][colIndex];
} }
product[rowIndex][colIndex] = matrixEntry; product[rowIndex][colIndex] = matrixEntry;
} }

View File

@ -23,8 +23,7 @@ public class MinimizingLateness {
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
StringTokenizer token; StringTokenizer token;
BufferedReader in BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
= new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
String ch = in.readLine(); String ch = in.readLine();
if (ch == null || ch.isEmpty()) { if (ch == null || ch.isEmpty()) {
in.close(); in.close();
@ -39,8 +38,7 @@ public class MinimizingLateness {
token = new StringTokenizer(ch, " "); token = new StringTokenizer(ch, " ");
// Include the time required for the operation to be performed in the array and the time // Include the time required for the operation to be performed in the array and the time
// it should be completed. // it should be completed.
array[i] = new Schedule( array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
i++; i++;
System.out.println(array[i - 1].t + " " + array[i - 1].d); System.out.println(array[i - 1].t + " " + array[i - 1].d);
} }

View File

@ -92,13 +92,11 @@ public class ColorContrastRatio {
final Color foreground = new Color(23, 103, 154); final Color foreground = new Color(23, 103, 154);
final double foregroundLuminance = algImpl.getRelativeLuminance(foreground); final double foregroundLuminance = algImpl.getRelativeLuminance(foreground);
assert foregroundLuminance assert foregroundLuminance == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance.";
== 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance.";
final Color background = new Color(226, 229, 248); final Color background = new Color(226, 229, 248);
final double backgroundLuminance = algImpl.getRelativeLuminance(background); final double backgroundLuminance = algImpl.getRelativeLuminance(background);
assert backgroundLuminance assert backgroundLuminance == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance.";
== 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance.";
final double contrastRatio = algImpl.getContrastRatio(foreground, background); final double contrastRatio = algImpl.getContrastRatio(foreground, background);
assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio.";

View File

@ -22,8 +22,7 @@ public class RangeInSortedArray {
// Recursive altered binary search which searches for leftmost as well as rightmost occurrence // Recursive altered binary search which searches for leftmost as well as rightmost occurrence
// of 'key' // of 'key'
public static void alteredBinSearch( public static void alteredBinSearch(int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
if (left > right) { if (left > right) {
return; return;
} }
@ -51,8 +50,7 @@ public class RangeInSortedArray {
// Iterative altered binary search which searches for leftmost as well as rightmost occurrence // Iterative altered binary search which searches for leftmost as well as rightmost occurrence
// of 'key' // of 'key'
public static void alteredBinSearchIter( public static void alteredBinSearchIter(int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
while (left <= right) { while (left <= right) {
int mid = (left + right) / 2; int mid = (left + right) / 2;
if (nums[mid] > key) { if (nums[mid] > key) {

View File

@ -26,8 +26,7 @@ public class WordBoggle {
public static void main(String[] args) { public static void main(String[] args) {
// Testcase // Testcase
List<String> ans = new ArrayList<>( List<String> ans = new ArrayList<>(Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
assert (boggleBoard( assert (boggleBoard(
new char[][] { new char[][] {
{'t', 'h', 'i', 's', 'i', 's', 'a'}, {'t', 'h', 'i', 's', 'i', 's', 'a'},
@ -55,8 +54,7 @@ public class WordBoggle {
.equals(ans)); .equals(ans));
} }
public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, Set<String> finalWords) {
Set<String> finalWords) {
if (visited[i][j]) { if (visited[i][j]) {
return; return;
} }

View File

@ -25,8 +25,7 @@ public class BankersAlgorithm {
/** /**
* This method finds the need of each process * This method finds the need of each process
*/ */
static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) {
int totalProcess, int totalResources) {
for (int i = 0; i < totalProcess; i++) { for (int i = 0; i < totalProcess; i++) {
for (int j = 0; j < totalResources; j++) { for (int j = 0; j < totalResources; j++) {
needArray[i][j] = maxArray[i][j] - allocationArray[i][j]; needArray[i][j] = maxArray[i][j] - allocationArray[i][j];
@ -49,8 +48,7 @@ public class BankersAlgorithm {
* *
* @return boolean if the system is in safe state or not * @return boolean if the system is in safe state or not
*/ */
static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) {
int[][] allocationArray, int totalProcess, int totalResources) {
int[][] needArray = new int[totalProcess][totalResources]; int[][] needArray = new int[totalProcess][totalResources];
calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources);
@ -158,8 +156,7 @@ public class BankersAlgorithm {
} }
} }
checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources);
numberOfResources);
sc.close(); sc.close();
} }

View File

@ -98,8 +98,7 @@ public class Damm {
private static void generateAndPrint(String input) { private static void generateAndPrint(String input) {
String result = addDammChecksum(input); String result = addDammChecksum(input);
System.out.println( System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
"Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
} }
private static void checkInput(String input) { private static void checkInput(String input) {

View File

@ -125,8 +125,7 @@ class Graph {
if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) { if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) {
return false; return false;
} }
return neighbours != null ? neighbours.equals(vertex.neighbours) return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null;
: vertex.neighbours == null;
} }
@Override @Override

View File

@ -7,8 +7,7 @@ import java.util.Set;
public class HappyNumbersSeq { public class HappyNumbersSeq {
private static final Set<Integer> CYCLE_NUMS private static final Set<Integer> CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
= new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
public static void main(String[] args) { public static void main(String[] args) {
Scanner in = new Scanner(System.in); Scanner in = new Scanner(System.in);

View File

@ -100,8 +100,7 @@ public class KochSnowflake {
double offsetX = imageWidth / 10.; double offsetX = imageWidth / 10.;
double offsetY = imageWidth / 3.7; double offsetY = imageWidth / 3.7;
Vector2 vector1 = new Vector2(offsetX, offsetY); Vector2 vector1 = new Vector2(offsetX, offsetY);
Vector2 vector2 Vector2 vector2 = new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY);
= new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY);
Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY); Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY);
ArrayList<Vector2> initialVectors = new ArrayList<Vector2>(); ArrayList<Vector2> initialVectors = new ArrayList<Vector2>();
initialVectors.add(vector1); initialVectors.add(vector1);
@ -146,10 +145,8 @@ public class KochSnowflake {
* @param imageHeight The height of the rendered image. * @param imageHeight The height of the rendered image.
* @return The image of the rendered edges. * @return The image of the rendered edges.
*/ */
private static BufferedImage GetImage( private static BufferedImage GetImage(ArrayList<Vector2> vectors, int imageWidth, int imageHeight) {
ArrayList<Vector2> vectors, int imageWidth, int imageHeight) { BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
BufferedImage image
= new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics(); Graphics2D g2d = image.createGraphics();
// Set the background white // Set the background white

View File

@ -35,8 +35,7 @@ public class LinearCongruentialGenerator {
* @param modulo The maximum number that can be generated (exclusive). A * @param modulo The maximum number that can be generated (exclusive). A
* common value is 2^32. * common value is 2^32.
*/ */
public LinearCongruentialGenerator( public LinearCongruentialGenerator(double seed, double multiplier, double increment, double modulo) {
double seed, double multiplier, double increment, double modulo) {
this.previousValue = seed; this.previousValue = seed;
this.a = multiplier; this.a = multiplier;
this.c = increment; this.c = increment;
@ -58,8 +57,7 @@ public class LinearCongruentialGenerator {
// Show the LCG in action. // Show the LCG in action.
// Decisive proof that the LCG works could be made by adding each number // Decisive proof that the LCG works could be made by adding each number
// generated to a Set while checking for duplicates. // generated to a Set while checking for duplicates.
LinearCongruentialGenerator lcg LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
= new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
for (int i = 0; i < 512; i++) { for (int i = 0; i < 512; i++) {
System.out.println(lcg.nextNumber()); System.out.println(lcg.nextNumber());
} }

View File

@ -115,8 +115,7 @@ public class Luhn {
int[] cardNumbers = toIntArray(trimmedCardNumber); int[] cardNumbers = toIntArray(trimmedCardNumber);
boolean isValid = luhnCheck(cardNumbers); boolean isValid = luhnCheck(cardNumbers);
if (!isValid) { if (!isValid) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo");
"Credit card number {" + cardNumber + "} - have a typo");
} }
return new CreditCard(cardNumbers); return new CreditCard(cardNumbers);
@ -149,8 +148,7 @@ public class Luhn {
private static void businessExample(String cardNumber) { private static void businessExample(String cardNumber) {
try { try {
System.out.println( System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber);
"Trying to create CreditCard object from valid card number: " + cardNumber);
CreditCard creditCard = CreditCard.fromString(cardNumber); CreditCard creditCard = CreditCard.fromString(cardNumber);
System.out.println("And business object is successfully created: " + creditCard + "\n"); System.out.println("And business object is successfully created: " + creditCard + "\n");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {

View File

@ -70,8 +70,7 @@ public class Mandelbrot {
* @param useDistanceColorCoding Render in color or black and white. * @param useDistanceColorCoding Render in color or black and white.
* @return The image of the rendered Mandelbrot set. * @return The image of the rendered Mandelbrot set.
*/ */
public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) {
double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) {
if (imageWidth <= 0) { if (imageWidth <= 0) {
throw new IllegalArgumentException("imageWidth should be greater than zero"); throw new IllegalArgumentException("imageWidth should be greater than zero");
} }
@ -84,8 +83,7 @@ public class Mandelbrot {
throw new IllegalArgumentException("maxStep should be greater than zero"); throw new IllegalArgumentException("maxStep should be greater than zero");
} }
BufferedImage image BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
= new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
double figureHeight = figureWidth / imageWidth * imageHeight; double figureHeight = figureWidth / imageWidth * imageHeight;
// loop through the image-coordinates // loop through the image-coordinates
@ -93,15 +91,12 @@ public class Mandelbrot {
for (int imageY = 0; imageY < imageHeight; imageY++) { for (int imageY = 0; imageY < imageHeight; imageY++) {
// determine the figure-coordinates based on the image-coordinates // determine the figure-coordinates based on the image-coordinates
double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth;
double figureY double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight;
= figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight;
double distance = getDistance(figureX, figureY, maxStep); double distance = getDistance(figureX, figureY, maxStep);
// color the corresponding pixel based on the selected coloring-function // color the corresponding pixel based on the selected coloring-function
image.setRGB(imageX, imageY, image.setRGB(imageX, imageY, useDistanceColorCoding ? colorCodedColorMap(distance).getRGB() : blackAndWhiteColorMap(distance).getRGB());
useDistanceColorCoding ? colorCodedColorMap(distance).getRGB()
: blackAndWhiteColorMap(distance).getRGB());
} }
} }

View File

@ -75,8 +75,7 @@ class BestFitCPU extends MemoryManagementAlgorithms {
int index = NO_ALLOCATION; // If there is no block that can fit the process, return int index = NO_ALLOCATION; // If there is no block that can fit the process, return
// NO_ALLOCATION as the // NO_ALLOCATION as the
// result. // result.
for (int i = 0; i < blockSizes.length; for (int i = 0; i < blockSizes.length; i++) { // Find the most fitting memory block for the given process.
i++) { // Find the most fitting memory block for the given process.
if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) { if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
minDiff = blockSizes[i] - processSize; minDiff = blockSizes[i] - processSize;
index = i; index = i;
@ -103,13 +102,10 @@ class BestFitCPU extends MemoryManagementAlgorithms {
ArrayList<Integer> memAlloc = new ArrayList<>(); ArrayList<Integer> memAlloc = new ArrayList<>();
// Do this for every process // Do this for every process
for (int processSize : sizeOfProcesses) { for (int processSize : sizeOfProcesses) {
int chosenBlockIdx = findBestFit( int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
if (chosenBlockIdx if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
sizeOfBlocks[chosenBlockIdx]
-= processSize; // resize the block based on the process size
} }
} }
return memAlloc; return memAlloc;
@ -133,8 +129,7 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
private static int findWorstFit(int[] blockSizes, int processSize) { private static int findWorstFit(int[] blockSizes, int processSize) {
int max = -1; int max = -1;
int index = -1; int index = -1;
for (int i = 0; i < blockSizes.length; for (int i = 0; i < blockSizes.length; i++) { // Find the index of the biggest memory block available.
i++) { // Find the index of the biggest memory block available.
if (blockSizes[i] > max) { if (blockSizes[i] > max) {
max = blockSizes[i]; max = blockSizes[i];
index = i; index = i;
@ -165,13 +160,10 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
ArrayList<Integer> memAlloc = new ArrayList<>(); ArrayList<Integer> memAlloc = new ArrayList<>();
// Do this for every process // Do this for every process
for (int processSize : sizeOfProcesses) { for (int processSize : sizeOfProcesses) {
int chosenBlockIdx = findWorstFit( int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
if (chosenBlockIdx if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
sizeOfBlocks[chosenBlockIdx]
-= processSize; // resize the block based on the process size
} }
} }
return memAlloc; return memAlloc;
@ -220,13 +212,10 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
ArrayList<Integer> memAlloc = new ArrayList<>(); ArrayList<Integer> memAlloc = new ArrayList<>();
// Do this for every process // Do this for every process
for (int processSize : sizeOfProcesses) { for (int processSize : sizeOfProcesses) {
int chosenBlockIdx = findFirstFit( int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
if (chosenBlockIdx if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
sizeOfBlocks[chosenBlockIdx]
-= processSize; // resize the block based on the process size
} }
} }
return memAlloc; return memAlloc;
@ -238,8 +227,7 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
*/ */
class NextFit extends MemoryManagementAlgorithms { class NextFit extends MemoryManagementAlgorithms {
private int counter private int counter = 0; // variable that keeps the position of the last registration into the memory
= 0; // variable that keeps the position of the last registration into the memory
/** /**
* Method to find the index of the memory block that is going to fit the * Method to find the index of the memory block that is going to fit the
@ -285,13 +273,10 @@ class NextFit extends MemoryManagementAlgorithms {
ArrayList<Integer> memAlloc = new ArrayList<>(); ArrayList<Integer> memAlloc = new ArrayList<>();
// Do this for every process // Do this for every process
for (int processSize : sizeOfProcesses) { for (int processSize : sizeOfProcesses) {
int chosenBlockIdx = findNextFit( int chosenBlockIdx = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
if (chosenBlockIdx if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
!= NO_ALLOCATION) { // Only if a block was chosen to store the process in it, sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
sizeOfBlocks[chosenBlockIdx]
-= processSize; // resize the block based on the process size
} }
} }
return memAlloc; return memAlloc;

View File

@ -42,8 +42,7 @@ public class MiniMaxAlgorithm {
} }
System.out.println(Arrays.toString(miniMaxAlgorith.getScores())); System.out.println(Arrays.toString(miniMaxAlgorith.getScores()));
System.out.println( System.out.println("The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore);
"The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore);
} }
/** /**
@ -79,8 +78,7 @@ public class MiniMaxAlgorithm {
// (1 x 2) = 2; ((1 x 2) + 1) = 3 // (1 x 2) = 2; ((1 x 2) + 1) = 3
// (2 x 2) = 4; ((2 x 2) + 1) = 5 ... // (2 x 2) = 4; ((2 x 2) + 1) = 5 ...
if (verbose) { if (verbose) {
System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2, System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2, (isMaximizer ? "Maximizer" : "Minimizer"), bestScore);
(isMaximizer ? "Maximizer" : "Minimizer"), bestScore);
} }
return bestScore; return bestScore;

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