From 415a04ea7f1eb3ca129bbaafc85323b24faccacf Mon Sep 17 00:00:00 2001 From: acbin <44314231+acbin@users.noreply.github.com> Date: Fri, 9 Jun 2023 20:05:14 +0800 Subject: [PATCH] Add automatic linter (#4214) --- .clang-format | 135 +++++++++++++++++ .github/workflows/clang-format-lint.yml | 16 ++ .github/workflows/prettify.yml | 30 ---- DIRECTORY.md | 16 +- .../thealgorithms/audiofilters/IIRFilter.java | 6 +- .../AllPathsFromSourceToTarget.java | 6 +- .../backtracking/Combination.java | 3 +- .../thealgorithms/backtracking/NQueens.java | 6 +- .../java/com/thealgorithms/ciphers/AES.java | 20 +-- .../thealgorithms/ciphers/AESEncryption.java | 8 +- .../com/thealgorithms/ciphers/Blowfish.java | 3 +- .../com/thealgorithms/ciphers/Caesar.java | 12 +- .../ciphers/ColumnarTranspositionCipher.java | 9 +- .../java/com/thealgorithms/ciphers/DES.java | 75 +++------- .../java/com/thealgorithms/ciphers/RSA.java | 3 +- .../thealgorithms/ciphers/a5/A5Cipher.java | 3 +- .../ciphers/a5/A5KeyStreamGenerator.java | 3 +- .../ciphers/a5/CompositeLFSR.java | 3 +- .../conversions/AnyBaseToAnyBase.java | 6 +- .../conversions/DecimalToAnyBase.java | 3 +- .../thealgorithms/conversions/HexToOct.java | 3 +- .../conversions/RgbHsvConversion.java | 3 +- .../conversions/TurkishToLatinConversion.java | 3 +- .../datastructures/graphs/A_Star.java | 29 ++-- .../datastructures/graphs/BellmanFord.java | 9 +- .../graphs/BipartiteGrapfDFS.java | 3 +- .../graphs/DIJSKSTRAS_ALGORITHM.java | 3 +- .../datastructures/graphs/FloydWarshall.java | 20 +-- .../graphs/HamiltonianCycle.java | 16 +- .../datastructures/graphs/Kruskal.java | 6 +- .../datastructures/graphs/MatrixGraphs.java | 10 +- .../datastructures/graphs/PrimMST.java | 7 +- .../graphs/TarjansAlgorithm.java | 6 +- .../hashmap/hashing/HashMapCuckooHashing.java | 3 +- .../datastructures/heaps/FibonacciHeap.java | 6 +- .../datastructures/heaps/HeapElement.java | 3 +- .../datastructures/heaps/MaxHeap.java | 14 +- .../datastructures/heaps/MinHeap.java | 14 +- .../lists/DoublyLinkedList.java | 3 +- .../datastructures/lists/SkipList.java | 7 +- .../datastructures/queues/LinkedQueue.java | 3 +- .../stacks/DecimalToAnyUsingStack.java | 3 +- .../trees/CheckBinaryTreeIsValidBST.java | 3 +- .../trees/CheckTreeIsSymmetric.java | 6 +- .../CreateBinaryTreeFromInorderPreorder.java | 16 +- .../datastructures/trees/KDTree.java | 34 ++--- .../datastructures/trees/LCA.java | 3 +- .../datastructures/trees/RedBlackBST.java | 6 +- .../datastructures/trees/SegmentTree.java | 6 +- .../devutils/nodes/LargeTreeNode.java | 3 +- .../devutils/nodes/SimpleTreeNode.java | 3 +- .../dynamicprogramming/BoundaryFill.java | 10 +- .../BruteForceKnapsack.java | 3 +- .../dynamicprogramming/CoinChange.java | 6 +- .../dynamicprogramming/EditDistance.java | 3 +- .../KnapsackMemoization.java | 12 +- .../LevenshteinDistance.java | 4 +- .../LongestPalindromicSubsequence.java | 9 +- ...atrixChainRecursiveTopDownMemoisation.java | 3 +- .../OptimalJobScheduling.java | 13 +- .../PalindromicPartitioning.java | 6 +- .../dynamicprogramming/RegexMatching.java | 3 +- .../dynamicprogramming/WineProblem.java | 3 +- .../com/thealgorithms/io/BufferedReader.java | 11 +- .../com/thealgorithms/maths/ADTFraction.java | 3 +- .../com/thealgorithms/maths/AbsoluteMin.java | 5 +- .../com/thealgorithms/maths/AliquotSum.java | 5 +- .../thealgorithms/maths/AmicableNumber.java | 7 +- .../java/com/thealgorithms/maths/Area.java | 3 +- .../maths/AutomorphicNumber.java | 3 +- .../maths/BinomialCoefficient.java | 3 +- .../maths/CircularConvolutionFFT.java | 6 +- .../thealgorithms/maths/ConvolutionFFT.java | 8 +- .../com/thealgorithms/maths/EulerMethod.java | 6 +- .../maths/FibonacciJavaStreams.java | 18 +-- .../thealgorithms/maths/KaprekarNumbers.java | 9 +- .../LinearDiophantineEquationsSolver.java | 12 +- .../com/thealgorithms/maths/MatrixUtil.java | 60 +++----- .../java/com/thealgorithms/maths/Median.java | 3 +- .../maths/NonRepeatingElement.java | 3 +- .../com/thealgorithms/maths/Perimeter.java | 3 +- .../thealgorithms/maths/RomanNumeralUtil.java | 6 +- .../SquareRootWithNewtonRaphsonMethod.java | 5 +- .../com/thealgorithms/maths/SumOfDigits.java | 6 +- .../maths/TrinomialTriangle.java | 3 +- .../matrixexponentiation/Fibonacci.java | 6 +- .../MinimizingLateness.java | 6 +- .../misc/ColorContrastRatio.java | 6 +- .../misc/RangeInSortedArray.java | 6 +- .../com/thealgorithms/misc/WordBoggle.java | 6 +- .../others/BankersAlgorithm.java | 9 +- .../java/com/thealgorithms/others/Damm.java | 3 +- .../com/thealgorithms/others/Dijkstra.java | 3 +- .../thealgorithms/others/HappyNumbersSeq.java | 3 +- .../thealgorithms/others/KochSnowflake.java | 9 +- .../others/LinearCongruentialGenerator.java | 6 +- .../java/com/thealgorithms/others/Luhn.java | 6 +- .../com/thealgorithms/others/Mandelbrot.java | 13 +- .../others/MemoryManagementAlgorithms.java | 45 ++---- .../others/MiniMaxAlgorithm.java | 6 +- .../com/thealgorithms/others/PageRank.java | 15 +- .../com/thealgorithms/others/PerlinNoise.java | 3 +- .../others/QueueUsingTwoStacks.java | 3 +- .../others/ReturnSubsequence.java | 14 +- .../others/SieveOfEratosthenes.java | 3 +- .../thealgorithms/others/SkylineProblem.java | 3 +- .../com/thealgorithms/others/TopKWords.java | 3 +- .../com/thealgorithms/others/Verhoeff.java | 3 +- .../scheduling/FCFSScheduling.java | 6 +- .../scheduling/RRScheduling.java | 10 +- .../scheduling/SJFScheduling.java | 4 +- .../thealgorithms/searches/BinarySearch.java | 12 +- .../searches/BinarySearch2dArray.java | 6 +- .../searches/DepthFirstSearch.java | 24 +-- .../searches/ExponentalSearch.java | 12 +- .../searches/FibonacciSearch.java | 3 +- .../searches/InterpolationSearch.java | 12 +- .../searches/IterativeBinarySearch.java | 11 +- .../searches/IterativeTernarySearch.java | 11 +- .../thealgorithms/searches/LinearSearch.java | 6 +- .../thealgorithms/searches/LowerBound.java | 12 +- .../searches/MonteCarloTreeSearch.java | 14 +- .../thealgorithms/searches/QuickSelect.java | 6 +- .../thealgorithms/searches/TernarySearch.java | 11 +- .../thealgorithms/searches/UpperBound.java | 12 +- .../sortOrderAgnosticBinarySearch.java | 3 +- .../com/thealgorithms/sorts/CountingSort.java | 14 +- .../sorts/DualPivotQuickSort.java | 3 +- .../sorts/DutchNationalFlagSort.java | 3 +- .../thealgorithms/sorts/InsertionSort.java | 9 +- .../sorts/MergeSortNoExtraSpace.java | 3 +- .../sorts/MergeSortRecursive.java | 3 +- .../com/thealgorithms/sorts/StrandSort.java | 3 +- .../com/thealgorithms/sorts/TreeSort.java | 3 +- .../com/thealgorithms/sorts/WiggleSort.java | 6 +- .../com/thealgorithms/strings/Anagrams.java | 12 +- .../thealgorithms/strings/CheckVowels.java | 3 +- .../thealgorithms/strings/HorspoolSearch.java | 9 +- .../com/thealgorithms/strings/Palindrome.java | 3 +- .../strings/StringCompression.java | 3 +- .../strings/zigZagPattern/zigZagPattern.java | 3 +- .../AllPathsFromSourceToTargetTest.java | 24 +-- .../buffers/CircularBufferTest.java | 3 +- .../datastructures/lists/SkipListTest.java | 3 +- .../trees/CheckBinaryTreeIsValidBSTTest.java | 9 +- ...eateBinaryTreeFromInorderPreorderTest.java | 18 +-- .../trees/InorderTraversalTest.java | 3 +- .../trees/LevelOrderTraversalTest.java | 9 +- .../trees/PostOrderTraversalTest.java | 3 +- .../trees/PreOrderTraversalTest.java | 3 +- .../trees/VerticalOrderTraversalTest.java | 6 +- .../trees/ZigzagTraversalTest.java | 9 +- .../StrassenMatrixMultiplicationTest.java | 3 +- .../OptimalJobSchedulingTest.java | 12 +- .../geometry/GrahamScanTest.java | 4 +- .../thealgorithms/maths/ADTFractionTest.java | 3 +- .../thealgorithms/maths/AbsoluteMinTest.java | 3 +- .../maths/AbsoluteValueTest.java | 4 +- .../com/thealgorithms/maths/AreaTest.java | 45 ++---- .../maths/AutomorphicNumberTest.java | 6 +- .../maths/DistanceFormulaTest.java | 6 +- .../java/com/thealgorithms/maths/GCDTest.java | 3 +- .../maths/LiouvilleLambdaFunctionTest.java | 6 +- .../maths/MobiusFunctionTest.java | 6 +- .../thealgorithms/maths/PollardRhoTest.java | 3 +- .../maths/SquareFreeIntegerTest.java | 137 ++++-------------- .../com/thealgorithms/others/ConwayTest.java | 3 +- .../others/LowestBasePalindromeTest.java | 18 +-- .../thealgorithms/others/PasswordGenTest.java | 6 +- .../others/TestPrintMatrixInSpiralOrder.java | 6 +- .../others/cn/HammingDistanceTest.java | 9 +- .../scheduling/RRSchedulingTest.java | 3 +- .../searches/BinarySearch2dArrayTest.java | 3 +- .../searches/BreadthFirstSearchTest.java | 8 +- .../searches/QuickSelectTest.java | 16 +- ...estSearchInARowAndColWiseSortedMatrix.java | 6 +- .../com/thealgorithms/sorts/CombSortTest.java | 9 +- .../sorts/IntrospectiveSortTest.java | 3 +- .../sorts/MergeSortRecursiveTest.java | 6 +- .../com/thealgorithms/sorts/SlowSortTest.java | 6 +- .../thealgorithms/sorts/StrandSortTest.java | 6 +- .../sorts/TopologicalSortTest.java | 3 +- .../com/thealgorithms/sorts/TreeSortTest.java | 12 +- .../strings/HammingDistanceTest.java | 3 +- .../strings/HorspoolSearchTest.java | 3 +- .../LetterCombinationsOfPhoneNumberTest.java | 4 +- .../thealgorithms/strings/PalindromeTest.java | 6 +- .../thealgorithms/strings/PangramTest.java | 6 +- 188 files changed, 661 insertions(+), 1133 deletions(-) create mode 100644 .clang-format create mode 100644 .github/workflows/clang-format-lint.yml delete mode 100644 .github/workflows/prettify.yml diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..1ae91b6b --- /dev/null +++ b/.clang-format @@ -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 +... diff --git a/.github/workflows/clang-format-lint.yml b/.github/workflows/clang-format-lint.yml new file mode 100644 index 00000000..7e7de570 --- /dev/null +++ b/.github/workflows/clang-format-lint.yml @@ -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 \ No newline at end of file diff --git a/.github/workflows/prettify.yml b/.github/workflows/prettify.yml deleted file mode 100644 index a5d7c318..00000000 --- a/.github/workflows/prettify.yml +++ /dev/null @@ -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 }} diff --git a/DIRECTORY.md b/DIRECTORY.md index 6f246ff1..d19c59d9 100644 --- a/DIRECTORY.md +++ b/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) diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index 21bb5a12..0de145f6 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.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++) { diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java index b840f6ad..8122ed4d 100644 --- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java +++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java @@ -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 localPathList) { + private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List localPathList) { if (u.equals(d)) { nm.add(new ArrayList<>(localPathList)); @@ -87,8 +86,7 @@ public class AllPathsFromSourceToTarget { } // Driver program - public static List> allPathsFromSourceToTarget( - int vertices, int[][] a, int source, int destination) { + public static List> 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++) { diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index 7c45dffb..70ae32b5 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -37,8 +37,7 @@ public class Combination { * @param result the list contains all combination. * @param the type of elements in the array. */ - private static void backtracking( - T[] arr, int index, TreeSet currSet, List> result) { + private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) { if (index + length - currSet.size() > arr.length) return; if (length - 1 == currSet.size()) { for (int i = index; i < arr.length; i++) { diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java index 6d45a73a..632d5441 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -47,8 +47,7 @@ public class NQueens { List> arrangements = new ArrayList>(); 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> solutions, int[] columns, int columnIndex) { + private static void getSolution(int boardSize, List> solutions, int[] columns, int columnIndex) { if (columnIndex == boardSize) { // this means that all queens have been placed List sol = new ArrayList(); diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java index 46886cbc..e310d718 100644 --- a/src/main/java/com/thealgorithms/ciphers/AES.java +++ b/src/main/java/com/thealgorithms/ciphers/AES.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index c010d532..2b12aeaa 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -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()); diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index bce7f699..fc7c5d04 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java index 6011909a..61c444cf 100644 --- a/src/main/java/com/thealgorithms/ciphers/Caesar.java +++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java index 70b1f7ea..89a0a886 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -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(); diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java index b6ca8fb8..119ad697 100644 --- a/src/main/java/com/thealgorithms/ciphers/DES.java +++ b/src/main/java/com/thealgorithms/ciphers/DES.java @@ -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 } } diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index e28eaecb..aea15c35 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -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()); } /** diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index 809f8507..b7d36db5 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java @@ -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(); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java index 148a49cf..2e924980 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java index 2d0309a9..12e93717 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java @@ -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); } } diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java index c6450a45..7a87fd15 100644 --- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java @@ -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!"); diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java index a77be2f5..31ef2bff 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java @@ -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(); } diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java index 69707c80..2a57fbde 100644 --- a/src/main/java/com/thealgorithms/conversions/HexToOct.java +++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java @@ -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 diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java index dc731006..ca64c3ff 100644 --- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java +++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java @@ -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; diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java index 39e0c443..d991f5f3 100644 --- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java +++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java index ea75e067..8cd28378 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java @@ -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 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 path, int estimated) { this.distance = distance; @@ -153,12 +150,8 @@ public class A_Star { }; Graph graph = new Graph(20); - ArrayList 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 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 queue = new PriorityQueue<>( - Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); + PriorityQueue 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 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()])); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index 2998f7e9..8229c1fa 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -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; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java index 0bdc5340..a4827d88 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java @@ -16,8 +16,7 @@ import java.util.Arrays; */ public class BipartiteGrapfDFS { - private static boolean bipartite( - int V, ArrayList> adj, int[] color, int node) { + private static boolean bipartite(int V, ArrayList> adj, int[] color, int node) { if (color[node] == -1) { color[node] = 1; } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java index 1811d4a1..59f0d011 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java @@ -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]; } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index 673b795b..b295fb08 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -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 - // new shortest distance // if the new - // distance calculated is less then the - // earlier shortest - DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] - + DistanceMatrix[intermediate][destination]; + 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]; } } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java index d4d6a381..0016abef 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java @@ -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,10 +14,11 @@ 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 + * for which hamiltonian path is to be found * @return Array containing hamiltonian cycle - * else returns 1D array with value -1. + * else returns 1D array with value -1. */ public int[] findHamiltonianCycle(int[][] graph) { this.V = graph.length; @@ -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; } @@ -69,7 +72,7 @@ public class HamiltonianCycle { this.graph[vertex][v] = 0; this.graph[v][vertex] = 0; - /** if vertex not already selected solve recursively **/ + /** if vertex not already selected solve recursively **/ if (!isPresent(v)) { return isPathFound(v); } @@ -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) { diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index 3c41a30b..bf5afcd1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -74,8 +74,7 @@ public class Kruskal { // captain of i, stores the set with all the connected nodes to i HashSet[] connectedGroups = new HashSet[nodes]; HashSet[] minGraph = new HashSet[nodes]; - PriorityQueue edges - = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); + PriorityQueue 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 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java index 701eec60..0348a60b 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java @@ -258,9 +258,8 @@ 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 - // currentVertex and the vertex + 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,9 +308,8 @@ 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 - // edge exists between the current vertex and the + 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); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java index e1876289..e61e2b6a 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java @@ -70,10 +70,9 @@ 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 - // false for vertices not yet included in MST // graph[u][v] is non zero only - // for adjacent vertices of m + 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 { if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) { parent[v] = u; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java index e63de0ad..4390a2f1 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java @@ -83,15 +83,13 @@ public class TarjansAlgorithm { Stack st = new Stack(); 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 st, List> graph) { + private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack st, List> graph) { // Initialize insertion time and lowTime value of current node insertionTime[u] = Time; diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java index d4f8cda9..74b2527f 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -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)); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index 34afa420..4aa7db19 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index be5e42c9..7c457a34 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 591b4439..faf9fb92 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -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); } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index 5c2cb5cc..288a1932 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -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); } } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 74aa4b8b..1fa43328 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -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 { diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java index 6a079ac8..33e3fd7c 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java @@ -203,9 +203,7 @@ public class SkipList> { 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> { 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; } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java index 7fa769c6..8b33e08c 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java @@ -123,8 +123,7 @@ public class LinkedQueue implements Iterable { */ 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 node = front; while (pos-- > 0) node = node.next; return node.data; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java index a0d36413..ec6c8414 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java @@ -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', diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java index 19fbb6a8..c034452f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java @@ -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)); } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java index bb592bd4..0df93cef 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java @@ -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; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java index 5c08a002..8303c658 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java @@ -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 inorderMap, final int preStart, final int inStart, - final int size) { + private static Node createTreeOptimized(final Integer[] preorder, final Map 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; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index f0f8fac8..577c0055 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -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 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; } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java index d7bdb0af..26d3a844 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java @@ -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> adj, int s, int p, int[] parent, int[] depth) { + private static void dfs(ArrayList> adj, int s, int p, int[] parent, int[] depth) { for (int adjacent : adj.get(s)) { if (adjacent != p) { parent[adjacent] = s; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java index fbb51701..ebdcba40 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java index d7674f4a..29562833 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java @@ -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]*/ diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index bfd30f9f..1575e364 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -53,8 +53,7 @@ public class LargeTreeNode extends TreeNode { * @param childNodes {@link Collection} of child Nodes. * @see TreeNode#TreeNode(Object, Node) */ - public LargeTreeNode( - E data, LargeTreeNode parentNode, Collection> childNodes) { + public LargeTreeNode(E data, LargeTreeNode parentNode, Collection> childNodes) { super(data, parentNode); this.childNodes = childNodes; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index 61f430bd..215f01a6 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -57,8 +57,7 @@ public class SimpleTreeNode extends TreeNode { * @param rightNode Value to which the nodes' right child reference will be * set. */ - public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode, - SimpleTreeNode rightNode) { + public SimpleTreeNode(E data, SimpleTreeNode parentNode, SimpleTreeNode leftNode, SimpleTreeNode rightNode) { super(data, parentNode); this.leftNode = leftNode; this.rightNode = rightNode; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index d09d2d9b..52d7bffa 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -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); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java index 5b17a101..77d997fc 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java @@ -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)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index 7d74e2a8..b5be0b26 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -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)); } /** diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java index bba63729..68877811 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java @@ -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(); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java index 161a910b..290e98ca 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java @@ -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)); } } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java index 23222bec..c4c9bbee 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java @@ -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]); } } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java index 68fd6edb..c40d9110 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java @@ -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 { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java index b1bf3152..ed9ccd8c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index 52ffaf19..640985a2 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -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,15 +74,13 @@ public class OptimalJobScheduling { return Run[process][machine]; else { - int[] runningCosts - = new int[numberMachines]; // stores the costs of executing our Process depending on - // the Machine the previous one was executed + 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 - // the Process to our Machine + 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 } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java index 00a9bda2..2ef7d61a 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java @@ -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(); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java index 57a47078..cc90e56f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java @@ -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)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java index dd358428..b7eb029e 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java @@ -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)); } } diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java index 8bd96cc9..7909eaa9 100644 --- a/src/main/java/com/thealgorithms/io/BufferedReader.java +++ b/src/main/java/com/thealgorithms/io/BufferedReader.java @@ -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]; } diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java index 1ffd3d67..a85ef090 100644 --- a/src/main/java/com/thealgorithms/maths/ADTFraction.java +++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java index a8796ae4..97d37dd9 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index b9c7d381..daf02f14 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index f5247083..ea9cd672 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -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))); } /** diff --git a/src/main/java/com/thealgorithms/maths/Area.java b/src/main/java/com/thealgorithms/maths/Area.java index b4bae5ae..262669fe 100644 --- a/src/main/java/com/thealgorithms/maths/Area.java +++ b/src/main/java/com/thealgorithms/maths/Area.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java index 55c4864f..1e5eb32f 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java index 5e7271a6..4009b79e 100644 --- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java +++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java @@ -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)); } } diff --git a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java index b66499b3..f01e029b 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -38,10 +38,8 @@ public class CircularConvolutionFFT { * @param b The other signal. * @return The convolved signal. */ - public static ArrayList fftCircularConvolution( - ArrayList a, ArrayList 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 fftCircularConvolution(ArrayList a, ArrayList 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); diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index cacde4b8..b761092a 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -42,8 +42,7 @@ public class ConvolutionFFT { * @param b The other signal. * @return The convolved signal. */ - public static ArrayList convolutionFFT( - ArrayList a, ArrayList b) { + public static ArrayList convolutionFFT(ArrayList a, ArrayList 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,9 +57,8 @@ 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 - // from + convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came + // from // paddingPowerOfTwo() method inside the fft() method. return convolved; diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index a5c5cf8d..336e23dd 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -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 differentialEquation) { + public static double eulerStep(double xCurrent, double stepSize, double yCurrent, BiFunction 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 eulerFull(double xStart, double xEnd, double stepSize, - double yStart, BiFunction differentialEquation) { + public static ArrayList eulerFull(double xStart, double xEnd, double stepSize, double yStart, BiFunction differentialEquation) { if (xStart >= xEnd) { throw new IllegalArgumentException("xEnd should be greater than xStart"); } diff --git a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java index 72e89f09..84322b6d 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java @@ -25,24 +25,15 @@ public class FibonacciJavaStreams { return Optional.of(BigDecimal.ONE); } - final List 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 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 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"))); } } } diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index 2db05939..d2283dc1 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -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)); diff --git a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java index 54cda155..2d00cc55 100644 --- a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java +++ b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java @@ -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; diff --git a/src/main/java/com/thealgorithms/maths/MatrixUtil.java b/src/main/java/com/thealgorithms/maths/MatrixUtil.java index 6fc5252f..f3d0efea 100644 --- a/src/main/java/com/thealgorithms/maths/MatrixUtil.java +++ b/src/main/java/com/thealgorithms/maths/MatrixUtil.java @@ -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 operate(final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2, - final BiFunction operation) { + public static Optional operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, final BiFunction operation) { if (!hasEqualSizes(matrix1, matrix2)) { return Optional.empty(); } @@ -39,29 +35,25 @@ public class MatrixUtil { final BigDecimal[][] result = new BigDecimal[rowSize][columnSize]; - IntStream.range(0, rowSize) - .forEach(rowIndex -> IntStream.range(0, columnSize).forEach(columnIndex -> { - final BigDecimal value1 = matrix1[rowIndex][columnIndex]; - final BigDecimal value2 = matrix2[rowIndex][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]; - result[rowIndex][columnIndex] = operation.apply(value1, value2); - })); + result[rowIndex][columnIndex] = operation.apply(value1, value2); + })); return Optional.of(result); } - public static Optional add( - final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::add); } - public static Optional subtract( - final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::subtract); } - public static Optional multiply( - final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + public static Optional multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { if (!canMultiply(matrix1, matrix2)) { return Optional.empty(); } @@ -77,23 +69,21 @@ public class MatrixUtil { .forEach(rowIndex -> IntStream.range(0, matrix2ColumnSize) .forEach(columnIndex - -> result[rowIndex][columnIndex] - = IntStream.range(0, size) - .mapToObj(index -> { - final BigDecimal value1 = matrix1[rowIndex][index]; - final BigDecimal value2 = matrix2[index][columnIndex]; + -> result[rowIndex][columnIndex] = IntStream.range(0, size) + .mapToObj(index -> { + final BigDecimal value1 = matrix1[rowIndex][index]; + final BigDecimal value2 = matrix2[index][columnIndex]; - return value1.multiply(value2); - }) - .reduce(BigDecimal.ZERO, BigDecimal::add))); + return value1.multiply(value2); + }) + .reduce(BigDecimal.ZERO, BigDecimal::add))); return Optional.of(result); } 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)}, diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java index 994b9b0c..89bc4225 100644 --- a/src/main/java/com/thealgorithms/maths/Median.java +++ b/src/main/java/com/thealgorithms/maths/Median.java @@ -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]; } } diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java index e2847bcc..5db4a1a1 100644 --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java @@ -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(); } diff --git a/src/main/java/com/thealgorithms/maths/Perimeter.java b/src/main/java/com/thealgorithms/maths/Perimeter.java index 15d032b0..e3476afa 100644 --- a/src/main/java/com/thealgorithms/maths/Perimeter.java +++ b/src/main/java/com/thealgorithms/maths/Perimeter.java @@ -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; diff --git a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java index f14415c3..0caa2862 100644 --- a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java +++ b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java @@ -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]); } } diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 98a9ac0c..bd3e4113 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -22,9 +22,8 @@ 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 - // is the precision value taken over here. + 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); } diff --git a/src/main/java/com/thealgorithms/maths/SumOfDigits.java b/src/main/java/com/thealgorithms/maths/SumOfDigits.java index 6ffc20ac..09b690fa 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/SumOfDigits.java @@ -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; } /** diff --git a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java index 5bae51d5..0e2fe9e7 100644 --- a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java +++ b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java index 78487660..aa255832 100644 --- a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java @@ -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; } diff --git a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java index cfd4ccbd..4b30155b 100644 --- a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java +++ b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java @@ -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); } diff --git a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java index b0da6cba..f7767d54 100644 --- a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java +++ b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java @@ -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."; diff --git a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java index b9e6fbb7..af2ca4dd 100644 --- a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java +++ b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/misc/WordBoggle.java b/src/main/java/com/thealgorithms/misc/WordBoggle.java index 5513bdc5..0dfbd89d 100644 --- a/src/main/java/com/thealgorithms/misc/WordBoggle.java +++ b/src/main/java/com/thealgorithms/misc/WordBoggle.java @@ -26,8 +26,7 @@ public class WordBoggle { public static void main(String[] args) { // Testcase - List ans = new ArrayList<>( - Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board")); + List 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 finalWords) { + public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, Set finalWords) { if (visited[i][j]) { return; } diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index f6a28729..3fbb4f9f 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -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(); } diff --git a/src/main/java/com/thealgorithms/others/Damm.java b/src/main/java/com/thealgorithms/others/Damm.java index ac480b93..a32ae246 100644 --- a/src/main/java/com/thealgorithms/others/Damm.java +++ b/src/main/java/com/thealgorithms/others/Damm.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java index c2f865d4..4886dc4c 100644 --- a/src/main/java/com/thealgorithms/others/Dijkstra.java +++ b/src/main/java/com/thealgorithms/others/Dijkstra.java @@ -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 diff --git a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java index 88951765..05093787 100644 --- a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java +++ b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java @@ -7,8 +7,7 @@ import java.util.Set; public class HappyNumbersSeq { - private static final Set CYCLE_NUMS - = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); + private static final Set CYCLE_NUMS = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); public static void main(String[] args) { Scanner in = new Scanner(System.in); diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index 91070920..8395b1f4 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -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 initialVectors = new ArrayList(); 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 vectors, int imageWidth, int imageHeight) { - BufferedImage image - = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); + private static BufferedImage GetImage(ArrayList vectors, int imageWidth, int imageHeight) { + BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Set the background white diff --git a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java index f16946dc..346ae9f8 100644 --- a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java +++ b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java @@ -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()); } diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 269250ba..fd5433ca 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -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) { diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 8dcaed2b..e60d5c02 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -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()); } } diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index a74d4cc8..1f5f455f 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -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 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 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 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 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; diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index 539b9dd2..2672dc6f 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -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; diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java index 6cd5a08d..fa85e970 100644 --- a/src/main/java/com/thealgorithms/others/PageRank.java +++ b/src/main/java/com/thealgorithms/others/PageRank.java @@ -10,8 +10,7 @@ class PageRank { System.out.print("Enter the Number of WebPages: "); nodes = in.nextInt(); PageRank p = new PageRank(); - System.out.println( - "Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); + System.out.println("Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: "); for (i = 1; i <= nodes; i++) { for (j = 1; j <= nodes; j++) { p.path[i][j] = in.nextInt(); @@ -36,8 +35,7 @@ class PageRank { int k = 1; // For Traversing int ITERATION_STEP = 1; InitialPageRank = 1 / totalNodes; - System.out.printf(" Total Number of Nodes :" + totalNodes - + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); + System.out.printf(" Total Number of Nodes :" + totalNodes + "\t Initial PageRank of All Nodes :" + InitialPageRank + "\n"); // 0th ITERATION _ OR _ INITIALIZATION PHASE // for (k = 1; k <= totalNodes; k++) { @@ -57,12 +55,10 @@ class PageRank { } for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { - for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; - ExternalNodeNumber++) { + for (ExternalNodeNumber = 1; ExternalNodeNumber <= totalNodes; ExternalNodeNumber++) { if (this.path[ExternalNodeNumber][InternalNodeNumber] == 1) { k = 1; - OutgoingLinks - = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber + OutgoingLinks = 0; // Count the Number of Outgoing Links for each ExternalNodeNumber while (k <= totalNodes) { if (this.path[ExternalNodeNumber][k] == 1) { OutgoingLinks = OutgoingLinks + 1; // Counter for Outgoing Links @@ -70,8 +66,7 @@ class PageRank { k = k + 1; } // Calculate PageRank - this.pagerank[InternalNodeNumber] - += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); + this.pagerank[InternalNodeNumber] += TempPageRank[ExternalNodeNumber] * (1 / OutgoingLinks); } } System.out.printf("\n After " + ITERATION_STEP + "th Step \n"); diff --git a/src/main/java/com/thealgorithms/others/PerlinNoise.java b/src/main/java/com/thealgorithms/others/PerlinNoise.java index a979c514..2f774e16 100644 --- a/src/main/java/com/thealgorithms/others/PerlinNoise.java +++ b/src/main/java/com/thealgorithms/others/PerlinNoise.java @@ -17,8 +17,7 @@ public class PerlinNoise { * @param seed used for randomizer * @return float array containing calculated "Perlin-Noise" values */ - static float[][] generatePerlinNoise( - int width, int height, int octaveCount, float persistence, long seed) { + static float[][] generatePerlinNoise(int width, int height, int octaveCount, float persistence, long seed) { final float[][] base = new float[width][height]; final float[][] perlinNoise = new float[width][height]; final float[][][] noiseLayers = new float[octaveCount][][]; diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java index 6c5a0b7b..6b766dc3 100644 --- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java +++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java @@ -141,8 +141,7 @@ public class QueueUsingTwoStacks { System.out.println(myQueue.isEmpty()); // Will print false System.out.println(myQueue.remove()); // Will print 1 - System.out.println( - (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL + System.out.println((myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL // instack: [] // outStack: [(top) 2, 3, 4] diff --git a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java index 9c26dffa..0d8cbea0 100644 --- a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java +++ b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java @@ -8,8 +8,7 @@ public class ReturnSubsequence { System.out.println("Enter String: "); Scanner s = new Scanner(System.in); String givenString = s.next(); // given string - String[] subsequence - = returnSubsequence(givenString); // calling returnSubsequence() function + String[] subsequence = returnSubsequence(givenString); // calling returnSubsequence() function System.out.println("Subsequences : "); // print the given array of subsequences for (int i = 0; i < subsequence.length; i++) { @@ -29,20 +28,17 @@ public class ReturnSubsequence { ans[0] = ""; return ans; } - String[] SmallAns = returnSubsequence(givenString.substring( - 1)); // recursive call to get subsequences of substring starting from index + String[] SmallAns = returnSubsequence(givenString.substring(1)); // recursive call to get subsequences of substring starting from index // position=1 - String[] ans = new String[2 - * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns + String[] ans = new String[2 * SmallAns.length]; // Our answer will be an array off string of size=2*SmallAns int i = 0; for (; i < SmallAns.length; i++) { ans[i] = SmallAns[i]; // Copying all the strings present in SmallAns to ans string array } for (int k = 0; k < SmallAns.length; k++) { - ans[k + SmallAns.length] - = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given - // substring in front of every string + ans[k + SmallAns.length] = givenString.charAt(0) + SmallAns[k]; // Insert character at index=0 of the given + // substring in front of every string // in SmallAns } return ans; diff --git a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java index 39669373..ec014ecf 100644 --- a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java @@ -30,8 +30,7 @@ public class SieveOfEratosthenes { } } - int primesCount - = (int) Arrays.stream(numbers).filter(element -> element == Type.PRIME).count(); + int primesCount = (int) Arrays.stream(numbers).filter(element -> element == Type.PRIME).count(); int[] primes = new int[primesCount]; int primeIndex = 0; diff --git a/src/main/java/com/thealgorithms/others/SkylineProblem.java b/src/main/java/com/thealgorithms/others/SkylineProblem.java index 3314f6d9..149adf43 100644 --- a/src/main/java/com/thealgorithms/others/SkylineProblem.java +++ b/src/main/java/com/thealgorithms/others/SkylineProblem.java @@ -18,8 +18,7 @@ public class SkylineProblem { for (int i = 0; i < num; i++) { String input = sc.next(); String[] data = input.split(","); - this.add( - Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); + this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); } this.print(this.findSkyline(0, num - 1)); diff --git a/src/main/java/com/thealgorithms/others/TopKWords.java b/src/main/java/com/thealgorithms/others/TopKWords.java index 6473c173..664a3ec9 100644 --- a/src/main/java/com/thealgorithms/others/TopKWords.java +++ b/src/main/java/com/thealgorithms/others/TopKWords.java @@ -64,8 +64,7 @@ public class TopKWords { public static void main(String[] args) { // you can replace the filePath with yours CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); - Map dictionary - = cw.getDictionary(); // get the words dictionary: {word: frequency} + Map dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency} // we change the map to list for convenient sort List> list = new ArrayList<>(dictionary.entrySet()); diff --git a/src/main/java/com/thealgorithms/others/Verhoeff.java b/src/main/java/com/thealgorithms/others/Verhoeff.java index a783aceb..2144f373 100644 --- a/src/main/java/com/thealgorithms/others/Verhoeff.java +++ b/src/main/java/com/thealgorithms/others/Verhoeff.java @@ -153,8 +153,7 @@ public class Verhoeff { private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(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) { diff --git a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java index f57ee5c6..e73937f6 100644 --- a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java @@ -30,8 +30,7 @@ public class FCFSScheduling { int waitingTime = 0; int burstTime = processes.get(0).getBurstTime(); - processes.get(0).setWaitingTime( - waitingTime); // for the first process, waiting time will be 0. + processes.get(0).setWaitingTime(waitingTime); // for the first process, waiting time will be 0. for (int i = 1; i < processesNumber; i++) { processes.get(i).setWaitingTime(waitingTime + burstTime); @@ -42,8 +41,7 @@ public class FCFSScheduling { private void evaluateTurnAroundTime() { for (int i = 0; i < processes.size(); i++) { - processes.get(i).setTurnAroundTimeTime( - processes.get(i).getBurstTime() + processes.get(i).getWaitingTime()); + processes.get(i).setTurnAroundTimeTime(processes.get(i).getBurstTime() + processes.get(i).getWaitingTime()); } } } diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java index e34cb787..9968f172 100644 --- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java @@ -63,8 +63,7 @@ public class RRScheduling { currentTime += quantumTime; } else { currentTime += remainingBurstTime[index]; - processes.get(index).setTurnAroundTimeTime( - currentTime - processes.get(index).getArrivalTime()); + processes.get(index).setTurnAroundTimeTime(currentTime - processes.get(index).getArrivalTime()); completed++; remainingBurstTime[index] = 0; } @@ -72,8 +71,7 @@ public class RRScheduling { // If some process has arrived when this process was executing, insert them into the // queue. for (int i = 1; i < processesNumber; i++) { - if (remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime - && mark[i] == 0) { + if (remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime && mark[i] == 0) { mark[i] = 1; queue.add(i); } @@ -97,8 +95,6 @@ public class RRScheduling { } private void evaluateWaitingTime() { - for (int i = 0; i < processes.size(); i++) - processes.get(i).setWaitingTime( - processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime()); + for (int i = 0; i < processes.size(); i++) processes.get(i).setWaitingTime(processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime()); } } diff --git a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java index 5eb8879a..2bc5f54c 100644 --- a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java @@ -53,9 +53,7 @@ public class SJFScheduling { } while (executed < size) { - while (k < size - && processes.get(k).getArrivalTime() - <= time) // here we find the processes that have arrived. + while (k < size && processes.get(k).getArrivalTime() <= time) // here we find the processes that have arrived. { ready.add(processes.get(k)); k++; diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 42502c36..22096307 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -66,11 +66,7 @@ class BinarySearch implements SearchAlgorithm { int size = 100; int maxElement = 100000; - Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[] ::new); + Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -78,11 +74,9 @@ class BinarySearch implements SearchAlgorithm { BinarySearch search = new BinarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index e2995747..e4c0cf9d 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -42,11 +42,9 @@ public class BinarySearch2dArray { if (arr[endRow][midCol] == target) return new int[] {endRow, midCol}; - if (target <= arr[startRow][midCol - 1]) - return binarySearch(arr, target, startRow, 0, midCol - 1); + if (target <= arr[startRow][midCol - 1]) return binarySearch(arr, target, startRow, 0, midCol - 1); - if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) - return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); + if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); if (target <= arr[endRow][midCol - 1]) return binarySearch(arr, target, endRow, 0, midCol - 1); diff --git a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java index feb7cf29..3a12537a 100644 --- a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java @@ -40,32 +40,22 @@ public class DepthFirstSearch { return Optional.of(node); } - return node.getSubNodes() - .stream() - .map(value -> search(value, name)) - .flatMap(Optional::stream) - .findAny(); + return node.getSubNodes().stream().map(value -> search(value, name)).flatMap(Optional::stream).findAny(); } 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)); } } public static void main(final String[] args) { - final Node rootNode = new Node("A", - List.of( - new Node("B", - List.of(new Node("D"), new Node("F", List.of(new Node("H"), new Node("I"))))), - new Node("C", List.of(new Node("G"))), new Node("E"))); + final Node rootNode = new Node("A", List.of(new Node("B", List.of(new Node("D"), new Node("F", List.of(new Node("H"), new Node("I"))))), new Node("C", List.of(new Node("G"))), new Node("E"))); { final String expected = "I"; - final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + final Node result = search(rootNode, expected).orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -73,8 +63,7 @@ public class DepthFirstSearch { { final String expected = "G"; - final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + final Node result = search(rootNode, expected).orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -82,8 +71,7 @@ public class DepthFirstSearch { { final String expected = "E"; - final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + final Node result = search(rootNode, expected).orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java index f3b86849..a856bd65 100644 --- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java +++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java @@ -14,11 +14,7 @@ class ExponentialSearch implements SearchAlgorithm { int size = 100; int maxElement = 100000; - Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[] ::new); + Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -26,12 +22,10 @@ class ExponentialSearch implements SearchAlgorithm { ExponentialSearch search = new ExponentialSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } @Override diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index 041802cf..4fba6e25 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -66,7 +66,6 @@ public class FibonacciSearch implements SearchAlgorithm { FibonacciSearch fsearch = new FibonacciSearch(); int atIndex = fsearch.find(integers, shouldBeFound); - System.out.println("Should be found: " + shouldBeFound + ". Found " + integers[atIndex] - + " at index " + atIndex + ". An array length " + size); + System.out.println("Should be found: " + shouldBeFound + ". Found " + integers[atIndex] + " at index " + atIndex + ". An array length " + size); } } diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java index 282e7309..215ecdef 100644 --- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java +++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java @@ -30,8 +30,7 @@ class InterpolationSearch { while (start <= end && key >= array[start] && key <= array[end]) { // Probing the position with keeping // uniform distribution in mind. - int pos - = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); + int pos = start + (((end - start) / (array[end] - array[start])) * (key - array[start])); // Condition of target found if (array[pos] == key) { @@ -54,8 +53,7 @@ class InterpolationSearch { Random r = new Random(); int size = 100; int maxElement = 100000; - int[] integers - = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); + int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); // the element that should be found int shouldBeFound = integers[r.nextInt(size - 1)]; @@ -63,11 +61,9 @@ class InterpolationSearch { InterpolationSearch search = new InterpolationSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java index 7fa6a37c..324b8f58 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -58,10 +58,7 @@ public final class IterativeBinarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[] ::new); + Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -69,11 +66,9 @@ public final class IterativeBinarySearch implements SearchAlgorithm { IterativeBinarySearch search = new IterativeBinarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java index efff17c9..e78acd6a 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java @@ -56,10 +56,7 @@ public class IterativeTernarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[] ::new); + Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -67,11 +64,9 @@ public class IterativeTernarySearch implements SearchAlgorithm { IterativeTernarySearch search = new IterativeTernarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java index 94939518..57927b30 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearch.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java @@ -42,8 +42,7 @@ public class LinearSearch implements SearchAlgorithm { Random r = new Random(); int size = 200; int maxElement = 100; - Integer[] integers - = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[] ::new); + Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -51,7 +50,6 @@ public class LinearSearch implements SearchAlgorithm { LinearSearch search = new LinearSearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); } } diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index be0f1131..ee6f51e6 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -33,11 +33,7 @@ class LowerBound implements SearchAlgorithm { int size = 100; int maxElement = 100000; - Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[] ::new); + Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element for which the lower bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -45,12 +41,10 @@ class LowerBound implements SearchAlgorithm { LowerBound search = new LowerBound(); int atIndex = search.find(integers, val); - System.out.printf("Val: %d. Lower Bound Found %d at index %d. An array length %d%n", val, - integers[atIndex], atIndex, size); + System.out.printf("Val: %d. Lower Bound Found %d at index %d. An array length %d%n", val, integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val; - System.out.printf( - "Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); + System.out.printf("Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index 4ba8110c..58afc8df 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -78,8 +78,7 @@ public class MonteCarloTreeSearch { winnerNode = getWinnerNode(rootNode); printScores(rootNode); - System.out.format( - "\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1); + System.out.format("\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1); return winnerNode; } @@ -119,10 +118,7 @@ public class MonteCarloTreeSearch { break; } - uctTemp = ((double) childNode.score / childNode.visitCount) - + 1.41 - * Math.sqrt( - Math.log(promisingNode.visitCount) / (double) childNode.visitCount); + uctTemp = ((double) childNode.score / childNode.visitCount) + 1.41 * Math.sqrt(Math.log(promisingNode.visitCount) / (double) childNode.visitCount); if (uctTemp > uctIndex) { uctIndex = uctTemp; @@ -161,8 +157,7 @@ public class MonteCarloTreeSearch { tempNode.visitCount++; // Add wining scores to bouth player and opponent depending on the turn. - if ((tempNode.isPlayersTurn && isPlayerWinner) - || (!tempNode.isPlayersTurn && !isPlayerWinner)) { + if ((tempNode.isPlayersTurn && isPlayerWinner) || (!tempNode.isPlayersTurn && !isPlayerWinner)) { tempNode.score += WIN_SCORE; } @@ -178,8 +173,7 @@ public class MonteCarloTreeSearch { System.out.println("N.\tScore\t\tVisits"); for (int i = 0; i < rootNode.childNodes.size(); i++) { - System.out.printf("%02d\t%d\t\t%d%n", i + 1, rootNode.childNodes.get(i).score, - rootNode.childNodes.get(i).visitCount); + System.out.printf("%02d\t%d\t\t%d%n", i + 1, rootNode.childNodes.get(i).score, rootNode.childNodes.get(i).visitCount); } } } diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java index db8223e3..7d3e2e34 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -49,8 +49,7 @@ public final class QuickSelect { return selectIndex(list, 0, list.size() - 1, n); } - private static > int selectIndex( - List list, int left, int right, int n) { + private static > int selectIndex(List list, int left, int right, int n) { while (true) { if (left == right) return left; int pivotIndex = pivot(list, left, right); @@ -65,8 +64,7 @@ public final class QuickSelect { } } - private static > int partition( - List list, int left, int right, int pivotIndex, int n) { + private static > int partition(List list, int left, int right, int pivotIndex, int n) { T pivotValue = list.get(pivotIndex); Collections.swap(list, pivotIndex, right); int storeIndex = left; diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index e79f0e66..3395bc0b 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -66,10 +66,7 @@ public class TernarySearch implements SearchAlgorithm { Random r = new Random(); int size = 100; int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .toArray(Integer[] ::new); + Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new); // the element that should be found Integer shouldBeFound = integers[r.nextInt(size - 1)]; @@ -77,11 +74,9 @@ public class TernarySearch implements SearchAlgorithm { TernarySearch search = new TernarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", - shouldBeFound, integers[atIndex], atIndex, size); + System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size); int toCheck = Arrays.binarySearch(integers, shouldBeFound); - System.out.printf( - "Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); + System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex); } } diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java index cddd3cb8..bbce617a 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -33,11 +33,7 @@ class UpperBound implements SearchAlgorithm { int size = 100; int maxElement = 100000; - Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)) - .limit(size) - .sorted() - .boxed() - .toArray(Integer[] ::new); + Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new); // The element for which the upper bound is to be found int val = integers[r.nextInt(size - 1)] + 1; @@ -45,12 +41,10 @@ class UpperBound implements SearchAlgorithm { UpperBound search = new UpperBound(); int atIndex = search.find(integers, val); - System.out.printf("Val: %d. Upper Bound Found %d at index %d. An array length %d%n", val, - integers[atIndex], atIndex, size); + System.out.printf("Val: %d. Upper Bound Found %d at index %d. An array length %d%n", val, integers[atIndex], atIndex, size); boolean toCheck = integers[atIndex] > val || integers[size - 1] < val; - System.out.printf( - "Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); + System.out.printf("Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck); } /** diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java index c21e307c..307aa957 100644 --- a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java @@ -4,8 +4,7 @@ public class sortOrderAgnosticBinarySearch { public static int find(int[] arr, int key) { int start = 0; int end = arr.length - 1; - boolean arrDescending = arr[start] - > arr[end]; // checking for Array is in ascending order or descending order. + boolean arrDescending = arr[start] > arr[end]; // checking for Array is in ascending order or descending order. while (start <= end) { int mid = end - start / 2; if (arr[mid] == key) { diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 11c2ce18..9a9b076b 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -53,20 +53,13 @@ class CountingSort implements SortAlgorithm { * @param list The list to be sorted */ private static > List streamSort(List list) { - return list.stream() - .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) - .entrySet() - .stream() - .flatMap( - entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) - .collect(toList()); + return list.stream().collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)).entrySet().stream().flatMap(entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())).collect(toList()); } // Driver Program public static void main(String[] args) { // Integer Input - List unsortedInts - = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); + List unsortedInts = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); CountingSort countingSort = new CountingSort(); System.out.println("Before Sorting:"); @@ -81,8 +74,7 @@ class CountingSort implements SortAlgorithm { System.out.println("\n------------------------------\n"); // String Input - List unsortedStrings - = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); + List unsortedStrings = Stream.of("c", "a", "e", "b", "d", "a", "f", "g", "c").collect(toList()); System.out.println("Before Sorting:"); print(unsortedStrings); diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java index 6fabddcb..31984a15 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -26,8 +26,7 @@ public class DualPivotQuickSort implements SortAlgorithm { * @param right The last index of an array * @param array The array to be sorted */ - private static > void dualPivotQuicksort( - T[] array, int left, int right) { + private static > void dualPivotQuicksort(T[] array, int left, int right) { if (left < right) { int[] pivots = partition(array, left, right); diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java index 123f22d8..7a3cdfa3 100644 --- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java +++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java @@ -13,8 +13,7 @@ public class DutchNationalFlagSort implements SortAlgorithm { @Override public > T[] sort(T[] unsorted) { - return dutch_national_flag_sort( - unsorted, unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1]); + return dutch_national_flag_sort(unsorted, unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1]); } public > T[] sort(T[] unsorted, T intendedMiddle) { diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index c74ff316..cd160866 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -75,17 +75,14 @@ class InsertionSort implements SortAlgorithm { double insertionTime = measureApproxExecTime(insertionSort::sort, randomArray); System.out.printf("Original insertion time: %5.2f sec.\n", insertionTime); - double insertionSentinelTime - = measureApproxExecTime(insertionSort::sentinelSort, copyRandomArray); + double insertionSentinelTime = measureApproxExecTime(insertionSort::sentinelSort, copyRandomArray); System.out.printf("Sentinel insertion time: %5.2f sec.\n", insertionSentinelTime); // ~ 1.5 time sentinel sort is faster, then classical Insertion sort implementation. - System.out.printf("Sentinel insertion is %f3.2 time faster than Original insertion sort\n", - insertionTime / insertionSentinelTime); + System.out.printf("Sentinel insertion is %f3.2 time faster than Original insertion sort\n", insertionTime / insertionSentinelTime); } - private static double measureApproxExecTime( - Function sortAlgorithm, Double[] randomArray) { + private static double measureApproxExecTime(Function sortAlgorithm, Double[] randomArray) { long start = System.currentTimeMillis(); sortAlgorithm.apply(randomArray); long end = System.currentTimeMillis(); diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java index 92405d3d..36b3f8de 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java @@ -13,8 +13,7 @@ public class MergeSortNoExtraSpace { merge_sort(a, 0, n - 1, maxele); } - public static void merge_sort( - int[] a, int start, int end, int maxele) { // this function divides the array into 2 halves + public static void merge_sort(int[] a, int start, int end, int maxele) { // this function divides the array into 2 halves if (start < end) { int mid = (start + end) / 2; merge_sort(a, start, mid, maxele); diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java index 9d4a5871..f9d12a2a 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java @@ -63,8 +63,7 @@ public class MergeSortRecursive { class App { public static void main(String[] args) { - MergeSortRecursive sort = new MergeSortRecursive( - new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9))); + MergeSortRecursive sort = new MergeSortRecursive(new ArrayList<>(Arrays.asList(4, 3, 1, 8, 5, 10, 0, 1, 4, 11, 8, 9))); sort.mergeSort(); } } diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 87489b8d..2d8411fa 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -25,8 +25,7 @@ public class StrandSort { return result; } - private static > LinkedList merge( - LinkedList left, LinkedList right) { + private static > LinkedList merge(LinkedList left, LinkedList right) { LinkedList result = new LinkedList(); while (!left.isEmpty() && !right.isEmpty()) { // change the direction of this comparison to change the direction of the sort diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index be95d643..e060af54 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -108,8 +108,7 @@ public class TreeSort implements SortAlgorithm { // ==== String List ======= System.out.println("Testing for String List...."); - List stringList = List.of( - "banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"); + List stringList = List.of("banana", "berry", "orange", "grape", "peach", "cherry", "apple", "pineapple"); System.out.printf("%-10s", "unsorted: "); print(stringList); stringList = treeSort.sort(stringList); diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java index e6f7f10a..c272b820 100644 --- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java +++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java @@ -71,14 +71,12 @@ public class WiggleSort implements SortAlgorithm { if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) { T smallestValue = select(Arrays.asList(sortThis), 0); if (!(0 == smallestValue.compareTo(median))) { - throw new IllegalArgumentException( - "For odd Arrays if the median appears ceil(n/2) times, " + throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, " + "the median has to be the smallest values in the array."); } } if (numMedians > ceil(sortThis.length / 2.0)) { - throw new IllegalArgumentException( - "No more than half the number of values may be the same."); + throw new IllegalArgumentException("No more than half the number of values may be the same."); } triColorSort(sortThis, median); diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index dcfc2f85..352d2308 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -19,14 +19,10 @@ public class Anagrams { String second = "lead"; // All the below methods takes input but doesn't return any output to the main method. Anagrams nm = new Anagrams(); - System.out.println( - nm.approach2(first, second)); /* To activate methods for different approaches*/ - System.out.println( - nm.approach1(first, second)); /* To activate methods for different approaches*/ - System.out.println( - nm.approach3(first, second)); /* To activate methods for different approaches*/ - System.out.println( - nm.approach4(first, second)); /* To activate methods for different approaches*/ + System.out.println(nm.approach2(first, second)); /* To activate methods for different approaches*/ + System.out.println(nm.approach1(first, second)); /* To activate methods for different approaches*/ + System.out.println(nm.approach3(first, second)); /* To activate methods for different approaches*/ + System.out.println(nm.approach4(first, second)); /* To activate methods for different approaches*/ /** * OUTPUT : * first string ="deal" second string ="lead" diff --git a/src/main/java/com/thealgorithms/strings/CheckVowels.java b/src/main/java/com/thealgorithms/strings/CheckVowels.java index 821bca69..7b4fca3d 100644 --- a/src/main/java/com/thealgorithms/strings/CheckVowels.java +++ b/src/main/java/com/thealgorithms/strings/CheckVowels.java @@ -11,8 +11,7 @@ import java.util.Set; */ public class CheckVowels { - private static final Set VOWELS - = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); + private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); /** * Check if a string is has vowels or not diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index aa318d87..99ba2399 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -100,8 +100,7 @@ public class HorspoolSearch { return -1; } - int textIndex = pattern.length() - - 1; // align pattern with text start and get index of the last character + int textIndex = pattern.length() - 1; // align pattern with text start and get index of the last character // while pattern is not out of text bounds while (textIndex < text.length()) { @@ -111,8 +110,7 @@ public class HorspoolSearch { comparisons++; char patternChar = pattern.charAt(i); char textChar = text.charAt((textIndex + i) - (pattern.length() - 1)); - if (!charEquals( - patternChar, textChar, caseSensitive)) { // bad character, shift pattern + if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern textIndex += getShiftValue(text.charAt(textIndex)); break; } @@ -159,8 +157,7 @@ public class HorspoolSearch { patternLength = pattern.length(); HashMap table = new HashMap<>(); - for (int i = pattern.length() - 2; i >= 0; - i--) { // length - 2 is the index of the second to last character + for (int i = pattern.length() - 2; i >= 0; i--) { // length - 2 is the index of the second to last character char c = pattern.charAt(i); int finalI = i; table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI); diff --git a/src/main/java/com/thealgorithms/strings/Palindrome.java b/src/main/java/com/thealgorithms/strings/Palindrome.java index cfc4efd1..c0cab91b 100644 --- a/src/main/java/com/thealgorithms/strings/Palindrome.java +++ b/src/main/java/com/thealgorithms/strings/Palindrome.java @@ -13,8 +13,7 @@ class Palindrome { * {@code false} */ public static boolean isPalindrome(String s) { - return ( - (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString())); + return ((s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString())); } /** diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java index 9e8f31d2..0b4157b5 100644 --- a/src/main/java/com/thealgorithms/strings/StringCompression.java +++ b/src/main/java/com/thealgorithms/strings/StringCompression.java @@ -33,8 +33,7 @@ public class StringCompression { break; } else if (input.charAt(i) != input.charAt(i + 1)) { if ((i + 1) == input.length() - 1) { - compressedString = appendCount(compressedString, count, input.charAt(i)) - + input.charAt(i + 1); + compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i + 1); break; } else { compressedString = appendCount(compressedString, count, input.charAt(i)); diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java index cc6654c1..75ab8833 100644 --- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java +++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java @@ -7,8 +7,7 @@ class zigZagPattern { int start = 0, index = 0, height = 1, depth = numRows; char[] zigZagedArray = new char[s.length()]; while (depth != 0) { - int pointer = start, height_space = 2 + ((height - 2) * 2), - depth_space = 2 + ((depth - 2) * 2); + int pointer = start, height_space = 2 + ((height - 2) * 2), depth_space = 2 + ((depth - 2) * 2); boolean bool = true; while (pointer < s.length()) { zigZagedArray[index++] = s.charAt(pointer); diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java index b9de924a..ca5e2ef8 100644 --- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java +++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java @@ -13,10 +13,8 @@ public class AllPathsFromSourceToTargetTest { int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}}; int source = 2; int destination = 3; - List> list2 - = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( - vertices, a, source, destination); + List> list2 = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @@ -27,10 +25,8 @@ public class AllPathsFromSourceToTargetTest { int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}, {1, 4}, {3, 4}, {2, 4}}; int source = 0; int destination = 4; - List> list2 = List.of(List.of(0, 1, 3, 4), List.of(0, 1, 4), - List.of(0, 2, 1, 3, 4), List.of(0, 2, 1, 4), List.of(0, 2, 4), List.of(0, 3, 4)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( - vertices, a, source, destination); + List> list2 = List.of(List.of(0, 1, 3, 4), List.of(0, 1, 4), List.of(0, 2, 1, 3, 4), List.of(0, 2, 1, 4), List.of(0, 2, 4), List.of(0, 3, 4)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @@ -38,14 +34,11 @@ public class AllPathsFromSourceToTargetTest { @Test void testForThirdCase() { int vertices = 6; - int[][] a = {{1, 0}, {2, 3}, {0, 4}, {1, 5}, {4, 3}, {0, 2}, {0, 3}, {1, 2}, {0, 5}, {3, 4}, - {2, 5}, {2, 4}}; + int[][] a = {{1, 0}, {2, 3}, {0, 4}, {1, 5}, {4, 3}, {0, 2}, {0, 3}, {1, 2}, {0, 5}, {3, 4}, {2, 5}, {2, 4}}; int source = 1; int destination = 5; - List> list2 - = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( - vertices, a, source, destination); + List> list2 = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } @@ -57,8 +50,7 @@ public class AllPathsFromSourceToTargetTest { int source = 0; int destination = 2; List> list2 = List.of(List.of(0, 1, 2), List.of(0, 2)); - List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( - vertices, a, source, destination); + List> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices, a, source, destination); list2 = list1; assertIterableEquals(list1, list2); } diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java index ab7eff71..9158d0e1 100644 --- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java +++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java @@ -104,8 +104,7 @@ class CircularBufferTest { private void shutDownExecutorSafely(ExecutorService executorService) { try { - if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) - executorService.shutdownNow(); + if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) executorService.shutdownNow(); } catch (InterruptedException e) { executorService.shutdownNow(); } diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java index fb45fa56..794b38d1 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java @@ -73,8 +73,7 @@ class SkipListTest { Arrays.stream(values).forEach(skipList::add); print(skipList); - String[] actualOrder - = IntStream.range(0, values.length).mapToObj(skipList::get).toArray(String[] ::new); + String[] actualOrder = IntStream.range(0, values.length).mapToObj(skipList::get).toArray(String[] ::new); assertArrayEquals(new String[] {"a", "b", "c", "d"}, actualOrder); } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java index db444e7d..bf7b9461 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java @@ -29,8 +29,7 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeIsBST() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 20}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -43,8 +42,7 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeWithDuplicatedNodesIsNotBST() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 13}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 13}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -57,8 +55,7 @@ public class CheckBinaryTreeIsValidBSTTest { */ @Test public void testBinaryTreeIsNotBST() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 12}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {9, 7, 13, 3, 8, 10, 12}); assertFalse(CheckBinaryTreeIsValidBST.isBST(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java index 53297768..10f7aa66 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java @@ -12,8 +12,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { public void testOnNullArraysShouldReturnNullTree() { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(null, null); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null); // then Assertions.assertNull(root); @@ -28,8 +27,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then Assertions.assertNull(root); @@ -44,8 +42,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -60,8 +57,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -76,8 +72,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); @@ -92,8 +87,7 @@ public class CreateBinaryTreeFromInorderPreorderTest { // when BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder); - BinaryTree.Node rootOpt - = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); + BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder); // then checkTree(preorder, inorder, root); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java index 2b85cf0c..e65beb89 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java @@ -43,8 +43,7 @@ public class InorderTraversalTest { */ @Test public void testRecursiveInorderNonBalanced() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, InorderTraversal.recursiveInorder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java index d8f5ed92..ee807bcc 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java @@ -31,8 +31,7 @@ public class LevelOrderTraversalTest { @Test public void testLevelOrderTraversalCompleteTree() { final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); - assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), - LevelOrderTraversal.traverse(root)); + assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7)), LevelOrderTraversal.traverse(root)); } /* @@ -46,9 +45,7 @@ public class LevelOrderTraversalTest { */ @Test public void testLevelOrderTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); - assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7), List.of(8, 9)), - LevelOrderTraversal.traverse(root)); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + assertEquals(List.of(List.of(1), List.of(2, 3), List.of(4, 5, 6, 7), List.of(8, 9)), LevelOrderTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java index 1104aa24..3acc7f07 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java @@ -45,8 +45,7 @@ public class PostOrderTraversalTest { */ @Test public void testPostOrderNonBalanced() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(8, 7, 6, 5); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java index 4e1f7102..b194da01 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java @@ -43,8 +43,7 @@ public class PreOrderTraversalTest { */ @Test public void testRecursivePreOrderNonBalanced() { - final BinaryTree.Node root - = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {5, null, 6, null, 7, null, 8}); List expected = List.of(5, 6, 7, 8); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java index 4b80a308..cc89c981 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java @@ -45,9 +45,7 @@ public class VerticalOrderTraversalTest { */ @Test public void testVerticalTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); - assertEquals( - List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root)); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + assertEquals(List.of(4, 2, 8, 1, 5, 6, 3, 9, 7), VerticalOrderTraversal.verticalTraversal(root)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java index 5ac0012b..eb5c0e3c 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java @@ -31,8 +31,7 @@ public class ZigzagTraversalTest { @Test public void testZigzagTraversalCompleteTree() { final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); - assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), - ZigzagTraversal.traverse(root)); + assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7)), ZigzagTraversal.traverse(root)); } /* @@ -46,9 +45,7 @@ public class ZigzagTraversalTest { */ @Test public void testZigzagTraversalDifferentHeight() { - final BinaryTree.Node root = TreeTestUtils.createTree( - new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); - assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7), List.of(9, 8)), - ZigzagTraversal.traverse(root)); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7, null, null, 8, null, null, 9}); + assertEquals(List.of(List.of(1), List.of(3, 2), List.of(4, 5, 6, 7), List.of(9, 8)), ZigzagTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java index 7fb4f178..bbf91cfb 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java @@ -33,8 +33,7 @@ class StrassenMatrixMultiplicationTest { void StrassenMatrixMultiplicationTestNegetiveNumber4x4() { int[][] A = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] B = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}}; - int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, - {272, -270, -268, 106}}; + int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, {272, -270, -268, 106}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java index 7e673ed7..a00d3e89 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java @@ -19,8 +19,7 @@ public class OptimalJobSchedulingTest { int[][] Transfer = {{0, 1, 2, 4}, {1, 0, 2, 3}, {2, 2, 0, 1}, {4, 3, 1, 0}}; - OptimalJobScheduling opt - = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); + OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); @@ -45,8 +44,7 @@ public class OptimalJobSchedulingTest { int[][] Transfer = {{0, 1, 2}, {1, 0, 2}, {2, 2, 0}}; - OptimalJobScheduling opt - = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); + OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); @@ -83,13 +81,11 @@ public class OptimalJobSchedulingTest { {1, 3, 2, 0}, }; - OptimalJobScheduling opt - = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); + OptimalJobScheduling opt = new OptimalJobScheduling(numberProcesses, numberMachines, Run, Transfer); opt.execute(); - int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 3}, {5, 8, 6, 9}, {6, 7, 8, 9}, {8, 8, 12, 13}, - {11, 10, 12, 12}}; + int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 3}, {5, 8, 6, 9}, {6, 7, 8, 9}, {8, 8, 12, 13}, {11, 10, 12, 12}}; for (int i = 0; i < numberProcesses; i++) { diff --git a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java index 8d52f2b9..57a87000 100644 --- a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java +++ b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java @@ -7,9 +7,7 @@ import org.junit.jupiter.api.Test; public class GrahamScanTest { @Test void testGrahamScan() { - GrahamScan.Point[] points = {new GrahamScan.Point(0, 3), new GrahamScan.Point(1, 1), - new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), new GrahamScan.Point(0, 0), - new GrahamScan.Point(1, 2), new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)}; + GrahamScan.Point[] points = {new GrahamScan.Point(0, 3), new GrahamScan.Point(1, 1), new GrahamScan.Point(2, 2), new GrahamScan.Point(4, 4), new GrahamScan.Point(0, 0), new GrahamScan.Point(1, 2), new GrahamScan.Point(3, 1), new GrahamScan.Point(3, 3)}; String expectedResult = "[(0, 0), (3, 1), (4, 4), (0, 3)]"; GrahamScan graham = new GrahamScan(points); diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java index eba7f2b4..938c7d55 100644 --- a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java +++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java @@ -13,8 +13,7 @@ public class ADTFractionTest { @Test void testConstructorWithDenominatorEqualToZero() { - Exception exception - = assertThrows(IllegalArgumentException.class, () -> new ADTFraction(1, 0)); + Exception exception = assertThrows(IllegalArgumentException.class, () -> new ADTFraction(1, 0)); assertEquals("Denominator cannot be 0", exception.getMessage()); } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java index c1dae574..4b676ca6 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java @@ -15,8 +15,7 @@ public class AbsoluteMinTest { @Test void testGetMinValueWithNoArguments() { - Exception exception - = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); + Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue()); assertEquals("Numbers array cannot be empty", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java index 3d1b58a5..f8765225 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -10,8 +10,6 @@ public class AbsoluteValueTest { @Test void testGetAbsValue() { - Stream.generate(() -> ThreadLocalRandom.current().nextInt()) - .limit(1000) - .forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); + Stream.generate(() -> ThreadLocalRandom.current().nextInt()).limit(1000).forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number))); } } diff --git a/src/test/java/com/thealgorithms/maths/AreaTest.java b/src/test/java/com/thealgorithms/maths/AreaTest.java index 3e4485e1..d431c69f 100644 --- a/src/test/java/com/thealgorithms/maths/AreaTest.java +++ b/src/test/java/com/thealgorithms/maths/AreaTest.java @@ -66,53 +66,36 @@ class AreaTest { @Test void testAllIllegalInput() { - assertAll( - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), + assertAll(() + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCube(0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(1, 0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSquare(0)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(0, 1)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(0, 1)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(1, 0)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTriangleRectangle(1, 0)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 1, 0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCircle(0)), - () - -> assertThrows( - IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), - () - -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1))); + () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaHemisphere(0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(1, 0)), () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCone(0, 1))); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java index c322cdc6..9571efff 100644 --- a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java @@ -20,9 +20,7 @@ public class AutomorphicNumberTest { assertFalse(AutomorphicNumber.isAutomorphic2(n)); assertFalse(AutomorphicNumber.isAutomorphic3(String.valueOf(n))); } - assertTrue( - AutomorphicNumber.isAutomorphic3("59918212890625")); // Special case for BigInteger - assertFalse( - AutomorphicNumber.isAutomorphic3("12345678912345")); // Special case for BigInteger + assertTrue(AutomorphicNumber.isAutomorphic3("59918212890625")); // Special case for BigInteger + assertFalse(AutomorphicNumber.isAutomorphic3("12345678912345")); // Special case for BigInteger } } diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index de9f561b..3a14b80d 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -19,14 +19,12 @@ public class DistanceFormulaTest { @Test void euclideanTest3() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), 110.91911467371168); + Assertions.assertEquals(DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), 110.91911467371168); } @Test void euclideanTest4() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(1000, 13, 20000, 84), 19022.067605809836); + Assertions.assertEquals(DistanceFormula.euclideanDistance(1000, 13, 20000, 84), 19022.067605809836); } @Test diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index 49a90232..5a659664 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -47,8 +47,7 @@ public class GCDTest { @Test void testArrayGcd2() { - Assertions.assertEquals( - GCD.gcd(new int[] {2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}), 5); + Assertions.assertEquals(GCD.gcd(new int[] {2 * 3 * 5 * 7, 2 * 5 * 5 * 5, 2 * 5 * 11, 5 * 5 * 5 * 13}), 5); } @Test diff --git a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java index 526b6aa2..a2be8a4c 100644 --- a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java @@ -13,8 +13,7 @@ class LiouvilleLambdaFunctionTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, - () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); // then @@ -28,8 +27,7 @@ class LiouvilleLambdaFunctionTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, - () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java index b4f51bf5..ddfac15d 100644 --- a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java @@ -13,8 +13,7 @@ class MobiusFunctionTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows( - IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); // then @@ -28,8 +27,7 @@ class MobiusFunctionTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows( - IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java index 83a52355..3e2270a6 100644 --- a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java +++ b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java @@ -40,8 +40,7 @@ class PollardRhoTest { String expectedMessage = "GCD cannot be found."; // when - Exception exception - = assertThrows(RuntimeException.class, () -> { PollardRho.pollardRho(number); }); + Exception exception = assertThrows(RuntimeException.class, () -> { PollardRho.pollardRho(number); }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java index a59c0583..d7e16e02 100644 --- a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java @@ -12,107 +12,36 @@ class SquareFreeIntegerTest { void testIsSquareFreeInteger() { // given - List listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, - 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, - 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, - 91, 93, 94, 95, 97, 101, 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, - 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, - 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, - 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, 195, 197, 199, 201, 202, 203, - 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, - 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, - 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, - 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, - 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, - 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, - 377, 379, 381, 382, 383, 385, 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, - 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, - 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, - 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, 473, 474, 478, 479, 481, - 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, - 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, - 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, - 569, 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, - 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, - 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, - 653, 654, 655, 658, 659, 661, 662, 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, - 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, - 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, - 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, 758, 759, 761, 762, - 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, - 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, - 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, - 851, 853, 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, - 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, - 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, - 934, 935, 937, 938, 939, 941, 942, 943, 946, 947, 949, 951, 953, 955, 957, 958, 959, - 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, - 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, - 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, 1034, 1037, 1038, - 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, - 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, - 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, - 1110, 1111, 1113, 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, - 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, - 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, - 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, 1191, 1193, 1194, 1195, 1198, - 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, - 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, - 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, - 1266, 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, - 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, - 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, - 1335, 1337, 1338, 1339, 1342, 1343, 1345, 1346, 1347, 1349, 1351, 1353, 1354, 1355, - 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, - 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, - 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, 1423, - 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, - 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, - 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, - 1495, 1497, 1498, 1499, 1501, 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, - 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, - 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, - 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, 1581, 1582, 1583, - 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, - 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, - 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, - 1654, 1655, 1657, 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, - 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, - 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, - 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, 1743, 1745, 1747, 1749, 1751, - 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, - 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, - 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, - 1822, 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, - 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, - 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, - 1894, 1895, 1897, 1898, 1901, 1902, 1903, 1905, 1906, 1907, 1909, 1910, 1913, 1914, - 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, - 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, - 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, 1983, - 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, - 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, - 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, - 2053, 2054, 2055, 2059, 2062, 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, - 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, - 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, - 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, 2139, 2141, 2143, - 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, - 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, - 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, - 2215, 2217, 2218, 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, - 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, - 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, - 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, 2297, 2298, 2301, 2302, 2305, - 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, - 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, - 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, - 2374, 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, - 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, - 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, - 2442, 2443, 2445, 2446, 2447, 2449, 2451, 2453, 2454, 2455, 2458, 2459, 2461, 2462, - 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, - 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); + List listOfSquareFreeIntegers = List.of(1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30, 31, 33, 34, 35, 37, 38, 39, 41, 42, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 66, 67, 69, 70, 71, 73, 74, 77, 78, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, + 102, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 118, 119, 122, 123, 127, 129, 130, 131, 133, 134, 137, 138, 139, 141, 142, 143, 145, 146, 149, 151, 154, 155, 157, 158, 159, 161, 163, 165, 166, 167, 170, 173, 174, 177, 178, 179, 181, 182, 183, 185, 186, 187, 190, 191, 193, 194, + 195, 197, 199, 201, 202, 203, 205, 206, 209, 210, 211, 213, 214, 215, 217, 218, 219, 221, 222, 223, 226, 227, 229, 230, 231, 233, 235, 237, 238, 239, 241, 246, 247, 249, 251, 253, 254, 255, 257, 258, 259, 262, 263, 265, 266, 267, 269, 271, 273, 274, 277, 278, 281, 282, 283, 285, 286, + 287, 290, 291, 293, 295, 298, 299, 301, 302, 303, 305, 307, 309, 310, 311, 313, 314, 317, 318, 319, 321, 322, 323, 326, 327, 329, 330, 331, 334, 335, 337, 339, 341, 345, 346, 347, 349, 353, 354, 355, 357, 358, 359, 362, 365, 366, 367, 370, 371, 373, 374, 377, 379, 381, 382, 383, 385, + 386, 389, 390, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 406, 407, 409, 410, 411, 413, 415, 417, 418, 419, 421, 422, 426, 427, 429, 430, 431, 433, 434, 435, 437, 438, 439, 442, 443, 445, 446, 447, 449, 451, 453, 454, 455, 457, 458, 461, 462, 463, 465, 466, 467, 469, 470, 471, + 473, 474, 478, 479, 481, 482, 483, 485, 487, 489, 491, 493, 494, 497, 498, 499, 501, 502, 503, 505, 506, 509, 510, 511, 514, 515, 517, 518, 519, 521, 523, 526, 527, 530, 533, 534, 535, 537, 538, 541, 542, 543, 545, 546, 547, 551, 553, 554, 555, 557, 559, 561, 562, 563, 565, 566, 569, + 570, 571, 573, 574, 577, 579, 581, 582, 583, 586, 587, 589, 590, 591, 593, 595, 597, 598, 599, 601, 602, 606, 607, 609, 610, 611, 613, 614, 615, 617, 618, 619, 622, 623, 626, 627, 629, 631, 633, 634, 635, 638, 641, 642, 643, 645, 646, 647, 649, 651, 653, 654, 655, 658, 659, 661, 662, + 663, 665, 667, 669, 670, 671, 673, 674, 677, 678, 679, 681, 682, 683, 685, 687, 689, 690, 691, 694, 695, 697, 698, 699, 701, 703, 705, 706, 707, 709, 710, 713, 714, 715, 717, 718, 719, 721, 723, 727, 730, 731, 733, 734, 737, 739, 741, 742, 743, 745, 746, 749, 751, 753, 754, 755, 757, + 758, 759, 761, 762, 763, 766, 767, 769, 770, 771, 773, 777, 778, 779, 781, 782, 785, 786, 787, 789, 790, 791, 793, 794, 795, 797, 798, 799, 802, 803, 805, 806, 807, 809, 811, 813, 814, 815, 817, 818, 821, 822, 823, 826, 827, 829, 830, 831, 834, 835, 838, 839, 842, 843, 849, 851, 853, + 854, 857, 858, 859, 861, 862, 863, 865, 866, 869, 870, 871, 874, 877, 878, 879, 881, 883, 885, 886, 887, 889, 890, 893, 894, 895, 897, 898, 899, 901, 902, 903, 905, 906, 907, 910, 911, 913, 914, 915, 917, 919, 921, 922, 923, 926, 929, 930, 933, 934, 935, 937, 938, 939, 941, 942, 943, + 946, 947, 949, 951, 953, 955, 957, 958, 959, 962, 965, 966, 967, 969, 970, 971, 973, 974, 977, 978, 979, 982, 983, 985, 986, 987, 989, 991, 993, 994, 995, 997, 998, 1001, 1002, 1003, 1005, 1006, 1007, 1009, 1010, 1011, 1013, 1015, 1018, 1019, 1021, 1022, 1023, 1027, 1030, 1031, 1033, + 1034, 1037, 1038, 1039, 1041, 1042, 1043, 1045, 1046, 1047, 1049, 1051, 1054, 1055, 1057, 1059, 1061, 1063, 1065, 1066, 1067, 1069, 1070, 1073, 1074, 1077, 1079, 1081, 1082, 1085, 1086, 1087, 1090, 1091, 1093, 1094, 1095, 1097, 1099, 1101, 1102, 1103, 1105, 1106, 1109, 1110, 1111, 1113, + 1114, 1115, 1117, 1118, 1119, 1121, 1122, 1123, 1126, 1129, 1130, 1131, 1133, 1135, 1137, 1138, 1139, 1141, 1142, 1145, 1146, 1147, 1149, 1151, 1153, 1154, 1155, 1157, 1158, 1159, 1162, 1163, 1165, 1166, 1167, 1169, 1171, 1173, 1174, 1177, 1178, 1181, 1182, 1185, 1186, 1187, 1189, 1190, + 1191, 1193, 1194, 1195, 1198, 1199, 1201, 1202, 1203, 1205, 1207, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 1221, 1222, 1223, 1226, 1227, 1229, 1230, 1231, 1234, 1235, 1237, 1238, 1239, 1241, 1243, 1245, 1246, 1247, 1249, 1253, 1254, 1255, 1257, 1258, 1259, 1261, 1262, 1263, 1265, 1266, + 1267, 1270, 1271, 1273, 1277, 1279, 1281, 1282, 1283, 1285, 1286, 1289, 1290, 1291, 1293, 1294, 1295, 1297, 1298, 1299, 1301, 1302, 1303, 1306, 1307, 1309, 1310, 1311, 1313, 1315, 1317, 1318, 1319, 1321, 1322, 1326, 1327, 1329, 1330, 1333, 1334, 1335, 1337, 1338, 1339, 1342, 1343, 1345, + 1346, 1347, 1349, 1351, 1353, 1354, 1355, 1357, 1358, 1361, 1362, 1363, 1365, 1366, 1367, 1370, 1371, 1373, 1374, 1378, 1379, 1381, 1382, 1383, 1385, 1387, 1389, 1390, 1391, 1393, 1394, 1397, 1398, 1399, 1401, 1402, 1403, 1405, 1406, 1407, 1409, 1410, 1411, 1414, 1415, 1417, 1418, 1419, + 1423, 1426, 1427, 1429, 1430, 1433, 1434, 1435, 1437, 1438, 1439, 1441, 1442, 1443, 1446, 1447, 1451, 1453, 1454, 1455, 1457, 1459, 1461, 1462, 1463, 1465, 1466, 1469, 1471, 1473, 1474, 1477, 1478, 1479, 1481, 1482, 1483, 1486, 1487, 1489, 1490, 1491, 1493, 1495, 1497, 1498, 1499, 1501, + 1502, 1505, 1506, 1507, 1509, 1510, 1511, 1513, 1514, 1515, 1517, 1518, 1522, 1523, 1526, 1527, 1529, 1531, 1533, 1534, 1535, 1537, 1538, 1541, 1542, 1543, 1545, 1546, 1547, 1549, 1551, 1553, 1554, 1555, 1558, 1559, 1561, 1562, 1563, 1565, 1567, 1569, 1570, 1571, 1574, 1577, 1578, 1579, + 1581, 1582, 1583, 1585, 1586, 1589, 1590, 1591, 1594, 1595, 1597, 1598, 1599, 1601, 1603, 1605, 1606, 1607, 1609, 1610, 1613, 1614, 1615, 1618, 1619, 1621, 1622, 1623, 1626, 1627, 1630, 1631, 1633, 1634, 1635, 1637, 1639, 1641, 1642, 1643, 1645, 1646, 1649, 1651, 1653, 1654, 1655, 1657, + 1658, 1659, 1661, 1662, 1663, 1667, 1669, 1670, 1671, 1673, 1677, 1678, 1679, 1685, 1686, 1687, 1689, 1691, 1693, 1695, 1697, 1698, 1699, 1702, 1703, 1705, 1706, 1707, 1709, 1711, 1713, 1714, 1717, 1718, 1721, 1722, 1723, 1726, 1727, 1729, 1730, 1731, 1733, 1735, 1738, 1739, 1741, 1742, + 1743, 1745, 1747, 1749, 1751, 1753, 1754, 1757, 1758, 1759, 1761, 1762, 1763, 1765, 1766, 1767, 1769, 1770, 1771, 1774, 1777, 1778, 1779, 1781, 1783, 1785, 1786, 1787, 1789, 1790, 1793, 1794, 1795, 1797, 1798, 1799, 1801, 1802, 1803, 1806, 1807, 1810, 1811, 1814, 1817, 1819, 1821, 1822, + 1823, 1826, 1829, 1830, 1831, 1833, 1834, 1835, 1837, 1838, 1839, 1841, 1842, 1843, 1846, 1847, 1851, 1853, 1855, 1857, 1858, 1861, 1865, 1866, 1867, 1869, 1870, 1871, 1873, 1874, 1877, 1878, 1879, 1882, 1883, 1885, 1886, 1887, 1889, 1891, 1893, 1894, 1895, 1897, 1898, 1901, 1902, 1903, + 1905, 1906, 1907, 1909, 1910, 1913, 1914, 1915, 1918, 1919, 1921, 1923, 1927, 1929, 1930, 1931, 1933, 1934, 1937, 1938, 1939, 1941, 1942, 1943, 1945, 1946, 1947, 1949, 1951, 1954, 1955, 1957, 1958, 1959, 1961, 1963, 1965, 1966, 1967, 1969, 1970, 1973, 1974, 1977, 1978, 1979, 1981, 1982, + 1983, 1985, 1986, 1987, 1990, 1991, 1993, 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2005, 2006, 2010, 2011, 2013, 2014, 2015, 2017, 2018, 2019, 2021, 2022, 2026, 2027, 2029, 2030, 2031, 2033, 2035, 2037, 2038, 2039, 2041, 2042, 2045, 2046, 2047, 2049, 2051, 2053, 2054, 2055, 2059, 2062, + 2063, 2065, 2066, 2067, 2069, 2071, 2073, 2074, 2077, 2078, 2081, 2082, 2083, 2085, 2086, 2087, 2089, 2090, 2091, 2093, 2094, 2095, 2098, 2099, 2101, 2102, 2103, 2105, 2109, 2110, 2111, 2113, 2114, 2117, 2118, 2119, 2121, 2122, 2123, 2126, 2127, 2129, 2130, 2131, 2134, 2135, 2137, 2138, + 2139, 2141, 2143, 2145, 2146, 2147, 2149, 2153, 2154, 2155, 2157, 2158, 2159, 2161, 2162, 2163, 2165, 2167, 2170, 2171, 2173, 2174, 2177, 2179, 2181, 2182, 2183, 2185, 2186, 2189, 2190, 2191, 2193, 2194, 2195, 2198, 2199, 2201, 2202, 2203, 2206, 2207, 2210, 2211, 2213, 2215, 2217, 2218, + 2219, 2221, 2222, 2226, 2227, 2229, 2230, 2231, 2233, 2234, 2235, 2237, 2238, 2239, 2242, 2243, 2245, 2246, 2247, 2249, 2251, 2253, 2255, 2257, 2258, 2261, 2262, 2263, 2265, 2266, 2267, 2269, 2270, 2271, 2273, 2274, 2278, 2279, 2281, 2282, 2283, 2285, 2287, 2289, 2290, 2291, 2293, 2294, + 2297, 2298, 2301, 2302, 2305, 2306, 2307, 2309, 2310, 2311, 2314, 2315, 2317, 2318, 2319, 2321, 2323, 2326, 2327, 2329, 2330, 2333, 2334, 2335, 2337, 2338, 2339, 2341, 2342, 2343, 2345, 2346, 2347, 2351, 2353, 2354, 2355, 2357, 2359, 2361, 2362, 2363, 2365, 2369, 2370, 2371, 2373, 2374, + 2377, 2378, 2379, 2381, 2382, 2383, 2386, 2387, 2389, 2390, 2391, 2393, 2395, 2397, 2398, 2399, 2402, 2405, 2406, 2407, 2409, 2410, 2411, 2413, 2414, 2415, 2417, 2418, 2419, 2422, 2423, 2426, 2427, 2429, 2431, 2433, 2434, 2435, 2437, 2438, 2441, 2442, 2443, 2445, 2446, 2447, 2449, 2451, + 2453, 2454, 2455, 2458, 2459, 2461, 2462, 2463, 2465, 2467, 2469, 2470, 2471, 2473, 2474, 2477, 2478, 2479, 2481, 2482, 2483, 2485, 2486, 2487, 2489, 2490, 2491, 2494, 2495, 2497, 2498); for (int i = 1; i <= 2500; i++) { // when @@ -131,8 +60,7 @@ class SquareFreeIntegerTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, - () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); }); String actualMessage = exception.getMessage(); // then @@ -146,8 +74,7 @@ class SquareFreeIntegerTest { String expectedMessage = "Number must be greater than zero."; // when - Exception exception = assertThrows(IllegalArgumentException.class, - () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { SquareFreeInteger.isSquareFreeInteger(number); }); String actualMessage = exception.getMessage(); // then diff --git a/src/test/java/com/thealgorithms/others/ConwayTest.java b/src/test/java/com/thealgorithms/others/ConwayTest.java index 5e61836f..f4c3051a 100644 --- a/src/test/java/com/thealgorithms/others/ConwayTest.java +++ b/src/test/java/com/thealgorithms/others/ConwayTest.java @@ -36,7 +36,6 @@ public class ConwayTest { @Test public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C() { - assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", - Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); + assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); } } diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java index 1de115bb..c8e173ab 100644 --- a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java +++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java @@ -16,18 +16,14 @@ public class LowestBasePalindromeTest { assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList())); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1)))); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 1)))); - assertTrue( - LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1)))); - assertTrue( - LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1)))); + assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1)))); + assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1)))); } @Test public void testIsPalindromicNegative() { - assertFalse( - LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2)))); - assertFalse( - LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1)))); + assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2)))); + assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1)))); } @Test @@ -47,14 +43,12 @@ public class LowestBasePalindromeTest { @Test public void testIsPalindromicInBaseThrowsExceptionForNegativeNumbers() { - assertThrows( - IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)); + assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)); } @Test public void testIsPalindromicInBaseThrowsExceptionForWrongBases() { - assertThrows( - IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(10, 1)); + assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(10, 1)); } @Test diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java index 8bf0d58e..aa5303ad 100644 --- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java +++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java @@ -9,8 +9,7 @@ public class PasswordGenTest { @Test public void failGenerationWithSameMinMaxLengthTest() { int length = 10; - assertThrows(IllegalArgumentException.class, - () -> { PasswordGen.generatePassword(length, length); }); + assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(length, length); }); } @Test @@ -23,8 +22,7 @@ public class PasswordGenTest { public void failGenerationWithMinLengthSmallerThanMaxLengthTest() { int minLength = 10; int maxLength = 5; - assertThrows(IllegalArgumentException.class, - () -> { PasswordGen.generatePassword(minLength, maxLength); }); + assertThrows(IllegalArgumentException.class, () -> { PasswordGen.generatePassword(minLength, maxLength); }); } @Test diff --git a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java index 03393651..6cc65367 100644 --- a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java +++ b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java @@ -8,12 +8,10 @@ import org.junit.jupiter.api.Test; public class TestPrintMatrixInSpiralOrder { @Test public void testOne() { - int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, - {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var printClass = new PrintAMatrixInSpiralOrder(); List res = printClass.print(matrix, matrix.length, matrix[0].length); - List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, - 10, 11, 17, 26, 25, 24, 15, 16); + List list = List.of(3, 4, 5, 6, 7, 12, 18, 27, 34, 33, 32, 31, 30, 23, 14, 8, 9, 10, 11, 17, 26, 25, 24, 15, 16); assertIterableEquals(res, list); } diff --git a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java index f9b517eb..cd4bc0ff 100644 --- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java @@ -46,8 +46,7 @@ public class HammingDistanceTest { @Test public void checkForLongDataBits() { - String senderBits = "10010101101010000100110100", - receiverBits = "00110100001011001100110101"; + String senderBits = "10010101101010000100110100", receiverBits = "00110100001011001100110101"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(7); } @@ -56,16 +55,14 @@ public class HammingDistanceTest { public void mismatchDataBits() { String senderBits = "100010", receiverBits = "00011"; - Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, - () -> { int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); }); + Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); }); Assertions.assertThat(ex.getMessage()).contains("bits should be same"); } @Test public void checkForLongDataBitsSame() { - String senderBits = "10010101101010000100110100", - receiverBits = "10010101101010000100110100"; + String senderBits = "10010101101010000100110100", receiverBits = "10010101101010000100110100"; int answer = hd.getHammingDistanceBetweenBits(senderBits, receiverBits); Assertions.assertThat(answer).isEqualTo(0); } diff --git a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java index 1d9b7a7f..81b9abee 100644 --- a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java @@ -11,8 +11,7 @@ class RRSchedulingTest { @Test public void testingProcesses() { List processes = addProcessesForRR(); - final RRScheduling rrScheduling - = new RRScheduling(processes, 4); // for sending to RR with quantum value 4 + final RRScheduling rrScheduling = new RRScheduling(processes, 4); // for sending to RR with quantum value 4 rrScheduling.scheduleProcesses(); diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index 4910762c..8c9bf5ff 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -160,7 +160,6 @@ public class BinarySearch2dArrayTest { int target = 5; // Assert that an empty array is not valid input for the method. - assertThrows(ArrayIndexOutOfBoundsException.class, - () -> BinarySearch2dArray.BinarySearch(arr, target)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> BinarySearch2dArray.BinarySearch(arr, target)); } } diff --git a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java index 5912458f..2a5fe0b9 100644 --- a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java @@ -9,13 +9,7 @@ import org.junit.jupiter.api.Test; class BreadthFirstSearchTest { private static final DepthFirstSearch.Node rootNode = new DepthFirstSearch.Node("A", - List.of( - new DepthFirstSearch.Node("B", - List.of(new DepthFirstSearch.Node("D"), - new DepthFirstSearch.Node("F", - List.of(new DepthFirstSearch.Node("H"), new DepthFirstSearch.Node("I"))))), - new DepthFirstSearch.Node("C", List.of(new DepthFirstSearch.Node("G"))), - new DepthFirstSearch.Node("E"))); + List.of(new DepthFirstSearch.Node("B", List.of(new DepthFirstSearch.Node("D"), new DepthFirstSearch.Node("F", List.of(new DepthFirstSearch.Node("H"), new DepthFirstSearch.Node("I"))))), new DepthFirstSearch.Node("C", List.of(new DepthFirstSearch.Node("G"))), new DepthFirstSearch.Node("E"))); @Test void searchI() { diff --git a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java index d788c5d1..405135ec 100644 --- a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java +++ b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java @@ -180,8 +180,7 @@ class QuickSelectTest { @Test void quickSelectNullList() { - NullPointerException exception - = assertThrows(NullPointerException.class, () -> QuickSelect.select(null, 0)); + NullPointerException exception = assertThrows(NullPointerException.class, () -> QuickSelect.select(null, 0)); String expectedMsg = "The list of elements must not be null."; assertEquals(expectedMsg, exception.getMessage()); } @@ -189,24 +188,21 @@ class QuickSelectTest { @Test void quickSelectEmptyList() { List objects = Collections.emptyList(); - IllegalArgumentException exception - = assertThrows(IllegalArgumentException.class, () -> QuickSelect.select(objects, 0)); + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> QuickSelect.select(objects, 0)); String expectedMsg = "The list of elements must not be empty."; assertEquals(expectedMsg, exception.getMessage()); } @Test void quickSelectIndexOutOfLeftBound() { - IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), -1)); + IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> QuickSelect.select(Collections.singletonList(1), -1)); String expectedMsg = "The index must not be negative."; assertEquals(expectedMsg, exception.getMessage()); } @Test void quickSelectIndexOutOfRightBound() { - IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, - () -> QuickSelect.select(Collections.singletonList(1), 1)); + IndexOutOfBoundsException exception = assertThrows(IndexOutOfBoundsException.class, () -> QuickSelect.select(Collections.singletonList(1), 1)); String expectedMsg = "The index must be less than the number of elements."; assertEquals(expectedMsg, exception.getMessage()); } @@ -221,9 +217,7 @@ class QuickSelectTest { } private static List generateRandomCharacters(int n) { - return RANDOM.ints(n, ASCII_A, ASCII_Z) - .mapToObj(i -> (char) i) - .collect(Collectors.toList()); + return RANDOM.ints(n, ASCII_A, ASCII_Z).mapToObj(i -> (char) i).collect(Collectors.toList()); } private static > List getSortedCopyOfList(List list) { diff --git a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java index 304544d2..83e65621 100644 --- a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java +++ b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java @@ -7,8 +7,7 @@ import org.junit.jupiter.api.Test; public class TestSearchInARowAndColWiseSortedMatrix { @Test public void searchItem() { - int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, - {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var test = new SearchInARowAndColWiseSortedMatrix(); int[] res = test.search(matrix, 16); @@ -18,8 +17,7 @@ public class TestSearchInARowAndColWiseSortedMatrix { @Test public void notFound() { - int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, - {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; + int[][] matrix = {{3, 4, 5, 6, 7}, {8, 9, 10, 11, 12}, {14, 15, 16, 17, 18}, {23, 24, 25, 26, 27}, {30, 31, 32, 33, 34}}; var test = new SearchInARowAndColWiseSortedMatrix(); int[] res = test.search(matrix, 96); diff --git a/src/test/java/com/thealgorithms/sorts/CombSortTest.java b/src/test/java/com/thealgorithms/sorts/CombSortTest.java index 1b2ca145..e33fc388 100644 --- a/src/test/java/com/thealgorithms/sorts/CombSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CombSortTest.java @@ -31,11 +31,9 @@ public class CombSortTest { @Test public void combSortStringArray() { - String[] inputArray - = {"4gp8", "aBJ2", "85cW", "Pmk9", "ewZO", "meuU", "RhNd", "5TKB", "eDd5", "zzyo"}; + String[] inputArray = {"4gp8", "aBJ2", "85cW", "Pmk9", "ewZO", "meuU", "RhNd", "5TKB", "eDd5", "zzyo"}; String[] outputArray = combSort.sort(inputArray); - String[] expectedArray - = {"4gp8", "5TKB", "85cW", "Pmk9", "RhNd", "aBJ2", "eDd5", "ewZO", "meuU", "zzyo"}; + String[] expectedArray = {"4gp8", "5TKB", "85cW", "Pmk9", "RhNd", "aBJ2", "eDd5", "ewZO", "meuU", "zzyo"}; assertArrayEquals(outputArray, expectedArray); } @@ -49,8 +47,7 @@ public class CombSortTest { @Test public void combSortDoubleArray() { - Double[] inputArray = {0.8335545399, 0.9346214114, 0.3096396752, 0.6433840668, 0.3973191975, - 0.6118850724, 0.0553975453, 0.1961108601, 0.6172800885, 0.1065247772}; + Double[] inputArray = {0.8335545399, 0.9346214114, 0.3096396752, 0.6433840668, 0.3973191975, 0.6118850724, 0.0553975453, 0.1961108601, 0.6172800885, 0.1065247772}; Double[] outputArray = combSort.sort(inputArray); Double[] expectedArray = { 0.0553975453, diff --git a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java index 91f9aeb4..54179e12 100644 --- a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java @@ -34,8 +34,7 @@ public class IntrospectiveSortTest { // valid test case public void StrandSortNullTest() { Integer[] expectedArray = null; - assertThrows( - NullPointerException.class, () -> { new IntrospectiveSort().sort(expectedArray); }); + assertThrows(NullPointerException.class, () -> { new IntrospectiveSort().sort(expectedArray); }); } @Test diff --git a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java index 745e1139..bdc1017e 100644 --- a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java +++ b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java @@ -13,8 +13,7 @@ public class MergeSortRecursiveTest { @Test void testMergeSortRecursiveCase1() { - MergeSortRecursive mergeSortRecursive - = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); + MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); List expected = Arrays.asList(3, 5, 9, 12, 15, 88); List sorted = mergeSortRecursive.mergeSort(); @@ -24,8 +23,7 @@ public class MergeSortRecursiveTest { @Test void testMergeSortRecursiveCase2() { - MergeSortRecursive mergeSortRecursive - = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); + MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); List expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); List sorted = mergeSortRecursive.mergeSort(); diff --git a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java index 5d5d1556..d4d9eaa1 100644 --- a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java @@ -71,11 +71,9 @@ public class SlowSortTest { @Test public void slowSortStringSymbolArray() { - String[] inputArray - = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"}; + String[] inputArray = {"cbf", "auk", "ó", "(b", "a", ")", "au", "á", "cba", "auk", "(a", "bhy", "cba"}; String[] outputArray = slowSort.sort(inputArray); - String[] expectedOutput - = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"}; + String[] expectedOutput = {"(a", "(b", ")", "a", "au", "auk", "auk", "bhy", "cba", "cba", "cbf", "á", "ó"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java index aa9e203c..679a1131 100644 --- a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java @@ -12,8 +12,7 @@ class StrandSortTest { // valid test case public void StrandSortNonDuplicateTest() { int[] expectedArray = {1, 2, 3, 4, 5}; - LinkedList actualList - = StrandSort.strandSort(new LinkedList(Arrays.asList(3, 1, 2, 4, 5))); + LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(3, 1, 2, 4, 5))); int[] actualArray = new int[actualList.size()]; for (int i = 0; i < actualList.size(); i++) { actualArray[i] = actualList.get(i); @@ -25,8 +24,7 @@ class StrandSortTest { // valid test case public void StrandSortDuplicateTest() { int[] expectedArray = {2, 2, 2, 5, 7}; - LinkedList actualList - = StrandSort.strandSort(new LinkedList(Arrays.asList(7, 2, 2, 2, 5))); + LinkedList actualList = StrandSort.strandSort(new LinkedList(Arrays.asList(7, 2, 2, 2, 5))); int[] actualArray = new int[actualList.size()]; for (int i = 0; i < actualList.size(); i++) { actualArray[i] = actualList.get(i); diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java index 6ee84b7b..e299dad1 100644 --- a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java @@ -53,8 +53,7 @@ class TopologicalSortTest { graph.addEdge("6", "2"); graph.addEdge("7", ""); graph.addEdge("8", ""); - Exception exception - = assertThrows(BackEdgeException.class, () -> TopologicalSort.sort(graph)); + Exception exception = assertThrows(BackEdgeException.class, () -> TopologicalSort.sort(graph)); String expected = "This graph contains a cycle. No linear ordering is possible. " + "Back edge: 6 -> 2"; assertEquals(exception.getMessage(), expected); diff --git a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java index 39ec5aad..5fb4c18e 100644 --- a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java @@ -30,11 +30,9 @@ public class TreeSortTest { @Test public void treeSortStringArray() { - String[] inputArray - = {"F6w9", "l1qz", "dIxH", "larj", "kRzy", "vnNH", "3ftM", "hc4n", "C5Qi", "btGF"}; + String[] inputArray = {"F6w9", "l1qz", "dIxH", "larj", "kRzy", "vnNH", "3ftM", "hc4n", "C5Qi", "btGF"}; String[] outputArray = treeSort.sort(inputArray); - String[] expectedArray - = {"3ftM", "C5Qi", "F6w9", "btGF", "dIxH", "hc4n", "kRzy", "l1qz", "larj", "vnNH"}; + String[] expectedArray = {"3ftM", "C5Qi", "F6w9", "btGF", "dIxH", "hc4n", "kRzy", "l1qz", "larj", "vnNH"}; assertArrayEquals(outputArray, expectedArray); } @@ -48,11 +46,9 @@ public class TreeSortTest { @Test public void treeSortDoubleArray() { - Double[] inputArray = {0.8047485045, 0.4493112337, 0.8298433723, 0.2691406748, 0.2482782839, - 0.5976243420, 0.6746235284, 0.0552623569, 0.3515624123, 0.0536747336}; + Double[] inputArray = {0.8047485045, 0.4493112337, 0.8298433723, 0.2691406748, 0.2482782839, 0.5976243420, 0.6746235284, 0.0552623569, 0.3515624123, 0.0536747336}; Double[] outputArray = treeSort.sort(inputArray); - Double[] expectedArray = {0.0536747336, 0.0552623569, 0.2482782839, 0.2691406748, - 0.3515624123, 0.4493112337, 0.5976243420, 0.6746235284, 0.8047485045, 0.8298433723}; + Double[] expectedArray = {0.0536747336, 0.0552623569, 0.2482782839, 0.2691406748, 0.3515624123, 0.4493112337, 0.5976243420, 0.6746235284, 0.8047485045, 0.8298433723}; assertArrayEquals(outputArray, expectedArray); } } diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java index 1fac37a6..e0fbdb14 100644 --- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java @@ -18,8 +18,7 @@ public class HammingDistanceTest { @Test void testNotEqualStringLengths() { - Exception exception = assertThrows( - Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc")); + Exception exception = assertThrows(Exception.class, () -> HammingDistance.calculateHammingDistance("ab", "abc")); assertEquals("String lengths must be equal", exception.getMessage()); } } diff --git a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java index 243edf4f..dcbd40fd 100644 --- a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java +++ b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java @@ -76,8 +76,7 @@ class HorspoolSearchTest { @Test void testFindFirstPatternNull() { - assertThrows( - NullPointerException.class, () -> HorspoolSearch.findFirst(null, "Hello World")); + assertThrows(NullPointerException.class, () -> HorspoolSearch.findFirst(null, "Hello World")); } @Test diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java index 7392ce2d..5fc8541b 100644 --- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java +++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java @@ -39,9 +39,7 @@ public class LetterCombinationsOfPhoneNumberTest { // "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", // "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"] int[] numbers4 = {2, 3, 4}; - List output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", - "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", - "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"); + List output4 = Arrays.asList("adg", "adh", "adi", "aeg", "aeh", "aei", "afg", "afh", "afi", "bdg", "bdh", "bdi", "beg", "beh", "bei", "bfg", "bfh", "bfi", "cdg", "cdh", "cdi", "ceg", "ceh", "cei", "cfg", "cfh", "cfi"); assertTrue(ob.printWords(numbers4, numbers4.length, 0, "").equals(output4)); } } diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java index a3390ff1..f07736c3 100644 --- a/src/test/java/com/thealgorithms/strings/PalindromeTest.java +++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java @@ -10,14 +10,12 @@ public class PalindromeTest { String[] palindromes = {null, "", "aba", "123321", "kayak"}; for (String s : palindromes) { - Assertions.assertTrue(Palindrome.isPalindrome(s) && Palindrome.isPalindromeRecursion(s) - && Palindrome.isPalindromeTwoPointer(s)); + Assertions.assertTrue(Palindrome.isPalindrome(s) && Palindrome.isPalindromeRecursion(s) && Palindrome.isPalindromeTwoPointer(s)); } String[] notPalindromes = {"abb", "abc", "abc123", "kayaks"}; for (String s : notPalindromes) { - Assertions.assertFalse(Palindrome.isPalindrome(s) || Palindrome.isPalindromeRecursion(s) - || Palindrome.isPalindromeTwoPointer(s)); + Assertions.assertFalse(Palindrome.isPalindrome(s) || Palindrome.isPalindromeRecursion(s) || Palindrome.isPalindromeTwoPointer(s)); } } } diff --git a/src/test/java/com/thealgorithms/strings/PangramTest.java b/src/test/java/com/thealgorithms/strings/PangramTest.java index 970e7280..5d138a5e 100644 --- a/src/test/java/com/thealgorithms/strings/PangramTest.java +++ b/src/test/java/com/thealgorithms/strings/PangramTest.java @@ -9,14 +9,12 @@ public class PangramTest { @Test public void testPangram() { assertTrue(Pangram.isPangram("The quick brown fox jumps over the lazy dog")); - assertFalse( - Pangram.isPangram("The quick brown fox jumps over the azy dog")); // L is missing + assertFalse(Pangram.isPangram("The quick brown fox jumps over the azy dog")); // L is missing assertFalse(Pangram.isPangram("+-1234 This string is not alphabetical")); assertFalse(Pangram.isPangram("\u0000/\\ Invalid characters are alright too")); assertTrue(Pangram.isPangram2("The quick brown fox jumps over the lazy dog")); - assertFalse( - Pangram.isPangram2("The quick brown fox jumps over the azy dog")); // L is missing + assertFalse(Pangram.isPangram2("The quick brown fox jumps over the azy dog")); // L is missing assertFalse(Pangram.isPangram2("+-1234 This string is not alphabetical")); assertFalse(Pangram.isPangram2("\u0000/\\ Invalid characters are alright too")); }