Add automatic linter (#4214)
This commit is contained in:
parent
00282efd8b
commit
415a04ea7f
135
.clang-format
Normal file
135
.clang-format
Normal 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
16
.github/workflows/clang-format-lint.yml
vendored
Normal 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
|
30
.github/workflows/prettify.yml
vendored
30
.github/workflows/prettify.yml
vendored
@ -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 }}
|
16
DIRECTORY.md
16
DIRECTORY.md
@ -16,6 +16,7 @@
|
||||
* [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)
|
||||
* [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
|
||||
* a5
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -227,6 +229,7 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -351,7 +354,6 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* others
|
||||
* [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)
|
||||
* scheduling
|
||||
* [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)
|
||||
* searches
|
||||
* [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)
|
||||
* [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)
|
||||
* [WordSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java)
|
||||
* ciphers
|
||||
* a5
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -578,9 +583,11 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -601,6 +608,7 @@
|
||||
* [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)
|
||||
* [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)
|
||||
* geometry
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
@ -654,6 +663,7 @@
|
||||
* [PrimeFactorizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java)
|
||||
* [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java)
|
||||
* [PythagoreanTripleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java)
|
||||
* [ReverseNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java)
|
||||
* [SquareFreeIntegerTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java)
|
||||
* [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java)
|
||||
* [SquareRootWithNewtonRaphsonTestMethod](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java)
|
||||
@ -674,20 +684,24 @@
|
||||
* [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java)
|
||||
* [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
|
||||
* [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java)
|
||||
* [CountWordsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountWordsTest.java)
|
||||
* [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java)
|
||||
* [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [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)
|
||||
* [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java)
|
||||
* scheduling
|
||||
* [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)
|
||||
* searches
|
||||
* [BinarySearch2dArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java)
|
||||
|
@ -47,8 +47,7 @@ public class IIRFilter {
|
||||
*/
|
||||
public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
|
||||
if (aCoeffs.length != order) {
|
||||
throw new IllegalArgumentException(
|
||||
"aCoeffs must be of size " + order + ", got " + aCoeffs.length);
|
||||
throw new IllegalArgumentException("aCoeffs must be of size " + order + ", got " + aCoeffs.length);
|
||||
}
|
||||
|
||||
if (aCoeffs[0] == 0.0) {
|
||||
@ -56,8 +55,7 @@ public class IIRFilter {
|
||||
}
|
||||
|
||||
if (bCoeffs.length != order) {
|
||||
throw new IllegalArgumentException(
|
||||
"bCoeffs must be of size " + order + ", got " + bCoeffs.length);
|
||||
throw new IllegalArgumentException("bCoeffs must be of size " + order + ", got " + bCoeffs.length);
|
||||
}
|
||||
|
||||
for (int i = 0; i <= order; i++) {
|
||||
|
@ -58,8 +58,7 @@ public class AllPathsFromSourceToTarget {
|
||||
// A recursive function to print all paths from 'u' to 'd'.
|
||||
// isVisited[] keeps track of vertices in current path.
|
||||
// localPathList<> stores actual vertices in the current path
|
||||
private void storeAllPathsUtil(
|
||||
Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) {
|
||||
private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) {
|
||||
|
||||
if (u.equals(d)) {
|
||||
nm.add(new ArrayList<>(localPathList));
|
||||
@ -87,8 +86,7 @@ public class AllPathsFromSourceToTarget {
|
||||
}
|
||||
|
||||
// Driver program
|
||||
public static List<List<Integer>> allPathsFromSourceToTarget(
|
||||
int vertices, int[][] a, int source, int destination) {
|
||||
public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) {
|
||||
// Create a sample graph
|
||||
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
|
@ -37,8 +37,7 @@ public class Combination {
|
||||
* @param result the list contains all combination.
|
||||
* @param <T> the type of elements in the array.
|
||||
*/
|
||||
private static <T> void backtracking(
|
||||
T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
|
||||
private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
|
||||
if (index + length - currSet.size() > arr.length) return;
|
||||
if (length - 1 == currSet.size()) {
|
||||
for (int i = index; i < arr.length; i++) {
|
||||
|
@ -47,8 +47,7 @@ public class NQueens {
|
||||
List<List<String>> arrangements = new ArrayList<List<String>>();
|
||||
getSolution(queens, arrangements, new int[queens], 0);
|
||||
if (arrangements.isEmpty()) {
|
||||
System.out.println("There is no way to place " + queens + " queens on board of size "
|
||||
+ queens + "x" + queens);
|
||||
System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens);
|
||||
} else {
|
||||
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 columnIndex: This is the column in which queen is being placed
|
||||
*/
|
||||
private static void getSolution(
|
||||
int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) {
|
||||
private static void getSolution(int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) {
|
||||
if (columnIndex == boardSize) {
|
||||
// this means that all queens have been placed
|
||||
List<String> sol = new ArrayList<String>();
|
||||
|
@ -2413,8 +2413,7 @@ public class AES {
|
||||
}
|
||||
|
||||
// replace bytes in original string
|
||||
rBytes = new StringBuilder(
|
||||
rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
|
||||
rBytes = new StringBuilder(rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
|
||||
}
|
||||
|
||||
// t = new BigInteger(rBytes, 16);
|
||||
@ -2453,12 +2452,8 @@ public class AES {
|
||||
// split previous key into 8-bit segments
|
||||
BigInteger[] prevKey = {
|
||||
roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
|
||||
roundKeys[i - 1]
|
||||
.remainder(new BigInteger("10000000000000000", 16))
|
||||
.divide(new BigInteger("100000000", 16)),
|
||||
roundKeys[i - 1]
|
||||
.remainder(new BigInteger("1000000000000000000000000", 16))
|
||||
.divide(new BigInteger("10000000000000000", 16)),
|
||||
roundKeys[i - 1].remainder(new BigInteger("10000000000000000", 16)).divide(new BigInteger("100000000", 16)),
|
||||
roundKeys[i - 1].remainder(new BigInteger("1000000000000000000000000", 16)).divide(new BigInteger("10000000000000000", 16)),
|
||||
roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
|
||||
};
|
||||
|
||||
@ -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 + 1]
|
||||
= MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
|
||||
outputCells[i * 4 + 2]
|
||||
= MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]];
|
||||
outputCells[i * 4 + 3]
|
||||
= MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
|
||||
outputCells[i * 4 + 1] = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
|
||||
outputCells[i * 4 + 2] = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]];
|
||||
outputCells[i * 4 + 3] = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
|
||||
}
|
||||
return mergeCellsIntoBlock(outputCells);
|
||||
}
|
||||
|
@ -57,9 +57,7 @@ public class AESEncryption {
|
||||
* @throws BadPaddingException (from Cipher)
|
||||
* @throws IllegalBlockSizeException (from Cipher)
|
||||
*/
|
||||
public static byte[] encryptText(String plainText, SecretKey secKey)
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
|
||||
IllegalBlockSizeException, BadPaddingException {
|
||||
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
|
||||
// AES defaults to AES/ECB/PKCS5Padding in Java 7
|
||||
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
|
||||
@ -71,9 +69,7 @@ public class AESEncryption {
|
||||
*
|
||||
* @return plainText
|
||||
*/
|
||||
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
|
||||
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
|
||||
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
|
||||
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
|
||||
// AES defaults to AES/ECB/PKCS5Padding in Java 7
|
||||
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
|
||||
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
|
||||
|
@ -1120,8 +1120,7 @@ public class Blowfish {
|
||||
a = hexToBin(a);
|
||||
b = hexToBin(b);
|
||||
String ans = "";
|
||||
for (int i = 0; i < a.length(); i++)
|
||||
ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
|
||||
for (int i = 0; i < a.length(); i++) ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0');
|
||||
ans = binToHex(ans);
|
||||
return ans;
|
||||
}
|
||||
|
@ -30,12 +30,10 @@ public class Caesar {
|
||||
|
||||
if (isCapitalLatinLetter(current)) {
|
||||
current += shift;
|
||||
encoded.append((
|
||||
char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
} else if (isSmallLatinLetter(current)) {
|
||||
current += shift;
|
||||
encoded.append((
|
||||
char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
|
||||
} else {
|
||||
encoded.append(current);
|
||||
}
|
||||
@ -59,12 +57,10 @@ public class Caesar {
|
||||
char current = encryptedMessage.charAt(i);
|
||||
if (isCapitalLatinLetter(current)) {
|
||||
current -= shift;
|
||||
decoded.append((
|
||||
char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
|
||||
decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
|
||||
} else if (isSmallLatinLetter(current)) {
|
||||
current -= shift;
|
||||
decoded.append((
|
||||
char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
|
||||
decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
|
||||
} else {
|
||||
decoded.append(current);
|
||||
}
|
||||
|
@ -51,8 +51,7 @@ public class ColumnarTranspositionCipher {
|
||||
*/
|
||||
public static String encrpyter(String word, String keyword, String abecedarium) {
|
||||
ColumnarTranspositionCipher.keyword = keyword;
|
||||
ColumnarTranspositionCipher.abecedarium
|
||||
= Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
|
||||
ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
|
||||
table = tableBuilder(word);
|
||||
Object[][] sortedTable = sortTable(table);
|
||||
StringBuilder wordEncrypted = new StringBuilder();
|
||||
@ -164,8 +163,7 @@ public class ColumnarTranspositionCipher {
|
||||
return columnArray;
|
||||
}
|
||||
|
||||
private static void switchColumns(
|
||||
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
|
||||
private static void switchColumns(Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
|
||||
for (int i = 0; i < table.length; i++) {
|
||||
table[i][secondColumnIndex] = table[i][firstColumnIndex];
|
||||
table[i][firstColumnIndex] = columnToSwitch[i];
|
||||
@ -199,8 +197,7 @@ public class ColumnarTranspositionCipher {
|
||||
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
|
||||
System.out.println("### Example of Columnar Transposition Cipher ###\n");
|
||||
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
|
||||
System.out.println("Word encrypted ->>> "
|
||||
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
|
||||
System.out.println("Word encrypted ->>> " + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
|
||||
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
|
||||
System.out.println("\n### Encrypted Table ###");
|
||||
showTable();
|
||||
|
@ -13,8 +13,7 @@ public class DES {
|
||||
private void sanitize(String key) {
|
||||
int length = key.length();
|
||||
if (length != 64) {
|
||||
throw new IllegalArgumentException(
|
||||
"DES key must be supplied as a 64 character binary string");
|
||||
throw new IllegalArgumentException("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
|
||||
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};
|
||||
private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
|
||||
|
||||
// Lookup table used to shift the initial key, in order to generate the subkeys
|
||||
private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
|
||||
|
||||
// Table to convert the 56 bit subkeys to 48 bit subkeys
|
||||
private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8,
|
||||
16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34,
|
||||
53, 46, 42, 50, 36, 29, 32};
|
||||
private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32};
|
||||
|
||||
// Initial permutatation of each 64 but message block
|
||||
private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54,
|
||||
46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51,
|
||||
43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
|
||||
private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
|
||||
|
||||
// Expansion table to convert right half of message blocks from 32 bits to 48 bits
|
||||
private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12,
|
||||
13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29,
|
||||
28, 29, 30, 31, 32, 1};
|
||||
private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1};
|
||||
|
||||
// The eight substitution boxes are defined below
|
||||
private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
|
||||
{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
|
||||
{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
|
||||
{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
|
||||
private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
|
||||
|
||||
private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
|
||||
{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
|
||||
{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
|
||||
{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
|
||||
private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
|
||||
|
||||
private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
|
||||
{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
|
||||
{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
|
||||
{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
|
||||
private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
|
||||
|
||||
private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
|
||||
{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
|
||||
{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
|
||||
{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
|
||||
private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
|
||||
|
||||
private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
|
||||
{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
|
||||
{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
|
||||
{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
|
||||
private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
|
||||
|
||||
private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
|
||||
{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
|
||||
{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
|
||||
{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
|
||||
private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
|
||||
|
||||
private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
|
||||
{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
|
||||
{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
|
||||
{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
|
||||
private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
|
||||
|
||||
private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
|
||||
{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
|
||||
{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
|
||||
{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
|
||||
private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
|
||||
|
||||
private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
|
||||
|
||||
// Permutation table, used in the feistel function post s-box usage
|
||||
static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8,
|
||||
24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
|
||||
static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
|
||||
|
||||
// Table used for final inversion of the message box after 16 rounds of Feistel Function
|
||||
static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6,
|
||||
46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3,
|
||||
43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
|
||||
static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
|
||||
|
||||
private String[] getSubkeys(String originalKey) {
|
||||
StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
|
||||
@ -182,8 +146,7 @@ public class DES {
|
||||
for (i = 0; i < 48; i += 6) {
|
||||
String block = mixedKey.substring(i, i + 6);
|
||||
int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
|
||||
int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4
|
||||
+ (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
|
||||
int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
|
||||
String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
|
||||
substitutedString.append(substitutedBlock);
|
||||
}
|
||||
@ -262,8 +225,7 @@ public class DES {
|
||||
StringBuilder decryptedMessage = new StringBuilder();
|
||||
int l = message.length(), i, j;
|
||||
if (l % 64 != 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"Encrypted message should be a multiple of 64 characters in length");
|
||||
throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
|
||||
}
|
||||
for (i = 0; i < l; i += 64) {
|
||||
String block = message.substring(i, i + 64);
|
||||
@ -274,7 +236,6 @@ public class DES {
|
||||
}
|
||||
decryptedMessage.append(new String(res));
|
||||
}
|
||||
return decryptedMessage.toString().replace(
|
||||
"\0", ""); // Get rid of the null bytes used for padding
|
||||
return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
|
||||
}
|
||||
}
|
||||
|
@ -34,8 +34,7 @@ public class RSA {
|
||||
* @return plain message
|
||||
*/
|
||||
public synchronized String decrypt(String encryptedMessage) {
|
||||
return new String(
|
||||
(new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
|
||||
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -6,8 +6,7 @@ import java.util.BitSet;
|
||||
public class A5Cipher {
|
||||
|
||||
private final A5KeyStreamGenerator keyStreamGenerator;
|
||||
private static final int KEY_STREAM_LENGTH
|
||||
= 228; // 28.5 bytes so we need to pad bytes or something
|
||||
private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
|
||||
|
||||
public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
|
||||
keyStreamGenerator = new A5KeyStreamGenerator();
|
||||
|
@ -9,8 +9,7 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
|
||||
private BitSet frameCounter;
|
||||
private BitSet sessionKey;
|
||||
private static final int INITIAL_CLOCKING_CYCLES = 100;
|
||||
private static final int KEY_STREAM_LENGTH
|
||||
= 228; // 28.5 bytes so we need to pad bytes or something
|
||||
private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
|
||||
|
||||
@Override
|
||||
public void initialize(BitSet sessionKey, BitSet frameCounter) {
|
||||
|
@ -29,8 +29,7 @@ public abstract class CompositeLFSR implements BaseLFSR {
|
||||
bitCount.put(false, 0);
|
||||
bitCount.put(true, 0);
|
||||
|
||||
registers.forEach(
|
||||
lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
|
||||
registers.forEach(lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
|
||||
return bitCount.get(false) <= bitCount.get(true);
|
||||
}
|
||||
}
|
||||
|
@ -30,8 +30,7 @@ public class AnyBaseToAnyBase {
|
||||
try {
|
||||
System.out.print("Enter number: ");
|
||||
n = in.next();
|
||||
System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and "
|
||||
+ MAXIMUM_BASE + "): ");
|
||||
System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
|
||||
b1 = in.nextInt();
|
||||
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
@ -41,8 +40,7 @@ public class AnyBaseToAnyBase {
|
||||
System.out.println("The number is invalid for this base!");
|
||||
continue;
|
||||
}
|
||||
System.out.print(
|
||||
"Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
|
||||
System.out.print("Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
|
||||
b2 = in.nextInt();
|
||||
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
|
||||
System.out.println("Invalid base!");
|
||||
|
@ -22,8 +22,7 @@ public class DecimalToAnyBase {
|
||||
|
||||
System.out.println("Decimal Input"
|
||||
+ " is: " + decInput);
|
||||
System.out.println("Value of " + decInput + " in base " + base
|
||||
+ " is: " + convertToAnyBase(decInput, base));
|
||||
System.out.println("Value of " + decInput + " in base " + base + " is: " + convertToAnyBase(decInput, base));
|
||||
|
||||
br.close();
|
||||
}
|
||||
|
@ -61,8 +61,7 @@ public class HexToOct {
|
||||
hexadecnum = scan.nextLine();
|
||||
|
||||
// first convert hexadecimal to decimal
|
||||
decnum = hex2decimal(
|
||||
hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
|
||||
decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
|
||||
// variable decnum
|
||||
|
||||
// convert decimal to octal
|
||||
|
@ -126,8 +126,7 @@ public class RgbHsvConversion {
|
||||
return bHue && bSaturation && bValue;
|
||||
}
|
||||
|
||||
private static int[] getRgbBySection(
|
||||
double hueSection, double chroma, double matchValue, double secondLargestComponent) {
|
||||
private static int[] getRgbBySection(double hueSection, double chroma, double matchValue, double secondLargestComponent) {
|
||||
int red;
|
||||
int green;
|
||||
int blue;
|
||||
|
@ -58,8 +58,7 @@ public class TurkishToLatinConversion {
|
||||
'G',
|
||||
};
|
||||
for (int i = 0; i < turkishChars.length; i++) {
|
||||
param = param.replaceAll(
|
||||
new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
|
||||
param = param.replaceAll(new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
@ -27,10 +27,8 @@ public class A_Star {
|
||||
|
||||
// Graph is bidirectional, for just one direction remove second instruction of this method.
|
||||
private void addEdge(Edge edge) {
|
||||
this.graph.get(edge.getFrom())
|
||||
.add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
|
||||
this.graph.get(edge.getTo())
|
||||
.add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
|
||||
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
|
||||
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
|
||||
}
|
||||
}
|
||||
|
||||
@ -64,8 +62,7 @@ public class A_Star {
|
||||
|
||||
private int distance; // distance advanced so far.
|
||||
private ArrayList<Integer> path; // list of visited nodes in this path.
|
||||
private int
|
||||
estimated; // heuristic value associated to the last node od the path (current node).
|
||||
private int estimated; // heuristic value associated to the last node od the path (current node).
|
||||
|
||||
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
|
||||
this.distance = distance;
|
||||
@ -153,12 +150,8 @@ public class A_Star {
|
||||
};
|
||||
|
||||
Graph graph = new Graph(20);
|
||||
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140,
|
||||
null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10,
|
||||
70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6,
|
||||
115, null, 15, 14, 80, null, 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1,
|
||||
101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18,
|
||||
142, null, 18, 8, 92, null, 8, 11, 87));
|
||||
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null,
|
||||
15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
|
||||
initializeGraph(graph, graphData);
|
||||
|
||||
PathAndDistance solution = aStar(3, 1, graph, heuristic);
|
||||
@ -169,8 +162,7 @@ public class A_Star {
|
||||
// nodes are prioritised by the less value of the current distance of their paths, and the
|
||||
// estimated value
|
||||
// given by the heuristic function to reach the destination point from the current point.
|
||||
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(
|
||||
Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
|
||||
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
|
||||
|
||||
// dummy data to start the algorithm from the beginning point
|
||||
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
|
||||
@ -179,19 +171,16 @@ public class A_Star {
|
||||
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
|
||||
while (!queue.isEmpty() && !solutionFound) {
|
||||
currentData = queue.poll(); // first in the queue, best node so keep exploring.
|
||||
int currentPosition
|
||||
= currentData.getPath().get(currentData.getPath().size() - 1); // current node.
|
||||
int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); // current node.
|
||||
if (currentPosition == to) {
|
||||
solutionFound = true;
|
||||
} else {
|
||||
for (Edge edge : graph.getNeighbours(currentPosition)) {
|
||||
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
|
||||
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
|
||||
updatedPath.add(
|
||||
edge.getTo()); // Add the new node to the path, update the distance,
|
||||
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
|
||||
// and the heuristic function value associated to that path.
|
||||
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(),
|
||||
updatedPath, heuristic[edge.getTo()]));
|
||||
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), updatedPath, heuristic[edge.getTo()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -77,8 +77,7 @@ number between 0 and total number of vertices-1,both inclusive*/
|
||||
p[0] = -1;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if (dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
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; // Update
|
||||
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;
|
||||
for (i = 0; i < v - 1; i++) {
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
|
||||
p[arr[j].v] = arr[j].u;
|
||||
}
|
||||
@ -137,8 +135,7 @@ number between 0 and total number of vertices-1,both inclusive*/
|
||||
}
|
||||
// Final cycle for negative checking
|
||||
for (j = 0; j < e; j++) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
|
||||
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
|
||||
neg = 1;
|
||||
System.out.println("Negative cycle");
|
||||
break;
|
||||
|
@ -16,8 +16,7 @@ import java.util.Arrays;
|
||||
*/
|
||||
public class BipartiteGrapfDFS {
|
||||
|
||||
private static boolean bipartite(
|
||||
int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
|
||||
private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
|
||||
if (color[node] == -1) {
|
||||
color[node] = 1;
|
||||
}
|
||||
|
@ -45,8 +45,7 @@ class dijkstras {
|
||||
Set[u] = true;
|
||||
|
||||
for (int v = 0; v < k; v++) {
|
||||
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
|
||||
&& dist[u] + graph[u][v] < dist[v]) {
|
||||
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
|
||||
dist[v] = dist[u] + graph[u][v];
|
||||
}
|
||||
}
|
||||
|
@ -9,15 +9,13 @@ public class FloydWarshall {
|
||||
public static final int INFINITY = 999;
|
||||
|
||||
public FloydWarshall(int numberofvertices) {
|
||||
DistanceMatrix = new int[numberofvertices + 1][numberofvertices
|
||||
+ 1]; // stores the value of distance from all the possible path form the source
|
||||
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
|
||||
// vertex to destination vertex
|
||||
// The matrix is initialized with 0's by default
|
||||
this.numberofvertices = numberofvertices;
|
||||
}
|
||||
|
||||
public void floydwarshall(
|
||||
int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
|
||||
public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
|
||||
@ -26,15 +24,11 @@ public class FloydWarshall {
|
||||
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
|
||||
for (int source = 1; source <= numberofvertices; source++) {
|
||||
for (int destination = 1; destination <= numberofvertices; destination++) {
|
||||
if (DistanceMatrix[source][intermediate]
|
||||
+ DistanceMatrix[intermediate][destination]
|
||||
< DistanceMatrix[source]
|
||||
[destination]) { // calculated distance it get replaced as
|
||||
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] < DistanceMatrix[source][destination]) { // calculated distance it get replaced as
|
||||
// new shortest distance // if the new
|
||||
// distance calculated is less then the
|
||||
// earlier shortest
|
||||
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
|
||||
+ DistanceMatrix[intermediate][destination];
|
||||
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,9 @@
|
||||
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)
|
||||
*/
|
||||
public class HamiltonianCycle {
|
||||
@ -12,6 +14,7 @@ public class HamiltonianCycle {
|
||||
|
||||
/**
|
||||
* Find hamiltonian cycle for given graph G(V,E)
|
||||
*
|
||||
* @param graph Adjacency matrix of a graph G(V, E)
|
||||
* for which hamiltonian path is to be found
|
||||
* @return Array containing hamiltonian cycle
|
||||
@ -44,12 +47,12 @@ public class HamiltonianCycle {
|
||||
/**
|
||||
* function to find paths recursively
|
||||
* Find paths recursively from given vertex
|
||||
*
|
||||
* @param vertex Vertex from which path is to be found
|
||||
* @returns true if path is found false otherwise
|
||||
*/
|
||||
public boolean isPathFound(int vertex) {
|
||||
boolean isLastVertexConnectedToStart
|
||||
= this.graph[vertex][0] == 1 && this.pathCount == this.V;
|
||||
boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
|
||||
if (isLastVertexConnectedToStart) {
|
||||
return true;
|
||||
}
|
||||
@ -88,6 +91,7 @@ public class HamiltonianCycle {
|
||||
/**
|
||||
* function to check if path is already selected
|
||||
* Check if path is already selected
|
||||
*
|
||||
* @param vertex Starting vertex
|
||||
*/
|
||||
public boolean isPresent(int vertex) {
|
||||
|
@ -74,8 +74,7 @@ public class Kruskal {
|
||||
// captain of i, stores the set with all the connected nodes to i
|
||||
HashSet<Integer>[] connectedGroups = new HashSet[nodes];
|
||||
HashSet<Edge>[] minGraph = new HashSet[nodes];
|
||||
PriorityQueue<Edge> edges
|
||||
= new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
|
||||
PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
|
||||
for (int i = 0; i < nodes; i++) {
|
||||
minGraph[i] = new HashSet<>();
|
||||
connectedGroups[i] = new HashSet<>();
|
||||
@ -88,8 +87,7 @@ public class Kruskal {
|
||||
while (connectedElements != nodes && !edges.isEmpty()) {
|
||||
Edge edge = edges.poll();
|
||||
// This if avoids cycles
|
||||
if (!connectedGroups[captain[edge.from]].contains(edge.to)
|
||||
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
|
||||
if (!connectedGroups[captain[edge.from]].contains(edge.to) && !connectedGroups[captain[edge.to]].contains(edge.from)) {
|
||||
// merge sets of the captains of each point connected by the edge
|
||||
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
|
||||
// update captains of the elements merged
|
||||
|
@ -258,8 +258,7 @@ class AdjacencyMatrixGraph {
|
||||
|
||||
// Get the adjacency array for this vertex
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int i = 0; i < adjacent.length;
|
||||
i++) { // we are considering exploring, recurse on it // If an edge exists between the
|
||||
for (int i = 0; i < adjacent.length; i++) { // we are considering exploring, recurse on it // If an edge exists between the
|
||||
// currentVertex and the vertex
|
||||
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
depthFirstOrder(i, visited, orderList);
|
||||
@ -309,8 +308,7 @@ class AdjacencyMatrixGraph {
|
||||
// Get the adjacency array for the currentVertex and
|
||||
// check each node
|
||||
int[] adjacent = _adjacency[currentVertex];
|
||||
for (int vertex = 0; vertex < adjacent.length;
|
||||
vertex++) { // vertex we are considering exploring, we add it to the queue // If an
|
||||
for (int vertex = 0; vertex < adjacent.length; vertex++) { // vertex we are considering exploring, we add it to the queue // If an
|
||||
// edge exists between the current vertex and the
|
||||
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
|
||||
queue.add(vertex);
|
||||
|
@ -70,8 +70,7 @@ class PrimMST {
|
||||
// Update key value and parent index of the adjacent
|
||||
// vertices of the picked vertex. Consider only those
|
||||
// vertices which are not yet included in MST
|
||||
for (int v = 0; v < V;
|
||||
v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is
|
||||
for (int v = 0; v < V; 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
|
||||
// for adjacent vertices of m
|
||||
{
|
||||
|
@ -83,15 +83,13 @@ public class TarjansAlgorithm {
|
||||
Stack<Integer> st = new Stack<Integer>();
|
||||
|
||||
for (int i = 0; i < V; i++) {
|
||||
if (insertionTime[i] == -1)
|
||||
stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
|
||||
if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
|
||||
}
|
||||
|
||||
return SCClist;
|
||||
}
|
||||
|
||||
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
|
||||
boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
|
||||
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
|
||||
|
||||
// Initialize insertion time and lowTime value of current node
|
||||
insertionTime[u] = Time;
|
||||
|
@ -204,8 +204,7 @@ public class HashMapCuckooHashing {
|
||||
* @return int the index where the key is located
|
||||
*/
|
||||
public boolean checkTableContainsKey(int key) {
|
||||
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key))
|
||||
|| (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
|
||||
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -143,8 +143,7 @@ public class FibonacciHeap {
|
||||
if (this.empty()) {
|
||||
return new int[0]; /// return an empty array
|
||||
}
|
||||
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO))
|
||||
+ 1]; // creates the array
|
||||
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
|
||||
rankArray[this.min.rank]++;
|
||||
HeapNode curr = this.min.next;
|
||||
while (curr != this.min) {
|
||||
@ -284,8 +283,7 @@ public class FibonacciHeap {
|
||||
*
|
||||
*/
|
||||
private HeapNode[] toBuckets(HeapNode curr) {
|
||||
HeapNode[] buckets
|
||||
= new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
|
||||
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
|
||||
curr.prev.next = null;
|
||||
HeapNode tmpCurr;
|
||||
while (curr != null) {
|
||||
|
@ -122,8 +122,7 @@ public class HeapElement {
|
||||
return false;
|
||||
}
|
||||
HeapElement otherHeapElement = (HeapElement) o;
|
||||
return ((this.key == otherHeapElement.key)
|
||||
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
|
||||
return ((this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
@ -70,20 +70,17 @@ public class MaxHeap implements Heap {
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = maxHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key < getElementKey(elementIndex * 2))
|
||||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2 * elementIndex < maxHeap.size())
|
||||
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
|
||||
if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
|
||||
swap(elementIndex, 2 * elementIndex + 1);
|
||||
elementIndex = 2 * elementIndex + 1;
|
||||
} else {
|
||||
swap(elementIndex, 2 * elementIndex);
|
||||
elementIndex = 2 * elementIndex;
|
||||
}
|
||||
wrongOrder = (key < getElementKey(elementIndex * 2))
|
||||
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
|
||||
wrongOrder = (key < getElementKey(elementIndex * 2)) || (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))) {
|
||||
toggleUp(elementIndex);
|
||||
} // ... or down ?
|
||||
else if (((2 * elementIndex <= maxHeap.size())
|
||||
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|
||||
|| ((2 * elementIndex < maxHeap.size())
|
||||
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
|
||||
else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
|
||||
toggleDown(elementIndex);
|
||||
}
|
||||
}
|
||||
|
@ -64,20 +64,17 @@ public class MinHeap implements Heap {
|
||||
// than any of its children's
|
||||
private void toggleDown(int elementIndex) {
|
||||
double key = minHeap.get(elementIndex - 1).getKey();
|
||||
boolean wrongOrder = (key > getElementKey(elementIndex * 2))
|
||||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
boolean wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
|
||||
// Check whether it shall swap the element with its left child or its right one if any.
|
||||
if ((2 * elementIndex < minHeap.size())
|
||||
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
|
||||
if ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
|
||||
swap(elementIndex, 2 * elementIndex + 1);
|
||||
elementIndex = 2 * elementIndex + 1;
|
||||
} else {
|
||||
swap(elementIndex, 2 * elementIndex);
|
||||
elementIndex = 2 * elementIndex;
|
||||
}
|
||||
wrongOrder = (key > getElementKey(elementIndex * 2))
|
||||
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
|
||||
wrongOrder = (key > getElementKey(elementIndex * 2)) || (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))) {
|
||||
toggleUp(elementIndex);
|
||||
} // ... or down ?
|
||||
else if (((2 * elementIndex <= minHeap.size())
|
||||
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|
||||
|| ((2 * elementIndex < minHeap.size())
|
||||
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
|
||||
else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
|
||||
toggleDown(elementIndex);
|
||||
}
|
||||
}
|
||||
|
@ -217,8 +217,7 @@ class LinkOperations {
|
||||
public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
|
||||
Link newLink = new Link(x);
|
||||
newLink.next = null; // currentTail(tail) newlink -->
|
||||
if (doublyLinkedList
|
||||
.isEmpty()) { // Check if there are no elements in list then it adds first element
|
||||
if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
|
||||
tail = newLink;
|
||||
head = tail;
|
||||
} else {
|
||||
|
@ -203,9 +203,7 @@ public class SkipList<E extends Comparable<E>> {
|
||||
return acc.toString();
|
||||
})
|
||||
.collect(Collectors.joining("\n"));
|
||||
String positions = IntStream.range(0, sizeWithHeader - 1)
|
||||
.mapToObj(i -> String.format("%3d", i))
|
||||
.collect(Collectors.joining(" "));
|
||||
String positions = IntStream.range(0, sizeWithHeader - 1).mapToObj(i -> String.format("%3d", i)).collect(Collectors.joining(" "));
|
||||
|
||||
return result + String.format("%n H %s%n", positions);
|
||||
}
|
||||
@ -296,8 +294,7 @@ public class SkipList<E extends Comparable<E>> {
|
||||
|
||||
public BernoulliHeightStrategy(double probability) {
|
||||
if (probability <= 0 || probability >= 1) {
|
||||
throw new IllegalArgumentException(
|
||||
"Probability should be from 0 to 1. But was: " + probability);
|
||||
throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability);
|
||||
}
|
||||
this.probability = probability;
|
||||
}
|
||||
|
@ -123,8 +123,7 @@ public class LinkedQueue<T> implements Iterable<T> {
|
||||
*/
|
||||
|
||||
public T peek(int pos) {
|
||||
if (pos > size)
|
||||
throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
|
||||
if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
|
||||
Node<T> node = front;
|
||||
while (pos-- > 0) node = node.next;
|
||||
return node.data;
|
||||
|
@ -23,8 +23,7 @@ public class DecimalToAnyUsingStack {
|
||||
*/
|
||||
private static String convert(int number, int radix) {
|
||||
if (radix < 2 || radix > 16) {
|
||||
throw new ArithmeticException(
|
||||
String.format("Invalid input -> number:%d,radius:%d", number, radix));
|
||||
throw new ArithmeticException(String.format("Invalid input -> number:%d,radius:%d", number, radix));
|
||||
}
|
||||
char[] tables = {
|
||||
'0',
|
||||
|
@ -23,7 +23,6 @@ public class CheckBinaryTreeIsValidBST {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
|
||||
return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
|
||||
}
|
||||
}
|
||||
|
@ -48,12 +48,10 @@ public class CheckTreeIsSymmetric {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left)
|
||||
&& isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
|
||||
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
|
||||
}
|
||||
|
||||
private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
|
||||
return leftSubtreeRoot == null || rightSubtreeRoot == null
|
||||
|| leftSubtreeRoot.data != rightSubtreeRoot.data;
|
||||
return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
|
||||
}
|
||||
}
|
||||
|
@ -36,8 +36,7 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length);
|
||||
}
|
||||
|
||||
private static Node createTree(final Integer[] preorder, final Integer[] inorder,
|
||||
final int preStart, final int inStart, final int size) {
|
||||
private static Node createTree(final Integer[] preorder, final Integer[] inorder, final int preStart, final int inStart, final int size) {
|
||||
if (size == 0) {
|
||||
return null;
|
||||
}
|
||||
@ -50,14 +49,11 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
int leftNodesCount = i - inStart;
|
||||
int rightNodesCount = size - leftNodesCount - 1;
|
||||
root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
|
||||
root.right
|
||||
= createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
|
||||
root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
|
||||
return root;
|
||||
}
|
||||
|
||||
private static Node createTreeOptimized(final Integer[] preorder,
|
||||
final Map<Integer, Integer> inorderMap, final int preStart, final int inStart,
|
||||
final int size) {
|
||||
private static Node createTreeOptimized(final Integer[] preorder, final Map<Integer, Integer> inorderMap, final int preStart, final int inStart, final int size) {
|
||||
if (size == 0) {
|
||||
return null;
|
||||
}
|
||||
@ -66,10 +62,8 @@ public class CreateBinaryTreeFromInorderPreorder {
|
||||
int i = inorderMap.get(preorder[preStart]);
|
||||
int leftNodesCount = i - inStart;
|
||||
int rightNodesCount = size - leftNodesCount - 1;
|
||||
root.left
|
||||
= createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
|
||||
root.right = createTreeOptimized(
|
||||
preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
|
||||
root.left = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
|
||||
root.right = createTreeOptimized(preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
@ -37,8 +37,7 @@ public class KDTree {
|
||||
if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
|
||||
this.k = points[0].getDimension();
|
||||
for (Point point : points)
|
||||
if (point.getDimension() != k)
|
||||
throw new IllegalArgumentException("Points must have the same dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
|
||||
this.root = build(points, 0);
|
||||
}
|
||||
|
||||
@ -49,13 +48,11 @@ public class KDTree {
|
||||
*
|
||||
*/
|
||||
KDTree(int[][] pointsCoordinates) {
|
||||
if (pointsCoordinates.length == 0)
|
||||
throw new IllegalArgumentException("Points array cannot be empty");
|
||||
if (pointsCoordinates.length == 0) throw new IllegalArgumentException("Points array cannot be empty");
|
||||
this.k = pointsCoordinates[0].length;
|
||||
Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
|
||||
for (Point point : points)
|
||||
if (point.getDimension() != k)
|
||||
throw new IllegalArgumentException("Points must have the same dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
|
||||
this.root = build(points, 0);
|
||||
}
|
||||
|
||||
@ -224,8 +221,7 @@ public class KDTree {
|
||||
*
|
||||
*/
|
||||
public void insert(Point point) {
|
||||
if (point.getDimension() != k)
|
||||
throw new IllegalArgumentException("Point has wrong dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
|
||||
root = insert(root, point, 0);
|
||||
}
|
||||
|
||||
@ -257,8 +253,7 @@ public class KDTree {
|
||||
* @return The Node corresponding to the specified point
|
||||
*/
|
||||
public Optional<Node> search(Point point) {
|
||||
if (point.getDimension() != k)
|
||||
throw new IllegalArgumentException("Point has wrong dimension");
|
||||
if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
|
||||
return search(root, point);
|
||||
}
|
||||
|
||||
@ -304,10 +299,7 @@ public class KDTree {
|
||||
Node left = findMin(root.left, axis);
|
||||
Node right = findMin(root.right, axis);
|
||||
Node[] candidates = {left, root, right};
|
||||
return Arrays.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
|
||||
.orElse(null);
|
||||
return Arrays.stream(candidates).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 right = findMax(root.right, axis);
|
||||
Node[] candidates = {left, root, right};
|
||||
return Arrays.stream(candidates)
|
||||
.filter(Objects::nonNull)
|
||||
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
|
||||
.orElse(null);
|
||||
return Arrays.stream(candidates).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
|
||||
* */
|
||||
public void delete(Point point) {
|
||||
Node node
|
||||
= search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
|
||||
Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
|
||||
root = delete(root, node);
|
||||
}
|
||||
|
||||
@ -406,12 +394,10 @@ public class KDTree {
|
||||
if (root == null) return nearest;
|
||||
if (root.point.equals(point)) return root;
|
||||
int distance = Point.comparableDistance(root.point, point);
|
||||
int distanceExceptAxis
|
||||
= Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
|
||||
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
|
||||
if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
|
||||
nearest = findNearest(root.getNearChild(point), point, nearest);
|
||||
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point))
|
||||
nearest = findNearest(root.getFarChild(point), point, nearest);
|
||||
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) nearest = findNearest(root.getFarChild(point), point, nearest);
|
||||
return nearest;
|
||||
}
|
||||
}
|
||||
|
@ -53,8 +53,7 @@ public class LCA {
|
||||
* @param parent An array to store parents of all vertices
|
||||
* @param depth An array to store depth of all vertices
|
||||
*/
|
||||
private static void dfs(
|
||||
ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
|
||||
private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
|
||||
for (int adjacent : adj.get(s)) {
|
||||
if (adjacent != p) {
|
||||
parent[adjacent] = s;
|
||||
|
@ -28,8 +28,7 @@ public class RedBlackBST {
|
||||
return;
|
||||
}
|
||||
printTree(node.left);
|
||||
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
|
||||
+ " Parent: " + node.p.key + "\n");
|
||||
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
|
||||
printTree(node.right);
|
||||
}
|
||||
|
||||
@ -37,8 +36,7 @@ public class RedBlackBST {
|
||||
if (node == nil) {
|
||||
return;
|
||||
}
|
||||
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
|
||||
+ " Parent: " + node.p.key + "\n");
|
||||
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
|
||||
printTreepre(node.left);
|
||||
printTreepre(node.right);
|
||||
}
|
||||
|
@ -26,8 +26,7 @@ public class SegmentTree {
|
||||
}
|
||||
|
||||
int mid = start + (end - start) / 2;
|
||||
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1)
|
||||
+ constructTree(arr, mid + 1, end, index * 2 + 2);
|
||||
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) + constructTree(arr, mid + 1, end, index * 2 + 2);
|
||||
return this.seg_t[index];
|
||||
}
|
||||
|
||||
@ -69,8 +68,7 @@ public class SegmentTree {
|
||||
}
|
||||
|
||||
int mid = start + (end - start) / 2;
|
||||
return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1)
|
||||
+ getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
|
||||
return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
|
||||
}
|
||||
|
||||
/* A function to query the sum of the subarray [start...end]*/
|
||||
|
@ -53,8 +53,7 @@ public class LargeTreeNode<E> extends TreeNode<E> {
|
||||
* @param childNodes {@link Collection} of child Nodes.
|
||||
* @see TreeNode#TreeNode(Object, Node)
|
||||
*/
|
||||
public LargeTreeNode(
|
||||
E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) {
|
||||
public LargeTreeNode(E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) {
|
||||
super(data, parentNode);
|
||||
this.childNodes = childNodes;
|
||||
}
|
||||
|
@ -57,8 +57,7 @@ public class SimpleTreeNode<E> extends TreeNode<E> {
|
||||
* @param rightNode Value to which the nodes' right child reference will be
|
||||
* set.
|
||||
*/
|
||||
public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode,
|
||||
SimpleTreeNode<E> rightNode) {
|
||||
public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode, SimpleTreeNode<E> rightNode) {
|
||||
super(data, parentNode);
|
||||
this.leftNode = leftNode;
|
||||
this.rightNode = rightNode;
|
||||
|
@ -24,8 +24,7 @@ public class BoundaryFill {
|
||||
* @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
|
||||
*/
|
||||
public static void putPixel(
|
||||
int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) {
|
||||
public static void putPixel(int[][] image, int x_co_ordinate, int y_co_ordinate, int 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 boundary_color The old color which is to be replaced in the image
|
||||
*/
|
||||
public static void boundaryFill(
|
||||
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) {
|
||||
public static void boundaryFill(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) {
|
||||
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);
|
||||
|
@ -22,8 +22,7 @@ public class BruteForceKnapsack {
|
||||
// (1) nth item included
|
||||
// (2) not included
|
||||
else {
|
||||
return Math.max(
|
||||
val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
|
||||
return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1), knapSack(W, wt, val, n - 1));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -10,10 +10,8 @@ public class CoinChange {
|
||||
int amount = 12;
|
||||
int[] coins = {2, 4, 5};
|
||||
|
||||
System.out.println("Number of combinations of getting change for " + amount
|
||||
+ " is: " + change(coins, amount));
|
||||
System.out.println("Minimum number of coins required for amount :" + amount
|
||||
+ " is: " + minimumCoins(coins, amount));
|
||||
System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount));
|
||||
System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -76,8 +76,7 @@ public class EditDistance {
|
||||
s2 = input.nextLine();
|
||||
// ans stores the final Edit Distance between the two strings
|
||||
int ans = minDistance(s1, s2);
|
||||
System.out.println(
|
||||
"The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
|
||||
System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
|
||||
input.close();
|
||||
}
|
||||
|
||||
|
@ -25,8 +25,7 @@ public class KnapsackMemoization {
|
||||
}
|
||||
|
||||
// Returns the value of maximum profit using recursive approach
|
||||
int solveKnapsackRecursive(
|
||||
int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
|
||||
int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) {
|
||||
// Base condition
|
||||
if (numOfItems == 0 || capacity == 0) {
|
||||
return 0;
|
||||
@ -38,16 +37,11 @@ public class KnapsackMemoization {
|
||||
|
||||
if (weights[numOfItems - 1] > capacity) {
|
||||
// Store the value of function call stack in table
|
||||
dpTable[numOfItems][capacity]
|
||||
= solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
|
||||
dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
|
||||
return dpTable[numOfItems][capacity];
|
||||
} else {
|
||||
// Return value of table after storing
|
||||
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));
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -32,9 +32,7 @@ public class LevenshteinDistance {
|
||||
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
|
||||
distanceMat[i][j] = distanceMat[i - 1][j - 1];
|
||||
} else {
|
||||
distanceMat[i][j] = 1
|
||||
+ minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1],
|
||||
distanceMat[i][j - 1]);
|
||||
distanceMat[i][j] = 1 + minimum(distanceMat[i - 1][j], distanceMat[i - 1][j - 1], distanceMat[i][j - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -32,8 +32,7 @@ public class LongestPalindromicSubsequence {
|
||||
} else {
|
||||
// if the last chars match, then remove it from both strings and recur
|
||||
if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) {
|
||||
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1),
|
||||
reverse.substring(0, reverse.length() - 1));
|
||||
String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1));
|
||||
|
||||
bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult;
|
||||
} else {
|
||||
@ -42,10 +41,8 @@ public class LongestPalindromicSubsequence {
|
||||
// updated original and reverse again then select the best result from these two
|
||||
// subproblems.
|
||||
|
||||
String bestSubResult1
|
||||
= recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
|
||||
String bestSubResult2
|
||||
= recursiveLPS(original.substring(0, original.length() - 1), reverse);
|
||||
String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1));
|
||||
String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse);
|
||||
if (bestSubResult1.length() > bestSubResult2.length()) {
|
||||
bestResult = bestSubResult1;
|
||||
} else {
|
||||
|
@ -28,8 +28,7 @@ public class MatrixChainRecursiveTopDownMemoisation {
|
||||
return m[i][j];
|
||||
} else {
|
||||
for (int k = i; k < j; k++) {
|
||||
int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j)
|
||||
+ (p[i - 1] * p[k] * p[j]);
|
||||
int q = Lookup_Chain(m, p, i, k) + Lookup_Chain(m, p, k + 1, j) + (p[i - 1] * p[k] * p[j]);
|
||||
if (q < m[i][j]) {
|
||||
m[i][j] = q;
|
||||
}
|
||||
|
@ -25,8 +25,7 @@ public class OptimalJobScheduling {
|
||||
* @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of
|
||||
* machines
|
||||
*/
|
||||
public OptimalJobScheduling(
|
||||
int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
|
||||
public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run, int[][] Transfer) {
|
||||
this.numberProcesses = numberProcesses;
|
||||
this.numberMachines = numberMachines;
|
||||
this.Run = Run;
|
||||
@ -75,14 +74,12 @@ public class OptimalJobScheduling {
|
||||
return Run[process][machine];
|
||||
else {
|
||||
|
||||
int[] runningCosts
|
||||
= new int[numberMachines]; // stores the costs of executing our Process depending on
|
||||
int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on
|
||||
// the Machine the previous one was executed
|
||||
|
||||
for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous
|
||||
// process to each and every Machine
|
||||
runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine]
|
||||
+ Run[process][machine]; // transferring the result to our Machine and executing
|
||||
runningCosts[k] = Cost[process - 1][k] + Transfer[k][machine] + Run[process][machine]; // transferring the result to our Machine and executing
|
||||
// the Process to our Machine
|
||||
|
||||
return findMin(runningCosts); // returns the minimum running cost
|
||||
|
@ -49,8 +49,7 @@ public class PalindromicPartitioning {
|
||||
if (L == 2) {
|
||||
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
|
||||
} else {
|
||||
isPalindrome[i][j]
|
||||
= (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];
|
||||
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -81,8 +80,7 @@ public class PalindromicPartitioning {
|
||||
word = input.nextLine();
|
||||
// ans stores the final minimal cut count needed for partitioning
|
||||
int ans = minimalpartitions(word);
|
||||
System.out.println(
|
||||
"The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans);
|
||||
System.out.println("The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans);
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
|
@ -159,8 +159,7 @@ public class RegexMatching {
|
||||
String pat = "*";
|
||||
System.out.println("Method 1: " + regexRecursion(src, pat));
|
||||
System.out.println("Method 2: " + regexRecursion(src, pat, 0, 0));
|
||||
System.out.println(
|
||||
"Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]));
|
||||
System.out.println("Method 3: " + regexRecursion(src, pat, 0, 0, new int[src.length()][pat.length()]));
|
||||
System.out.println("Method 4: " + regexBU(src, pat));
|
||||
}
|
||||
}
|
||||
|
@ -75,8 +75,7 @@ public class WineProblem {
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {2, 3, 5, 1, 4};
|
||||
System.out.println("Method 1: " + WPRecursion(arr, 0, arr.length - 1));
|
||||
System.out.println(
|
||||
"Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]));
|
||||
System.out.println("Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]));
|
||||
System.out.println("Method 3: " + WPBU(arr));
|
||||
}
|
||||
}
|
||||
|
@ -43,8 +43,7 @@ public class BufferedReader {
|
||||
|
||||
public BufferedReader(InputStream input, int bufferSize) throws IOException {
|
||||
this.input = input;
|
||||
if (input.available() == -1)
|
||||
throw new IOException("Empty or already closed stream provided");
|
||||
if (input.available() == -1) throw new IOException("Empty or already closed stream provided");
|
||||
|
||||
this.bufferSize = bufferSize;
|
||||
buffer = new byte[bufferSize];
|
||||
@ -90,14 +89,10 @@ public class BufferedReader {
|
||||
|
||||
public int peek(int n) throws IOException {
|
||||
int available = available();
|
||||
if (n >= available)
|
||||
throw new IOException(
|
||||
"Out of range, available %d, but trying with %d".formatted(available, n));
|
||||
if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n));
|
||||
pushRefreshData();
|
||||
|
||||
if (n >= bufferSize)
|
||||
throw new IllegalAccessError(
|
||||
"Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
|
||||
if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize));
|
||||
return buffer[n];
|
||||
}
|
||||
|
||||
|
@ -21,8 +21,7 @@ public record ADTFraction(int numerator, int denominator) {
|
||||
* @return A new {@code ADTFraction} containing the result of the operation
|
||||
*/
|
||||
public ADTFraction plus(ADTFraction fraction) {
|
||||
var numerator
|
||||
= this.denominator * fraction.numerator + this.numerator * fraction.denominator;
|
||||
var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
|
||||
var denominator = this.denominator * fraction.denominator;
|
||||
return new ADTFraction(numerator, denominator);
|
||||
}
|
||||
|
@ -17,10 +17,7 @@ public class AbsoluteMin {
|
||||
|
||||
var absMinWrapper = new Object() { int value = numbers[0]; };
|
||||
|
||||
Arrays.stream(numbers)
|
||||
.skip(1)
|
||||
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
|
||||
.forEach(number -> absMinWrapper.value = number);
|
||||
Arrays.stream(numbers).skip(1).filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)).forEach(number -> absMinWrapper.value = number);
|
||||
|
||||
return absMinWrapper.value;
|
||||
}
|
||||
|
@ -20,10 +20,7 @@ public class AliquotSum {
|
||||
public static int getAliquotValue(int number) {
|
||||
var sumWrapper = new Object() { int value = 0; };
|
||||
|
||||
IntStream.iterate(1, i -> ++i)
|
||||
.limit(number / 2)
|
||||
.filter(i -> number % i == 0)
|
||||
.forEach(i -> sumWrapper.value += i);
|
||||
IntStream.iterate(1, i -> ++i).limit(number / 2).filter(i -> number % i == 0).forEach(i -> sumWrapper.value += i);
|
||||
|
||||
return sumWrapper.value;
|
||||
}
|
||||
|
@ -47,9 +47,7 @@ public class AmicableNumber {
|
||||
}
|
||||
}
|
||||
}
|
||||
res.insert(0,
|
||||
"Int Range of " + startValue + " till " + stopValue + " there are " + countofRes
|
||||
+ " Amicable_numbers.These are \n ");
|
||||
res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n ");
|
||||
System.out.println(res);
|
||||
}
|
||||
|
||||
@ -61,8 +59,7 @@ public class AmicableNumber {
|
||||
* otherwise false
|
||||
*/
|
||||
static boolean isAmicableNumber(int numberOne, int numberTwo) {
|
||||
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
|
||||
&& numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
|
||||
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -135,8 +135,7 @@ public class Area {
|
||||
* @param height height of trapezium
|
||||
* @return area of given trapezium
|
||||
*/
|
||||
public static double surfaceAreaTrapezium(
|
||||
final double base1, final double base2, final double height) {
|
||||
public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) {
|
||||
if (base1 <= 0) {
|
||||
throw new IllegalArgumentException(POSITIVE_BASE + 1);
|
||||
}
|
||||
|
@ -27,8 +27,7 @@ public class AutomorphicNumber {
|
||||
numberOfdigits++; // Calculating number of digits in n
|
||||
t /= 10;
|
||||
}
|
||||
long lastDigits
|
||||
= square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
|
||||
long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
|
||||
return n == lastDigits;
|
||||
}
|
||||
|
||||
|
@ -33,7 +33,6 @@ public class BinomialCoefficient {
|
||||
}
|
||||
|
||||
// Recursive Call
|
||||
return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1)
|
||||
+ binomialCoefficient(totalObjects - 1, numberOfObjects));
|
||||
return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + binomialCoefficient(totalObjects - 1, numberOfObjects));
|
||||
}
|
||||
}
|
||||
|
@ -38,10 +38,8 @@ public class CircularConvolutionFFT {
|
||||
* @param b The other signal.
|
||||
* @return The convolved signal.
|
||||
*/
|
||||
public static ArrayList<FFT.Complex> fftCircularConvolution(
|
||||
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
|
||||
public static ArrayList<FFT.Complex> fftCircularConvolution(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
|
||||
padding(a, convolvedSize); // Zero padding the smaller signal
|
||||
padding(b, convolvedSize);
|
||||
|
||||
|
@ -42,8 +42,7 @@ public class ConvolutionFFT {
|
||||
* @param b The other signal.
|
||||
* @return The convolved signal.
|
||||
*/
|
||||
public static ArrayList<FFT.Complex> convolutionFFT(
|
||||
ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
|
||||
public static ArrayList<FFT.Complex> convolutionFFT(ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
|
||||
int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal
|
||||
padding(a, convolvedSize); // Zero padding both signals
|
||||
padding(b, convolvedSize);
|
||||
@ -58,8 +57,7 @@ public class ConvolutionFFT {
|
||||
convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b)
|
||||
}
|
||||
FFT.fft(convolved, true); // IFFT
|
||||
convolved.subList(convolvedSize, convolved.size())
|
||||
.clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came
|
||||
convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came
|
||||
// from
|
||||
// paddingPowerOfTwo() method inside the fft() method.
|
||||
|
||||
|
@ -53,8 +53,7 @@ public class EulerMethod {
|
||||
* @param differentialEquation The differential equation to be solved.
|
||||
* @return The next y-value.
|
||||
*/
|
||||
public static double eulerStep(double xCurrent, double stepSize, double yCurrent,
|
||||
BiFunction<Double, Double, Double> differentialEquation) {
|
||||
public static double eulerStep(double xCurrent, double stepSize, double yCurrent, BiFunction<Double, Double, Double> differentialEquation) {
|
||||
if (stepSize <= 0) {
|
||||
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
|
||||
* equation.
|
||||
*/
|
||||
public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize,
|
||||
double yStart, BiFunction<Double, Double, Double> differentialEquation) {
|
||||
public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize, double yStart, BiFunction<Double, Double, Double> differentialEquation) {
|
||||
if (xStart >= xEnd) {
|
||||
throw new IllegalArgumentException("xEnd should be greater than xStart");
|
||||
}
|
||||
|
@ -25,24 +25,15 @@ public class FibonacciJavaStreams {
|
||||
return Optional.of(BigDecimal.ONE);
|
||||
}
|
||||
|
||||
final List<BigDecimal> results
|
||||
= Stream
|
||||
.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);
|
||||
final List<BigDecimal> results = Stream.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));
|
||||
}
|
||||
|
||||
public static void assertThat(final Object actual, final Object expected) {
|
||||
if (!Objects.equals(actual, expected)) {
|
||||
throw new AssertionError(
|
||||
String.format("expected=%s but was actual=%s", expected, actual));
|
||||
throw new AssertionError(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));
|
||||
assertThat(result.isPresent(), true);
|
||||
result.ifPresent(value
|
||||
-> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525")));
|
||||
result.ifPresent(value -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -34,13 +34,10 @@ public class KaprekarNumbers {
|
||||
BigInteger leftDigits1 = BigInteger.ZERO;
|
||||
BigInteger leftDigits2;
|
||||
if (numberSquared.toString().contains("0")) {
|
||||
leftDigits1 = new BigInteger(
|
||||
numberSquared.toString().substring(0, numberSquared.toString().indexOf("0")));
|
||||
leftDigits1 = new BigInteger(numberSquared.toString().substring(0, numberSquared.toString().indexOf("0")));
|
||||
}
|
||||
leftDigits2 = new BigInteger(numberSquared.toString().substring(
|
||||
0, (numberSquared.toString().length() - number.length())));
|
||||
BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(
|
||||
numberSquared.toString().length() - number.length()));
|
||||
leftDigits2 = new BigInteger(numberSquared.toString().substring(0, (numberSquared.toString().length() - number.length())));
|
||||
BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(numberSquared.toString().length() - number.length()));
|
||||
String x = leftDigits1.add(rightDigits).toString();
|
||||
String y = leftDigits2.add(rightDigits).toString();
|
||||
return (number.equals(x)) || (number.equals(y));
|
||||
|
@ -27,8 +27,7 @@ public final class LinearDiophantineEquationsSolver {
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
private static GcdSolutionWrapper gcd(
|
||||
final int a, final int b, final GcdSolutionWrapper previous) {
|
||||
private static GcdSolutionWrapper gcd(final int a, final int b, final GcdSolutionWrapper previous) {
|
||||
if (b == 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 next = /* recursive call */ gcd(b, a % b, stubWrapper);
|
||||
previous.getSolution().setX(next.getSolution().getY());
|
||||
previous.getSolution().setY(
|
||||
next.getSolution().getX() - (a / b) * (next.getSolution().getY()));
|
||||
previous.getSolution().setY(next.getSolution().getX() - (a / b) * (next.getSolution().getY()));
|
||||
previous.setGcd(next.getGcd());
|
||||
return new GcdSolutionWrapper(next.getGcd(), previous.getSolution());
|
||||
}
|
||||
|
||||
public static final class Solution {
|
||||
|
||||
public static final Solution NO_SOLUTION
|
||||
= 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 NO_SOLUTION = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE);
|
||||
public static final Solution INFINITE_SOLUTIONS = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE);
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
|
@ -17,19 +17,15 @@ public class MatrixUtil {
|
||||
return matrix != null && matrix.length > 0 && matrix[0].length > 0;
|
||||
}
|
||||
|
||||
public static boolean hasEqualSizes(
|
||||
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return (isValid(matrix1) && isValid(matrix2) && matrix1.length == matrix2.length
|
||||
&& matrix1[0].length == matrix2[0].length);
|
||||
public static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
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) {
|
||||
return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1,
|
||||
final BigDecimal[][] matrix2,
|
||||
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
|
||||
public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
|
||||
if (!hasEqualSizes(matrix1, matrix2)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@ -39,8 +35,7 @@ public class MatrixUtil {
|
||||
|
||||
final BigDecimal[][] result = new BigDecimal[rowSize][columnSize];
|
||||
|
||||
IntStream.range(0, rowSize)
|
||||
.forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> {
|
||||
IntStream.range(0, rowSize).forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> {
|
||||
final BigDecimal value1 = matrix1[rowIndex][columnIndex];
|
||||
final BigDecimal value2 = matrix2[rowIndex][columnIndex];
|
||||
|
||||
@ -50,18 +45,15 @@ public class MatrixUtil {
|
||||
return Optional.of(result);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> add(
|
||||
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
public static Optional<BigDecimal[][]> add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return operate(matrix1, matrix2, BigDecimal::add);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> subtract(
|
||||
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
public static Optional<BigDecimal[][]> subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
return operate(matrix1, matrix2, BigDecimal::subtract);
|
||||
}
|
||||
|
||||
public static Optional<BigDecimal[][]> multiply(
|
||||
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
public static Optional<BigDecimal[][]> multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
|
||||
if (!canMultiply(matrix1, matrix2)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
@ -77,8 +69,7 @@ public class MatrixUtil {
|
||||
.forEach(rowIndex
|
||||
-> IntStream.range(0, matrix2ColumnSize)
|
||||
.forEach(columnIndex
|
||||
-> result[rowIndex][columnIndex]
|
||||
= IntStream.range(0, size)
|
||||
-> result[rowIndex][columnIndex] = IntStream.range(0, size)
|
||||
.mapToObj(index -> {
|
||||
final BigDecimal value1 = matrix1[rowIndex][index];
|
||||
final BigDecimal value2 = matrix2[index][columnIndex];
|
||||
@ -92,8 +83,7 @@ public class MatrixUtil {
|
||||
|
||||
public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) {
|
||||
if (!Objects.deepEquals(actual, expected)) {
|
||||
throw new AssertionError(String.format("expected=%s but was actual=%s",
|
||||
Arrays.deepToString(expected), Arrays.deepToString(actual)));
|
||||
throw new AssertionError(String.format("expected=%s but was actual=%s", Arrays.deepToString(expected), Arrays.deepToString(actual)));
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,9 +99,7 @@ public class MatrixUtil {
|
||||
{new BigDecimal(2), new BigDecimal(0)},
|
||||
};
|
||||
|
||||
final BigDecimal[][] actual
|
||||
= add(matrix1, matrix2)
|
||||
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
final BigDecimal[][] actual = add(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
|
||||
final BigDecimal[][] expected = {
|
||||
{new BigDecimal(4), new BigDecimal(5)},
|
||||
@ -132,9 +120,7 @@ public class MatrixUtil {
|
||||
{new BigDecimal(-2), new BigDecimal(-3)},
|
||||
};
|
||||
|
||||
final BigDecimal[][] actual
|
||||
= subtract(matrix1, matrix2)
|
||||
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
final BigDecimal[][] actual = subtract(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
|
||||
final BigDecimal[][] expected = {
|
||||
{new BigDecimal(-1), new BigDecimal(4)},
|
||||
@ -157,9 +143,7 @@ public class MatrixUtil {
|
||||
{new BigDecimal(5), new BigDecimal(6)},
|
||||
};
|
||||
|
||||
final BigDecimal[][] actual
|
||||
= multiply(matrix1, matrix2)
|
||||
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
final BigDecimal[][] actual = multiply(matrix1, matrix2).orElseThrow(() -> new AssertionError("Could not compute matrix!"));
|
||||
|
||||
final BigDecimal[][] expected = {
|
||||
{new BigDecimal(22), new BigDecimal(28)},
|
||||
|
@ -15,7 +15,6 @@ public class Median {
|
||||
public static double median(int[] values) {
|
||||
Arrays.sort(values);
|
||||
int length = values.length;
|
||||
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0
|
||||
: values[length / 2];
|
||||
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0 : values[length / 2];
|
||||
}
|
||||
}
|
||||
|
@ -21,8 +21,7 @@ public class NonRepeatingElement {
|
||||
}
|
||||
int[] arr = new int[n];
|
||||
|
||||
System.out.println(
|
||||
"Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
|
||||
System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
|
||||
for (i = 0; i < n; i++) {
|
||||
arr[i] = sc.nextInt();
|
||||
}
|
||||
|
@ -27,8 +27,7 @@ public class Perimeter {
|
||||
* @param sides for length of remaining sides
|
||||
* @return Perimeter of given trapezoid.
|
||||
*/
|
||||
public static float perimeterIrregularPolygon(
|
||||
float side1, float side2, float side3, float... sides) {
|
||||
public static float perimeterIrregularPolygon(float side1, float side2, float side3, float... sides) {
|
||||
float perimeter = side1 + side2 + side3;
|
||||
for (float side : sides) {
|
||||
perimeter += side;
|
||||
|
@ -63,11 +63,9 @@ public class RomanNumeralUtil {
|
||||
|
||||
public static String generate(int number) {
|
||||
if (number < MIN_VALUE || number > MAX_VALUE) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE));
|
||||
throw new IllegalArgumentException(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]
|
||||
+ RN_I[number % 10]);
|
||||
return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] + RN_I[number % 10]);
|
||||
}
|
||||
}
|
||||
|
@ -22,8 +22,7 @@ public class SquareRootWithNewtonRaphsonMethod {
|
||||
double x = n; // initially taking a guess that x = n.
|
||||
double root = 0.5 * (x + n / x); // applying Newton-Raphson Method.
|
||||
|
||||
while (
|
||||
Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001
|
||||
while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001
|
||||
// is the precision value taken over here.
|
||||
x = root; // decreasing the value of x to root, i.e. decreasing the guess.
|
||||
root = 0.5 * (x + n / x);
|
||||
|
@ -3,13 +3,11 @@ package com.thealgorithms.maths;
|
||||
public class SumOfDigits {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6
|
||||
&& sumOfDigitsFast(-123) == 6;
|
||||
assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6;
|
||||
|
||||
assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0;
|
||||
|
||||
assert sumOfDigits(12345) == 15 && sumOfDigitsRecursion(12345) == 15
|
||||
&& sumOfDigitsFast(12345) == 15;
|
||||
assert sumOfDigits(12345) == 15 && sumOfDigitsRecursion(12345) == 15 && sumOfDigitsFast(12345) == 15;
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -18,8 +18,7 @@ public class TrinomialTriangle {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (
|
||||
TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1));
|
||||
return (TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1));
|
||||
}
|
||||
|
||||
public static void printTrinomial(int n) {
|
||||
|
@ -35,10 +35,8 @@ public class Fibonacci {
|
||||
for (int rowIndex = 0; rowIndex < rowsInMatrix1; rowIndex++) {
|
||||
for (int colIndex = 0; colIndex < columnsInMatrix2; colIndex++) {
|
||||
int matrixEntry = 0;
|
||||
for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1;
|
||||
intermediateIndex++) {
|
||||
matrixEntry += matrix1[rowIndex][intermediateIndex]
|
||||
* matrix2[intermediateIndex][colIndex];
|
||||
for (int intermediateIndex = 0; intermediateIndex < columnsInMatrix1; intermediateIndex++) {
|
||||
matrixEntry += matrix1[rowIndex][intermediateIndex] * matrix2[intermediateIndex][colIndex];
|
||||
}
|
||||
product[rowIndex][colIndex] = matrixEntry;
|
||||
}
|
||||
|
@ -23,8 +23,7 @@ public class MinimizingLateness {
|
||||
public static void main(String[] args) throws IOException {
|
||||
StringTokenizer token;
|
||||
|
||||
BufferedReader in
|
||||
= new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
|
||||
BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
|
||||
String ch = in.readLine();
|
||||
if (ch == null || ch.isEmpty()) {
|
||||
in.close();
|
||||
@ -39,8 +38,7 @@ public class MinimizingLateness {
|
||||
token = new StringTokenizer(ch, " ");
|
||||
// Include the time required for the operation to be performed in the array and the time
|
||||
// it should be completed.
|
||||
array[i] = new Schedule(
|
||||
Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
|
||||
array[i] = new Schedule(Integer.parseInt(token.nextToken()), Integer.parseInt(token.nextToken()));
|
||||
i++;
|
||||
System.out.println(array[i - 1].t + " " + array[i - 1].d);
|
||||
}
|
||||
|
@ -92,13 +92,11 @@ public class ColorContrastRatio {
|
||||
|
||||
final Color foreground = new Color(23, 103, 154);
|
||||
final double foregroundLuminance = algImpl.getRelativeLuminance(foreground);
|
||||
assert foregroundLuminance
|
||||
== 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance.";
|
||||
assert foregroundLuminance == 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance.";
|
||||
|
||||
final Color background = new Color(226, 229, 248);
|
||||
final double backgroundLuminance = algImpl.getRelativeLuminance(background);
|
||||
assert backgroundLuminance
|
||||
== 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance.";
|
||||
assert backgroundLuminance == 0.7898468477881603 : "Test 5 Failed - Incorrect relative luminance.";
|
||||
|
||||
final double contrastRatio = algImpl.getContrastRatio(foreground, background);
|
||||
assert contrastRatio == 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio.";
|
||||
|
@ -22,8 +22,7 @@ public class RangeInSortedArray {
|
||||
|
||||
// Recursive altered binary search which searches for leftmost as well as rightmost occurrence
|
||||
// of 'key'
|
||||
public static void alteredBinSearch(
|
||||
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
public static void alteredBinSearch(int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
if (left > right) {
|
||||
return;
|
||||
}
|
||||
@ -51,8 +50,7 @@ public class RangeInSortedArray {
|
||||
|
||||
// Iterative altered binary search which searches for leftmost as well as rightmost occurrence
|
||||
// of 'key'
|
||||
public static void alteredBinSearchIter(
|
||||
int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
public static void alteredBinSearchIter(int[] nums, int key, int left, int right, int[] range, boolean goLeft) {
|
||||
while (left <= right) {
|
||||
int mid = (left + right) / 2;
|
||||
if (nums[mid] > key) {
|
||||
|
@ -26,8 +26,7 @@ public class WordBoggle {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Testcase
|
||||
List<String> ans = new ArrayList<>(
|
||||
Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
|
||||
List<String> ans = new ArrayList<>(Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board"));
|
||||
assert (boggleBoard(
|
||||
new char[][] {
|
||||
{'t', 'h', 'i', 's', 'i', 's', 'a'},
|
||||
@ -55,8 +54,7 @@ public class WordBoggle {
|
||||
.equals(ans));
|
||||
}
|
||||
|
||||
public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited,
|
||||
Set<String> finalWords) {
|
||||
public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, Set<String> finalWords) {
|
||||
if (visited[i][j]) {
|
||||
return;
|
||||
}
|
||||
|
@ -25,8 +25,7 @@ public class BankersAlgorithm {
|
||||
/**
|
||||
* This method finds the need of each process
|
||||
*/
|
||||
static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray,
|
||||
int totalProcess, int totalResources) {
|
||||
static void calculateNeed(int[][] needArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) {
|
||||
for (int i = 0; i < totalProcess; i++) {
|
||||
for (int j = 0; j < totalResources; 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
|
||||
*/
|
||||
static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray,
|
||||
int[][] allocationArray, int totalProcess, int totalResources) {
|
||||
static boolean checkSafeSystem(int[] processes, int[] availableArray, int[][] maxArray, int[][] allocationArray, int totalProcess, int totalResources) {
|
||||
int[][] needArray = new int[totalProcess][totalResources];
|
||||
|
||||
calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources);
|
||||
@ -158,8 +156,7 @@ public class BankersAlgorithm {
|
||||
}
|
||||
}
|
||||
|
||||
checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses,
|
||||
numberOfResources);
|
||||
checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, numberOfResources);
|
||||
|
||||
sc.close();
|
||||
}
|
||||
|
@ -98,8 +98,7 @@ public class Damm {
|
||||
|
||||
private static void generateAndPrint(String input) {
|
||||
String result = addDammChecksum(input);
|
||||
System.out.println(
|
||||
"Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
|
||||
System.out.println("Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'");
|
||||
}
|
||||
|
||||
private static void checkInput(String input) {
|
||||
|
@ -125,8 +125,7 @@ class Graph {
|
||||
if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) {
|
||||
return false;
|
||||
}
|
||||
return neighbours != null ? neighbours.equals(vertex.neighbours)
|
||||
: vertex.neighbours == null;
|
||||
return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -7,8 +7,7 @@ import java.util.Set;
|
||||
|
||||
public class HappyNumbersSeq {
|
||||
|
||||
private static final Set<Integer> CYCLE_NUMS
|
||||
= new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
|
||||
private static final Set<Integer> CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145));
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
@ -100,8 +100,7 @@ public class KochSnowflake {
|
||||
double offsetX = imageWidth / 10.;
|
||||
double offsetY = imageWidth / 3.7;
|
||||
Vector2 vector1 = new Vector2(offsetX, offsetY);
|
||||
Vector2 vector2
|
||||
= new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY);
|
||||
Vector2 vector2 = new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY);
|
||||
Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY);
|
||||
ArrayList<Vector2> initialVectors = new ArrayList<Vector2>();
|
||||
initialVectors.add(vector1);
|
||||
@ -146,10 +145,8 @@ public class KochSnowflake {
|
||||
* @param imageHeight The height of the rendered image.
|
||||
* @return The image of the rendered edges.
|
||||
*/
|
||||
private static BufferedImage GetImage(
|
||||
ArrayList<Vector2> vectors, int imageWidth, int imageHeight) {
|
||||
BufferedImage image
|
||||
= new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
private static BufferedImage GetImage(ArrayList<Vector2> vectors, int imageWidth, int imageHeight) {
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g2d = image.createGraphics();
|
||||
|
||||
// Set the background white
|
||||
|
@ -35,8 +35,7 @@ public class LinearCongruentialGenerator {
|
||||
* @param modulo The maximum number that can be generated (exclusive). A
|
||||
* common value is 2^32.
|
||||
*/
|
||||
public LinearCongruentialGenerator(
|
||||
double seed, double multiplier, double increment, double modulo) {
|
||||
public LinearCongruentialGenerator(double seed, double multiplier, double increment, double modulo) {
|
||||
this.previousValue = seed;
|
||||
this.a = multiplier;
|
||||
this.c = increment;
|
||||
@ -58,8 +57,7 @@ public class LinearCongruentialGenerator {
|
||||
// Show the LCG in action.
|
||||
// Decisive proof that the LCG works could be made by adding each number
|
||||
// generated to a Set while checking for duplicates.
|
||||
LinearCongruentialGenerator lcg
|
||||
= new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
|
||||
LinearCongruentialGenerator lcg = new LinearCongruentialGenerator(1664525, 1013904223, Math.pow(2.0, 32.0));
|
||||
for (int i = 0; i < 512; i++) {
|
||||
System.out.println(lcg.nextNumber());
|
||||
}
|
||||
|
@ -115,8 +115,7 @@ public class Luhn {
|
||||
int[] cardNumbers = toIntArray(trimmedCardNumber);
|
||||
boolean isValid = luhnCheck(cardNumbers);
|
||||
if (!isValid) {
|
||||
throw new IllegalArgumentException(
|
||||
"Credit card number {" + cardNumber + "} - have a typo");
|
||||
throw new IllegalArgumentException("Credit card number {" + cardNumber + "} - have a typo");
|
||||
}
|
||||
|
||||
return new CreditCard(cardNumbers);
|
||||
@ -149,8 +148,7 @@ public class Luhn {
|
||||
|
||||
private static void businessExample(String cardNumber) {
|
||||
try {
|
||||
System.out.println(
|
||||
"Trying to create CreditCard object from valid card number: " + cardNumber);
|
||||
System.out.println("Trying to create CreditCard object from valid card number: " + cardNumber);
|
||||
CreditCard creditCard = CreditCard.fromString(cardNumber);
|
||||
System.out.println("And business object is successfully created: " + creditCard + "\n");
|
||||
} catch (IllegalArgumentException e) {
|
||||
|
@ -70,8 +70,7 @@ public class Mandelbrot {
|
||||
* @param useDistanceColorCoding Render in color or black and white.
|
||||
* @return The image of the rendered Mandelbrot set.
|
||||
*/
|
||||
public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX,
|
||||
double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) {
|
||||
public static BufferedImage getImage(int imageWidth, int imageHeight, double figureCenterX, double figureCenterY, double figureWidth, int maxStep, boolean useDistanceColorCoding) {
|
||||
if (imageWidth <= 0) {
|
||||
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");
|
||||
}
|
||||
|
||||
BufferedImage image
|
||||
= new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
|
||||
double figureHeight = figureWidth / imageWidth * imageHeight;
|
||||
|
||||
// loop through the image-coordinates
|
||||
@ -93,15 +91,12 @@ public class Mandelbrot {
|
||||
for (int imageY = 0; imageY < imageHeight; imageY++) {
|
||||
// determine the figure-coordinates based on the image-coordinates
|
||||
double figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth;
|
||||
double figureY
|
||||
= figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight;
|
||||
double figureY = figureCenterY + ((double) imageY / imageHeight - 0.5) * figureHeight;
|
||||
|
||||
double distance = getDistance(figureX, figureY, maxStep);
|
||||
|
||||
// color the corresponding pixel based on the selected coloring-function
|
||||
image.setRGB(imageX, imageY,
|
||||
useDistanceColorCoding ? colorCodedColorMap(distance).getRGB()
|
||||
: blackAndWhiteColorMap(distance).getRGB());
|
||||
image.setRGB(imageX, imageY, useDistanceColorCoding ? colorCodedColorMap(distance).getRGB() : blackAndWhiteColorMap(distance).getRGB());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -75,8 +75,7 @@ class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
int index = NO_ALLOCATION; // If there is no block that can fit the process, return
|
||||
// NO_ALLOCATION as the
|
||||
// result.
|
||||
for (int i = 0; i < blockSizes.length;
|
||||
i++) { // Find the most fitting memory block for the given process.
|
||||
for (int i = 0; i < blockSizes.length; i++) { // Find the most fitting memory block for the given process.
|
||||
if (blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
|
||||
minDiff = blockSizes[i] - processSize;
|
||||
index = i;
|
||||
@ -103,13 +102,10 @@ class BestFitCPU extends MemoryManagementAlgorithms {
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx = findBestFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findBestFit(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
|
||||
if (chosenBlockIdx
|
||||
!= 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
|
||||
if (chosenBlockIdx != 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
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
@ -133,8 +129,7 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
private static int findWorstFit(int[] blockSizes, int processSize) {
|
||||
int max = -1;
|
||||
int index = -1;
|
||||
for (int i = 0; i < blockSizes.length;
|
||||
i++) { // Find the index of the biggest memory block available.
|
||||
for (int i = 0; i < blockSizes.length; i++) { // Find the index of the biggest memory block available.
|
||||
if (blockSizes[i] > max) {
|
||||
max = blockSizes[i];
|
||||
index = i;
|
||||
@ -165,13 +160,10 @@ class WorstFitCPU extends MemoryManagementAlgorithms {
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx = findWorstFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findWorstFit(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
|
||||
if (chosenBlockIdx
|
||||
!= 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
|
||||
if (chosenBlockIdx != 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
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
@ -220,13 +212,10 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx = findFirstFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findFirstFit(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
|
||||
if (chosenBlockIdx
|
||||
!= 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
|
||||
if (chosenBlockIdx != 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
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
@ -238,8 +227,7 @@ class FirstFitCPU extends MemoryManagementAlgorithms {
|
||||
*/
|
||||
class NextFit extends MemoryManagementAlgorithms {
|
||||
|
||||
private int counter
|
||||
= 0; // variable that keeps the position of the last registration into the memory
|
||||
private int counter = 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
|
||||
@ -285,13 +273,10 @@ class NextFit extends MemoryManagementAlgorithms {
|
||||
ArrayList<Integer> memAlloc = new ArrayList<>();
|
||||
// Do this for every process
|
||||
for (int processSize : sizeOfProcesses) {
|
||||
int chosenBlockIdx = findNextFit(
|
||||
sizeOfBlocks, processSize); // Find the index of the memory block going to be used
|
||||
int chosenBlockIdx = findNextFit(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
|
||||
if (chosenBlockIdx
|
||||
!= 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
|
||||
if (chosenBlockIdx != 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
|
||||
}
|
||||
}
|
||||
return memAlloc;
|
||||
|
@ -42,8 +42,7 @@ public class MiniMaxAlgorithm {
|
||||
}
|
||||
|
||||
System.out.println(Arrays.toString(miniMaxAlgorith.getScores()));
|
||||
System.out.println(
|
||||
"The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore);
|
||||
System.out.println("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
|
||||
// (2 x 2) = 4; ((2 x 2) + 1) = 5 ...
|
||||
if (verbose) {
|
||||
System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2,
|
||||
(isMaximizer ? "Maximizer" : "Minimizer"), bestScore);
|
||||
System.out.printf("From %02d and %02d, %s chooses %02d%n", score1, score2, (isMaximizer ? "Maximizer" : "Minimizer"), bestScore);
|
||||
}
|
||||
|
||||
return bestScore;
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user