From 26d4249f2640d077049a91d5b4671901ac82fe38 Mon Sep 17 00:00:00 2001 From: acbin <44314231+acbin@users.noreply.github.com> Date: Fri, 9 Jun 2023 10:46:23 +0000 Subject: [PATCH] style: format code --- .../thealgorithms/audiofilters/IIRFilter.java | 20 +- .../AllPathsFromSourceToTarget.java | 33 +- .../backtracking/ArrayCombination.java | 2 +- .../backtracking/Combination.java | 6 +- .../thealgorithms/backtracking/FloodFill.java | 8 +- .../backtracking/KnightsTour.java | 41 +-- .../backtracking/MazeRecursion.java | 16 +- .../thealgorithms/backtracking/NQueens.java | 25 +- .../thealgorithms/backtracking/PowerSum.java | 22 +- .../backtracking/WordSearch.java | 16 +- .../java/com/thealgorithms/ciphers/AES.java | 104 ++---- .../thealgorithms/ciphers/AESEncryption.java | 20 +- .../thealgorithms/ciphers/AffineCipher.java | 19 +- .../com/thealgorithms/ciphers/Blowfish.java | 57 +-- .../com/thealgorithms/ciphers/Caesar.java | 15 +- .../ciphers/ColumnarTranspositionCipher.java | 59 +-- .../java/com/thealgorithms/ciphers/DES.java | 266 ++++++-------- .../com/thealgorithms/ciphers/HillCipher.java | 21 +- .../com/thealgorithms/ciphers/Polybius.java | 13 +- .../java/com/thealgorithms/ciphers/RSA.java | 10 +- .../ciphers/SimpleSubCipher.java | 1 - .../com/thealgorithms/ciphers/Vigenere.java | 28 +- .../thealgorithms/ciphers/a5/A5Cipher.java | 3 +- .../ciphers/a5/A5KeyStreamGenerator.java | 15 +- .../ciphers/a5/CompositeLFSR.java | 8 +- .../com/thealgorithms/ciphers/a5/Utils.java | 9 +- .../conversions/AnyBaseToAnyBase.java | 16 +- .../conversions/DecimalToAnyBase.java | 17 +- .../conversions/DecimalToBinary.java | 4 +- .../thealgorithms/conversions/HexToOct.java | 3 +- .../conversions/RgbHsvConversion.java | 123 ++----- .../conversions/TurkishToLatinConversion.java | 7 +- .../buffers/CircularBuffer.java | 11 +- .../datastructures/caches/LFUCache.java | 3 +- .../datastructures/caches/LRUCache.java | 12 +- .../datastructures/caches/MRUCache.java | 12 +- .../dynamicarray/DynamicArray.java | 18 +- .../datastructures/graphs/A_Star.java | 170 ++------- .../datastructures/graphs/BellmanFord.java | 43 ++- .../graphs/BipartiteGrapfDFS.java | 15 +- .../graphs/ConnectedComponent.java | 8 +- .../datastructures/graphs/Cycles.java | 4 +- .../graphs/DIJSKSTRAS_ALGORITHM.java | 34 +- .../datastructures/graphs/FloydWarshall.java | 59 +-- .../graphs/HamiltonianCycle.java | 11 +- .../datastructures/graphs/KahnsAlgorithm.java | 4 +- .../datastructures/graphs/Kosaraju.java | 73 ++-- .../datastructures/graphs/Kruskal.java | 38 +- .../datastructures/graphs/MatrixGraphs.java | 26 +- .../datastructures/graphs/PrimMST.java | 29 +- .../graphs/TarjansAlgorithm.java | 58 +-- .../hashmap/hashing/HashMapCuckooHashing.java | 65 +--- .../hashmap/hashing/Intersection.java | 7 +- .../datastructures/hashmap/hashing/Main.java | 46 ++- .../hashmap/hashing/MainCuckooHashing.java | 88 ++--- .../hashmap/hashing/MajorityElement.java | 29 +- .../datastructures/hashmap/hashing/Map.java | 1 - .../datastructures/heaps/FibonacciHeap.java | 61 ++-- .../datastructures/heaps/GenericHeap.java | 14 +- .../datastructures/heaps/HeapElement.java | 11 +- .../datastructures/heaps/LeftistHeap.java | 206 ++++++----- .../datastructures/heaps/MaxHeap.java | 55 +-- .../datastructures/heaps/MinHeap.java | 55 +-- .../heaps/MinPriorityQueue.java | 15 +- .../lists/CircleLinkedList.java | 8 +- .../lists/CursorLinkedList.java | 3 +- .../lists/DoublyLinkedList.java | 20 +- .../lists/MergeSortedArrayList.java | 6 +- .../lists/MergeSortedSinglyLinkedList.java | 9 +- .../lists/Merge_K_SortedLinkedlist.java | 4 +- .../datastructures/lists/RandomNode.java | 22 +- .../SearchSinglyLinkedListRecursion.java | 5 +- .../lists/SinglyLinkedList.java | 34 +- .../datastructures/lists/SkipList.java | 43 +-- .../datastructures/queues/CircularQueue.java | 7 +- .../datastructures/queues/LinkedQueue.java | 13 +- .../datastructures/queues/PriorityQueues.java | 7 +- .../stacks/BalancedBrackets.java | 44 +-- .../stacks/CalculateMaxOfMin.java | 8 +- .../stacks/DecimalToAnyUsingStack.java | 7 +- .../stacks/DuplicateBrackets.java | 3 +- .../datastructures/stacks/InfixToPostfix.java | 28 +- .../stacks/LargestRectangle.java | 7 +- .../stacks/MaximumMinimumWindow.java | 4 +- .../stacks/NextGraterElement.java | 5 +- .../stacks/NextSmallerElement.java | 24 +- .../datastructures/stacks/NodeStack.java | 3 +- .../datastructures/stacks/PostfixToInfix.java | 22 +- .../datastructures/stacks/ReverseStack.java | 19 +- .../stacks/StackOfLinkedList.java | 8 +- .../datastructures/trees/AVLSimple.java | 46 +-- .../trees/BSTRecursiveGeneric.java | 34 +- .../datastructures/trees/BinaryTree.java | 6 +- .../trees/CheckBinaryTreeIsValidBST.java | 4 +- .../trees/CheckIfBinaryTreeBalanced.java | 17 +- .../trees/CheckTreeIsSymmetric.java | 6 +- .../CreateBinaryTreeFromInorderPreorder.java | 59 +-- .../datastructures/trees/GenericTree.java | 4 +- .../datastructures/trees/KDTree.java | 118 +++--- .../datastructures/trees/LCA.java | 23 +- .../datastructures/trees/LazySegmentTree.java | 32 +- .../datastructures/trees/RedBlackBST.java | 20 +- .../datastructures/trees/SameTreesCheck.java | 5 +- .../datastructures/trees/SegmentTree.java | 30 +- .../datastructures/trees/TreeRandomNode.java | 18 +- .../datastructures/trees/TrieImp.java | 89 +++-- .../trees/VerticalOrderTraversal.java | 38 +- .../datastructures/trees/ZigzagTraversal.java | 3 +- .../datastructures/trees/nearestRightKey.java | 2 +- .../devutils/entities/ProcessDetails.java | 1 - .../devutils/nodes/LargeTreeNode.java | 5 +- .../thealgorithms/devutils/nodes/Node.java | 3 +- .../devutils/nodes/SimpleTreeNode.java | 8 +- .../BinaryExponentiation.java | 2 +- .../divideandconquer/ClosestPair.java | 20 +- .../divideandconquer/SkylineAlgorithm.java | 15 +- .../StrassenMatrixMultiplication.java | 11 +- .../dynamicprogramming/BoardPath.java | 20 +- .../dynamicprogramming/BoundaryFill.java | 124 ++----- .../BruteForceKnapsack.java | 9 +- .../dynamicprogramming/CatalanNumber.java | 4 +- .../dynamicprogramming/ClimbingStairs.java | 7 +- .../dynamicprogramming/CoinChange.java | 23 +- .../CountFriendsPairing.java | 6 +- .../dynamicprogramming/DiceThrow.java | 11 +- .../DyanamicProgrammingKnapsack.java | 4 +- .../dynamicprogramming/EditDistance.java | 11 +- .../dynamicprogramming/EggDropping.java | 4 +- .../dynamicprogramming/Fibonacci.java | 25 +- .../dynamicprogramming/FordFulkerson.java | 15 +- .../dynamicprogramming/KadaneAlgorithm.java | 3 +- .../dynamicprogramming/Knapsack.java | 13 +- .../KnapsackMemoization.java | 13 +- .../LevenshteinDistance.java | 13 +- .../LongestAlternatingSubsequence.java | 34 +- .../LongestCommonSubsequence.java | 6 +- .../LongestIncreasingSubsequence.java | 4 +- .../LongestPalindromicSubsequence.java | 37 +- .../LongestValidParentheses.java | 5 +- .../MatrixChainMultiplication.java | 11 +- ...atrixChainRecursiveTopDownMemoisation.java | 16 +- .../dynamicprogramming/MinimumPathSum.java | 8 +- .../MinimumSumPartition.java | 6 +- .../dynamicprogramming/NewManShanksPrime.java | 3 +- .../OptimalJobScheduling.java | 58 +-- .../PalindromicPartitioning.java | 26 +- .../dynamicprogramming/PartitionProblem.java | 12 +- .../dynamicprogramming/RegexMatching.java | 19 +- .../dynamicprogramming/RodCutting.java | 2 +- .../ShortestCommonSupersequenceLength.java | 7 +- .../dynamicprogramming/SubsetCount.java | 58 ++- .../dynamicprogramming/SubsetSum.java | 2 +- .../dynamicprogramming/Sum_Of_Subset.java | 2 +- .../dynamicprogramming/UniquePaths.java | 18 +- .../dynamicprogramming/WineProblem.java | 6 +- .../thealgorithms/geometry/GrahamScan.java | 168 +++++---- .../com/thealgorithms/io/BufferedReader.java | 342 +++++++++--------- .../com/thealgorithms/maths/ADTFraction.java | 10 +- .../com/thealgorithms/maths/AbsoluteMin.java | 7 +- .../com/thealgorithms/maths/AliquotSum.java | 20 +- .../thealgorithms/maths/AmicableNumber.java | 36 +- .../java/com/thealgorithms/maths/Area.java | 3 +- .../maths/AutomorphicNumber.java | 12 +- .../maths/BinomialCoefficient.java | 14 +- .../maths/CircularConvolutionFFT.java | 10 +- .../com/thealgorithms/maths/Convolution.java | 5 +- .../thealgorithms/maths/ConvolutionFFT.java | 11 +- .../maths/DeterminantOfMatrix.java | 4 +- .../com/thealgorithms/maths/DigitalRoot.java | 16 +- .../thealgorithms/maths/DistanceFormula.java | 14 +- .../thealgorithms/maths/DudeneyNumber.java | 6 +- .../com/thealgorithms/maths/EulerMethod.java | 47 +-- .../java/com/thealgorithms/maths/FFT.java | 17 +- .../com/thealgorithms/maths/FFTBluestein.java | 19 +- .../com/thealgorithms/maths/Factorial.java | 3 +- .../thealgorithms/maths/FastInverseSqrt.java | 19 +- .../maths/FibonacciJavaStreams.java | 54 +-- .../thealgorithms/maths/FindMaxRecursion.java | 10 +- .../thealgorithms/maths/FindMinRecursion.java | 10 +- .../com/thealgorithms/maths/FrizzyNumber.java | 9 +- .../java/com/thealgorithms/maths/GCD.java | 8 +- .../com/thealgorithms/maths/Gaussian.java | 17 +- .../com/thealgorithms/maths/GenericRoot.java | 3 +- .../thealgorithms/maths/HarshadNumber.java | 6 +- .../thealgorithms/maths/JosephusProblem.java | 18 +- .../thealgorithms/maths/JugglerSequence.java | 5 +- .../thealgorithms/maths/KaprekarNumbers.java | 39 +- .../com/thealgorithms/maths/KeithNumber.java | 31 +- .../maths/KrishnamurthyNumber.java | 34 +- .../maths/LeastCommonMultiple.java | 4 +- .../thealgorithms/maths/LeonardoNumber.java | 6 +- .../LinearDiophantineEquationsSolver.java | 52 +-- .../maths/LiouvilleLambdaFunction.java | 8 +- .../com/thealgorithms/maths/LongDivision.java | 18 +- .../com/thealgorithms/maths/LucasSeries.java | 4 +- .../com/thealgorithms/maths/MagicSquare.java | 10 +- .../com/thealgorithms/maths/MatrixUtil.java | 173 ++++----- .../java/com/thealgorithms/maths/Median.java | 5 +- .../thealgorithms/maths/MobiusFunction.java | 18 +- .../java/com/thealgorithms/maths/Mode.java | 17 +- .../maths/NonRepeatingElement.java | 39 +- .../thealgorithms/maths/NthUglyNumber.java | 5 +- .../thealgorithms/maths/NumberOfDigits.java | 4 +- .../com/thealgorithms/maths/ParseInteger.java | 6 +- .../thealgorithms/maths/PascalTriangle.java | 26 +- .../com/thealgorithms/maths/PerfectCube.java | 2 +- .../thealgorithms/maths/PerfectNumber.java | 18 +- .../com/thealgorithms/maths/Perimeter.java | 17 +- .../com/thealgorithms/maths/PiNilakantha.java | 14 +- .../com/thealgorithms/maths/PollardRho.java | 28 +- .../com/thealgorithms/maths/PrimeCheck.java | 8 +- .../com/thealgorithms/maths/PronicNumber.java | 9 +- .../thealgorithms/maths/RomanNumeralUtil.java | 23 +- .../maths/SimpsonIntegration.java | 10 +- .../maths/SquareFreeInteger.java | 35 +- .../SquareRootWithNewtonRaphsonMethod.java | 10 +- .../maths/SumOfArithmeticSeries.java | 10 +- .../com/thealgorithms/maths/SumOfDigits.java | 18 +- .../maths/SumWithoutArithmeticOperators.java | 22 +- .../maths/TrinomialTriangle.java | 5 +- .../com/thealgorithms/maths/TwinPrime.java | 31 +- .../thealgorithms/maths/VampireNumber.java | 26 +- .../maths/VectorCrossProduct.java | 8 +- .../matrixexponentiation/Fibonacci.java | 37 +- .../MinimizingLateness.java | 16 +- .../misc/ColorContrastRatio.java | 39 +- .../thealgorithms/misc/InverseOfMatrix.java | 3 +- .../misc/MedianOfRunningArray.java | 2 +- .../thealgorithms/misc/PalindromePrime.java | 4 +- .../misc/RangeInSortedArray.java | 41 +-- .../java/com/thealgorithms/misc/Sort012D.java | 38 +- .../java/com/thealgorithms/misc/Sparcity.java | 12 +- .../thealgorithms/misc/ThreeSumProblem.java | 11 +- .../com/thealgorithms/misc/WordBoggle.java | 93 ++--- .../java/com/thealgorithms/others/BFPRT.java | 3 +- .../others/BankersAlgorithm.java | 55 +-- .../com/thealgorithms/others/BoyerMoore.java | 3 +- .../java/com/thealgorithms/others/CRC16.java | 33 +- .../java/com/thealgorithms/others/Conway.java | 15 +- .../java/com/thealgorithms/others/Damm.java | 31 +- .../com/thealgorithms/others/Dijkstra.java | 33 +- .../thealgorithms/others/FloydTriangle.java | 4 +- .../thealgorithms/others/HappyNumbersSeq.java | 5 +- .../com/thealgorithms/others/Huffman.java | 15 +- ...g_auto_completing_features_using_trie.java | 8 +- .../others/InsertDeleteInArray.java | 4 +- .../thealgorithms/others/KochSnowflake.java | 44 +-- .../com/thealgorithms/others/LineSweep.java | 22 +- .../others/LinearCongruentialGenerator.java | 19 +- .../others/LowestBasePalindrome.java | 15 +- .../java/com/thealgorithms/others/Luhn.java | 41 +-- .../com/thealgorithms/others/Mandelbrot.java | 97 ++--- .../others/MemoryManagementAlgorithms.java | 106 +++--- .../others/MiniMaxAlgorithm.java | 22 +- .../com/thealgorithms/others/PageRank.java | 56 +-- .../com/thealgorithms/others/PasswordGen.java | 6 +- .../com/thealgorithms/others/PerlinNoise.java | 35 +- .../others/PrintAMatrixInSpiralOrder.java | 3 - .../others/QueueUsingTwoStacks.java | 3 +- .../com/thealgorithms/others/RabinKarp.java | 23 +- .../others/RemoveDuplicateFromString.java | 8 +- .../others/ReturnSubsequence.java | 18 +- .../others/SieveOfEratosthenes.java | 6 +- .../thealgorithms/others/SkylineProblem.java | 10 +- .../java/com/thealgorithms/others/Sudoku.java | 18 +- .../com/thealgorithms/others/TopKWords.java | 7 +- .../thealgorithms/others/TowerOfHanoi.java | 15 +- .../com/thealgorithms/others/Verhoeff.java | 51 ++- .../others/cn/HammingDistance.java | 9 +- .../thealgorithms/others/countSetBits.java | 28 +- .../scheduling/FCFSScheduling.java | 22 +- .../scheduling/RRScheduling.java | 43 ++- .../scheduling/SJFScheduling.java | 92 ++--- .../thealgorithms/searches/BinarySearch.java | 30 +- .../searches/BinarySearch2dArray.java | 93 ++--- .../searches/DepthFirstSearch.java | 29 +- .../searches/ExponentalSearch.java | 30 +- .../searches/FibonacciSearch.java | 14 +- .../searches/HowManyTimesRotated.java | 20 +- .../searches/InterpolationSearch.java | 27 +- .../searches/IterativeBinarySearch.java | 21 +- .../searches/IterativeTernarySearch.java | 21 +- .../thealgorithms/searches/JumpSearch.java | 2 +- .../com/thealgorithms/searches/KMPSearch.java | 8 +- .../thealgorithms/searches/LinearSearch.java | 15 +- .../searches/LinearSearchThread.java | 6 +- .../thealgorithms/searches/LowerBound.java | 30 +- .../searches/MonteCarloTreeSearch.java | 37 +- .../searches/OrderAgnosticBinarySearch.java | 69 ++-- .../searches/PerfectBinarySearch.java | 2 +- .../thealgorithms/searches/QuickSelect.java | 30 +- .../searches/RabinKarpAlgorithm.java | 2 +- ...owColumnWiseSorted2dArrayBinarySearch.java | 53 +-- .../searches/SaddlebackSearch.java | 2 +- .../SearchInARowAndColWiseSortedMatrix.java | 3 +- .../searches/SquareRootBinarySearch.java | 4 +- .../thealgorithms/searches/TernarySearch.java | 38 +- .../com/thealgorithms/searches/UnionFind.java | 16 +- .../thealgorithms/searches/UpperBound.java | 30 +- .../sortOrderAgnosticBinarySearch.java | 36 +- .../com/thealgorithms/sorts/BeadSort.java | 45 ++- .../com/thealgorithms/sorts/BitonicSort.java | 2 +- .../com/thealgorithms/sorts/BogoSort.java | 4 +- .../sorts/BubbleSortRecursion.java | 5 +- .../com/thealgorithms/sorts/BucketSort.java | 2 +- .../com/thealgorithms/sorts/CircleSort.java | 13 +- .../sorts/CocktailShakerSort.java | 4 +- .../com/thealgorithms/sorts/CountingSort.java | 20 +- .../java/com/thealgorithms/sorts/DNFSort.java | 40 +- .../sorts/DualPivotQuickSort.java | 20 +- .../sorts/DutchNationalFlagSort.java | 25 +- .../thealgorithms/sorts/InsertionSort.java | 18 +- .../com/thealgorithms/sorts/LinkListSort.java | 181 +++++---- .../com/thealgorithms/sorts/MergeSort.java | 3 +- .../sorts/MergeSortNoExtraSpace.java | 12 +- .../sorts/MergeSortRecursive.java | 24 +- .../com/thealgorithms/sorts/OddEvenSort.java | 2 +- .../thealgorithms/sorts/PigeonholeSort.java | 2 +- .../com/thealgorithms/sorts/QuickSort.java | 18 +- .../com/thealgorithms/sorts/RadixSort.java | 2 +- .../thealgorithms/sorts/SelectionSort.java | 4 +- .../com/thealgorithms/sorts/ShellSort.java | 2 +- .../com/thealgorithms/sorts/SimpleSort.java | 2 +- .../thealgorithms/sorts/SortAlgorithm.java | 6 +- .../com/thealgorithms/sorts/SortUtils.java | 4 +- .../sorts/SortUtilsRandomGenerator.java | 5 +- .../com/thealgorithms/sorts/StoogeSort.java | 10 +- .../com/thealgorithms/sorts/StrandSort.java | 21 +- .../com/thealgorithms/sorts/SwapSort.java | 10 +- .../java/com/thealgorithms/sorts/TimSort.java | 4 +- .../thealgorithms/sorts/TopologicalSort.java | 42 +-- .../com/thealgorithms/sorts/TreeSort.java | 16 +- .../com/thealgorithms/sorts/WiggleSort.java | 35 +- .../thealgorithms/strings/Alphabetical.java | 5 +- .../com/thealgorithms/strings/Anagrams.java | 55 +-- .../thealgorithms/strings/CheckVowels.java | 5 +- .../strings/HammingDistance.java | 7 +- .../thealgorithms/strings/HorspoolSearch.java | 19 +- .../LetterCombinationsOfPhoneNumber.java | 25 +- .../strings/LongestPalindromicSubstring.java | 4 +- .../java/com/thealgorithms/strings/Lower.java | 7 +- .../com/thealgorithms/strings/MyAtoi.java | 27 +- .../com/thealgorithms/strings/Palindrome.java | 4 +- .../com/thealgorithms/strings/Pangram.java | 2 +- .../thealgorithms/strings/PermuteString.java | 16 +- .../strings/ReverseStringRecursive.java | 7 +- .../strings/StringCompression.java | 104 +++--- .../java/com/thealgorithms/strings/Upper.java | 7 +- .../strings/ValidParentheses.java | 56 ++- .../com/thealgorithms/strings/WordLadder.java | 14 +- .../strings/longestNonRepeativeSubstring.java | 3 +- .../strings/zigZagPattern/zigZagPattern.java | 12 +- .../AllPathsFromSourceToTargetTest.java | 41 ++- .../backtracking/CombinationTest.java | 15 +- .../backtracking/FloodFillTest.java | 72 ++-- .../backtracking/MazeRecursionTest.java | 34 +- .../backtracking/PermutationTest.java | 10 +- .../backtracking/PowerSumTest.java | 4 +- .../backtracking/WordSearchTest.java | 6 +- .../thealgorithms/ciphers/BlowfishTest.java | 12 +- .../com/thealgorithms/ciphers/CaesarTest.java | 5 +- .../com/thealgorithms/ciphers/DESTest.java | 45 ++- .../com/thealgorithms/ciphers/RSATest.java | 5 +- .../ciphers/SimpleSubCipherTest.java | 5 +- .../ciphers/SimpleSubstitutionCipherTest.java | 4 +- .../thealgorithms/ciphers/VigenereTest.java | 5 +- .../thealgorithms/ciphers/a5/LFSRTest.java | 8 +- .../conversions/BinaryToDecimalTest.java | 4 +- .../conversions/HexaDecimalToBinaryTest.java | 5 +- .../conversions/HexaDecimalToDecimalTest.java | 6 +- .../conversions/RomanToIntegerTest.java | 4 +- .../buffers/CircularBufferTest.java | 24 +- .../datastructures/caches/LFUCacheTest.java | 20 +- .../graphs/HamiltonianCycleTest.java | 34 +- .../datastructures/graphs/KosarajuTest.java | 12 +- .../graphs/TarjansAlgorithmTest.java | 14 +- .../hashmap/HashMapCuckooHashingTest.java | 2 +- .../hashmap/hashing/MajorityElementTest.java | 13 +- .../hashmap/hashing/MapTest.java | 5 +- .../datastructures/heaps/LeftistHeapTest.java | 42 +-- .../lists/SinglyLinkedListTest.java | 120 +++--- .../datastructures/lists/SkipListTest.java | 10 +- .../queues/LinkedQueueTest.java | 33 +- .../queues/PriorityQueuesTest.java | 4 +- .../trees/BSTFromSortedArrayTest.java | 6 +- .../datastructures/trees/BinaryTreeTest.java | 120 +++--- .../trees/CeilInBinarySearchTreeTest.java | 18 +- .../trees/CheckBinaryTreeIsValidBSTTest.java | 15 +- .../trees/CheckTreeIsSymmetricTest.java | 11 +- ...eateBinaryTreeFromInorderPreorderTest.java | 21 +- .../trees/InorderTraversalTest.java | 10 +- .../datastructures/trees/KDTreeTest.java | 38 +- .../trees/LazySegmentTreeTest.java | 21 +- .../trees/LevelOrderTraversalTest.java | 16 +- .../trees/PostOrderTraversalTest.java | 10 +- .../trees/PreOrderTraversalTest.java | 10 +- .../trees/SameTreesCheckTest.java | 24 +- .../datastructures/trees/TreeTestUtils.java | 2 +- .../trees/VerticalOrderTraversalTest.java | 14 +- .../trees/ZigzagTraversalTest.java | 16 +- .../BinaryExponentiationTest.java | 1 - .../StrassenMatrixMultiplicationTest.java | 21 +- .../dynamicprogramming/EggDroppingTest.java | 20 +- .../KnapsackMemoizationTest.java | 16 +- .../LevenshteinDistanceTests.java | 5 +- .../OptimalJobSchedulingTest.java | 102 ++---- .../PartitionProblemTest.java | 20 +- .../dynamicprogramming/SubsetCountTest.java | 19 +- .../dynamicprogramming/climbStairsTest.java | 23 +- .../geometry/GrahamScanTest.java | 9 +- .../thealgorithms/io/BufferedReaderTest.java | 177 +++++---- .../thealgorithms/maths/ADTFractionTest.java | 6 +- .../thealgorithms/maths/AbsoluteMinTest.java | 6 +- .../maths/AbsoluteValueTest.java | 10 +- .../com/thealgorithms/maths/AreaTest.java | 70 ++-- .../maths/AutomorphicNumberTest.java | 11 +- .../com/thealgorithms/maths/AverageTest.java | 1 - .../maths/CollatzConjectureTest.java | 27 +- .../maths/DistanceFormulaTest.java | 62 +--- .../maths/DudeneyNumberTest.java | 5 +- .../com/thealgorithms/maths/FindMaxTest.java | 20 +- .../com/thealgorithms/maths/FindMinTest.java | 16 +- .../thealgorithms/maths/FrizzyNumberTest.java | 40 +- .../java/com/thealgorithms/maths/GCDTest.java | 28 +- .../maths/HarshadNumberTest.java | 3 +- .../maths/HeronsFormulaTest.java | 10 +- .../maths/KaprekarNumbersTest.java | 6 +- .../maths/LeonardoNumberTest.java | 7 +- .../maths/LiouvilleLambdaFunctionTest.java | 40 +- .../thealgorithms/maths/LongDivisionTest.java | 35 +- .../thealgorithms/maths/LucasSeriesTest.java | 3 +- .../com/thealgorithms/maths/MedianTest.java | 3 +- .../maths/MobiusFunctionTest.java | 30 +- .../maths/NthUglyNumberTest.java | 14 +- .../maths/PascalTriangleTest.java | 30 +- .../maths/PerfectNumberTest.java | 5 +- .../maths/PerfectSquareTest.java | 6 +- .../thealgorithms/maths/PerimeterTest.java | 2 +- .../thealgorithms/maths/PollardRhoTest.java | 26 +- .../maths/PrimeFactorizationTest.java | 10 +- .../thealgorithms/maths/PronicNumberTest.java | 12 +- .../maths/ReverseNumberTest.java | 6 +- .../maths/SquareFreeIntegerTest.java | 181 ++++++--- ...SquareRootWithNewtonRaphsonTestMethod.java | 15 +- .../SquareRootwithBabylonianMethodTest.java | 20 +- .../maths/StandardDeviationTest.java | 21 +- .../maths/StandardScoreTest.java | 5 +- .../SumWithoutArithmeticOperatorsTest.java | 33 +- .../thealgorithms/maths/TwinPrimeTest.java | 102 +++--- .../com/thealgorithms/maths/VolumeTest.java | 1 + .../others/ArrayLeftRotationTest.java | 14 +- .../thealgorithms/others/BestFitCPUTest.java | 30 +- .../com/thealgorithms/others/CRC16Test.java | 5 +- .../others/CRCAlgorithmTest.java | 12 +- .../others/CalculateMaxOfMinTest.java | 14 +- .../com/thealgorithms/others/ConwayTest.java | 27 +- .../thealgorithms/others/CountCharTest.java | 7 +- .../others/CountFriendsPairingTest.java | 16 +- .../thealgorithms/others/CountWordsTest.java | 1 - .../thealgorithms/others/FirstFitCPUTest.java | 30 +- .../others/KadaneAlogrithmTest.java | 16 +- .../thealgorithms/others/LineSweepTest.java | 21 +- .../others/LinkListSortTest.java | 16 +- .../others/LowestBasePalindromeTest.java | 25 +- .../com/thealgorithms/others/NextFitTest.java | 30 +- .../thealgorithms/others/PasswordGenTest.java | 16 +- .../others/TestPrintMatrixInSpiralOrder.java | 21 +- .../thealgorithms/others/TwoPointersTest.java | 33 +- .../thealgorithms/others/WorstFitCPUTest.java | 39 +- .../others/cn/HammingDistanceTest.java | 19 +- .../scheduling/FCFSSchedulingTest.java | 10 +- .../scheduling/RRSchedulingTest.java | 7 +- .../scheduling/SJFSchedulingTest.java | 143 ++++---- .../searches/BinarySearch2dArrayTest.java | 48 +-- .../searches/BreadthFirstSearchTest.java | 27 +- .../searches/HowManyTimesRotatedTest.java | 5 +- .../OrderAgnosticBinarySearchTest.java | 119 +++--- .../searches/QuickSelectTest.java | 34 +- ...lumnWiseSorted2dArrayBinarySearchTest.java | 196 +++++----- ...estSearchInARowAndColWiseSortedMatrix.java | 23 +- .../sortOrderAgnosticBinarySearchTest.java | 19 +- .../com/thealgorithms/sorts/BeadSortTest.java | 14 +- .../sorts/BinaryInsertionSortTest.java | 8 +- .../com/thealgorithms/sorts/BogoSortTest.java | 30 +- .../thealgorithms/sorts/BubbleSortTest.java | 10 +- .../thealgorithms/sorts/BucketSortTest.java | 16 +- .../sorts/CocktailShakerSortTest.java | 14 +- .../com/thealgorithms/sorts/CombSortTest.java | 62 ++-- .../sorts/DualPivotQuickSortTest.java | 21 +- .../sorts/DutchNationalFlagSortTest.java | 32 +- .../sorts/InsertionSortTest.java | 7 +- .../sorts/IntrospectiveSortTest.java | 9 +- .../sorts/MergeSortRecursiveTest.java | 46 +-- .../thealgorithms/sorts/OddEvenSortTest.java | 7 +- .../sorts/SelectionSortTest.java | 14 +- .../thealgorithms/sorts/ShellSortTest.java | 31 +- .../thealgorithms/sorts/SimpleSortTest.java | 30 +- .../com/thealgorithms/sorts/SlowSortTest.java | 6 +- .../sorts/SortUtilsRandomGeneratorTest.java | 4 +- .../thealgorithms/sorts/SortUtilsTest.java | 5 +- .../sorts/SortingAlgorithmTest.java | 31 +- .../thealgorithms/sorts/StrandSortTest.java | 14 +- .../com/thealgorithms/sorts/TimSortTest.java | 4 +- .../sorts/TopologicalSortTest.java | 11 +- .../com/thealgorithms/sorts/TreeSortTest.java | 56 +-- .../thealgorithms/sorts/WiggleSortTest.java | 28 +- .../strings/HammingDistanceTest.java | 24 +- .../strings/HorspoolSearchTest.java | 11 +- .../LetterCombinationsOfPhoneNumberTest.java | 15 +- .../com/thealgorithms/strings/LowerTest.java | 6 +- .../com/thealgorithms/strings/MyAtoiTest.java | 12 +- .../thealgorithms/strings/PalindromeTest.java | 15 +- .../thealgorithms/strings/PangramTest.java | 9 +- .../strings/ReverseStringRecursiveTest.java | 16 +- .../strings/ReverseStringTest.java | 4 +- .../thealgorithms/strings/RotationTest.java | 2 +- .../strings/StringCompressionTest.java | 7 +- .../strings/ValidParenthesesTest.java | 11 +- .../thealgorithms/strings/WordLadderTest.java | 8 +- .../longestNonRepeativeSubstringTest.java | 10 +- .../zigZagPattern/zigZagPatternTest.java | 10 +- 521 files changed, 5269 insertions(+), 7345 deletions(-) diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index 4aca8fb40624..21bb5a123f83 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java @@ -22,9 +22,7 @@ public class IIRFilter { */ public IIRFilter(int order) throws IllegalArgumentException { if (order < 1) { - throw new IllegalArgumentException( - "order must be greater than zero" - ); + throw new IllegalArgumentException("order must be greater than zero"); } this.order = order; @@ -47,24 +45,19 @@ public IIRFilter(int order) throws IllegalArgumentException { * @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is * not of size {@code order}, or if {@code aCoeffs[0]} is 0.0 */ - public void setCoeffs(double[] aCoeffs, double[] bCoeffs) - throws IllegalArgumentException { + 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 - ); + "aCoeffs must be of size " + order + ", got " + aCoeffs.length); } if (aCoeffs[0] == 0.0) { - throw new IllegalArgumentException( - "aCoeffs.get(0) must not be zero" - ); + throw new IllegalArgumentException("aCoeffs.get(0) must not be zero"); } if (bCoeffs.length != order) { throw new IllegalArgumentException( - "bCoeffs must be of size " + order + ", got " + bCoeffs.length - ); + "bCoeffs must be of size " + order + ", got " + bCoeffs.length); } for (int i = 0; i <= order; i++) { @@ -84,8 +77,7 @@ public double process(double sample) { // Process for (int i = 1; i <= order; i++) { - result += - (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); + result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]); } result = (result + coeffsB[0] * sample) / coeffsA[0]; diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java index 8acaa954ce75..b840f6ad5388 100644 --- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java +++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -15,13 +16,12 @@ public class AllPathsFromSourceToTarget { private int v; // To store the paths from source to destination - static List<List<Integer>> nm=new ArrayList<>(); + static List<List<Integer>> nm = new ArrayList<>(); // adjacency list private ArrayList<Integer>[] adjList; // Constructor - public AllPathsFromSourceToTarget(int vertices) - { + public AllPathsFromSourceToTarget(int vertices) { // initialise vertex count this.v = vertices; @@ -31,8 +31,7 @@ public AllPathsFromSourceToTarget(int vertices) } // utility method to initialise adjacency list - private void initAdjList() - { + private void initAdjList() { adjList = new ArrayList[v]; for (int i = 0; i < v; i++) { @@ -41,15 +40,12 @@ private void initAdjList() } // add edge from u to v - public void addEdge(int u, int v) - { + public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } - - public void storeAllPaths(int s, int d) - { + public void storeAllPaths(int s, int d) { boolean[] isVisited = new boolean[v]; ArrayList<Integer> pathList = new ArrayList<>(); @@ -61,9 +57,9 @@ public void storeAllPaths(int s, int d) // A recursive function to print all paths from 'u' to 'd'. // isVisited[] keeps track of vertices in current path. - // localPathList<> stores actual vertices in the current path - private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) - { + // localPathList<> stores actual vertices in the current path + private void storeAllPathsUtil( + Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) { if (u.equals(d)) { nm.add(new ArrayList<>(localPathList)); @@ -74,7 +70,7 @@ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<I isVisited[u] = true; // Recursion for all the vertices adjacent to current vertex - + for (Integer i : adjList[u]) { if (!isVisited[i]) { // store current node in path[] @@ -91,12 +87,11 @@ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<I } // Driver program - public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) - { + public static List<List<Integer>> allPathsFromSourceToTarget( + int vertices, int[][] a, int source, int destination) { // Create a sample graph AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices); - for(int i=0 ; i<a.length ; i++) - { + for (int i = 0; i < a.length; i++) { g.addEdge(a[i][0], a[i][1]); // edges are added } diff --git a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java index 4238846786e4..50ef8f7234de 100644 --- a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java +++ b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java @@ -22,7 +22,7 @@ public static List<TreeSet<Integer>> combination(int n, int k) { length = k; Integer[] arr = new Integer[n]; for (int i = 1; i <= n; i++) { - arr[i-1] = i; + arr[i - 1] = i; } return Combination.combination(arr, length); } diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index c2d148a270e8..7c45dffb8630 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -38,11 +38,7 @@ public static <T> List<TreeSet<T>> combination(T[] arr, int n) { * @param <T> the type of elements in the array. */ private static <T> void backtracking( - T[] arr, - int index, - TreeSet<T> currSet, - List<TreeSet<T>> result - ) { + T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) { if (index + length - currSet.size() > arr.length) return; if (length - 1 == currSet.size()) { for (int i = index; i < arr.length; i++) { diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java index 6c4446a40bc4..b6b1c5ee19f8 100644 --- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java +++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java @@ -38,13 +38,7 @@ public static void putPixel(int[][] image, int x, int y, int newColor) { * @param newColor The new color which to be filled in the image * @param oldColor The old color which is to be replaced in the image */ - public static void floodFill( - int[][] image, - int x, - int y, - int newColor, - int oldColor - ) { + public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) { if (x < 0 || x >= image.length) return; if (y < 0 || y >= image[x].length) return; if (getPixel(image, x, y) != oldColor) return; diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java index a2075fd9d778..882b43537b7f 100644 --- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java +++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java @@ -4,9 +4,10 @@ /* * Problem Statement: - - - Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of - chess knight must visit each square exactly once. Print the order of each cell in which they are visited. + + Given a N*N board with the Knight placed on the first block of an empty board. Moving according + to the rules of chess knight must visit each square exactly once. Print the order of each cell in + which they are visited. Example: - @@ -27,14 +28,14 @@ public class KnightsTour { private static final int base = 12; private static final int[][] moves = { - { 1, -2 }, - { 2, -1 }, - { 2, 1 }, - { 1, 2 }, - { -1, 2 }, - { -2, 1 }, - { -2, -1 }, - { -1, -2 }, + {1, -2}, + {2, -1}, + {2, 1}, + {1, 2}, + {-1, 2}, + {-2, 1}, + {-2, -1}, + {-1, -2}, }; // Possible moves by knight on chess private static int[][] grid; // chess grid private static int total; // total squares in chess @@ -75,23 +76,17 @@ private static boolean solve(int row, int column, int count) { return false; } - Collections.sort( - neighbor, - new Comparator<int[]>() { - public int compare(int[] a, int[] b) { - return a[2] - b[2]; - } + Collections.sort(neighbor, new Comparator<int[]>() { + public int compare(int[] a, int[] b) { + return a[2] - b[2]; } - ); + }); for (int[] nb : neighbor) { row = nb[0]; column = nb[1]; grid[row][column] = count; - if ( - !orphanDetected(count, row, column) && - solve(row, column, count + 1) - ) { + if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) { return true; } grid[row][column] = 0; @@ -109,7 +104,7 @@ private static List<int[]> neighbors(int row, int column) { int y = m[1]; if (grid[row + y][column + x] == 0) { int num = countNeighbors(row + y, column + x); - neighbour.add(new int[] { row + y, column + x, num }); + neighbour.add(new int[] {row + y, column + x, num}); } } return neighbour; diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java index 0e1cd308d6cb..d66d1482d83e 100644 --- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java +++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java @@ -51,9 +51,7 @@ public static void mazeRecursion() { setWay2(map2, 1, 1); // Print out the new map1, with the ball footprint - System.out.println( - "After the ball goes through the map1,show the current map1 condition" - ); + System.out.println("After the ball goes through the map1,show the current map1 condition"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); @@ -62,9 +60,7 @@ public static void mazeRecursion() { } // Print out the new map2, with the ball footprint - System.out.println( - "After the ball goes through the map2,show the current map2 condition" - ); + System.out.println("After the ball goes through the map2,show the current map2 condition"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map2[i][j] + " "); @@ -85,7 +81,7 @@ public static void mazeRecursion() { * means the ball has gone through the path but this path is dead end * 5. We will need strategy for the ball to pass through the maze for example: * Down -> Right -> Up -> Left, if the path doesn't work, then backtrack - * + * * @author OngLipWei * @version Jun 23, 2021 11:36:14 AM * @param map The maze @@ -99,7 +95,8 @@ public static boolean setWay(int[][] map, int i, int j) { } if (map[i][j] == 0) { // if the ball haven't gone through this point // then the ball follows the move strategy : down -> right -> up -> left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 + // first。 if (setWay(map, i + 1, j)) { // go down return true; } else if (setWay(map, i, j + 1)) { // go right @@ -129,7 +126,8 @@ public static boolean setWay2(int[][] map, int i, int j) { } if (map[i][j] == 0) { // if the ball haven't gone through this point // then the ball follows the move strategy : up->right->down->left - map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。 + map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 + // first。 if (setWay2(map, i - 1, j)) { // go up return true; } else if (setWay2(map, i, j + 1)) { // go right diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java index a567c57b451a..6d45a73a821b 100644 --- a/src/main/java/com/thealgorithms/backtracking/NQueens.java +++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java @@ -47,14 +47,8 @@ public static void placeQueens(final int queens) { List<List<String>> arrangements = new ArrayList<List<String>>(); getSolution(queens, arrangements, new int[queens], 0); if (arrangements.isEmpty()) { - System.out.println( - "There is no way to place " + - queens + - " queens on board of size " + - queens + - "x" + - queens - ); + System.out.println("There is no way to place " + queens + " queens on board of size " + + queens + "x" + queens); } else { System.out.println("Arrangement for placing " + queens + " queens"); } @@ -73,11 +67,7 @@ public static void placeQueens(final int queens) { * @param columnIndex: This is the column in which queen is being placed */ private static void getSolution( - int boardSize, - List<List<String>> solutions, - int[] columns, - int columnIndex - ) { + int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) { if (columnIndex == boardSize) { // this means that all queens have been placed List<String> sol = new ArrayList<String>(); @@ -96,7 +86,8 @@ private static void getSolution( for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) { columns[columnIndex] = rowIndex; if (isPlacedCorrectly(columns, rowIndex, columnIndex)) { - // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column + // If queen is placed successfully at rowIndex in column=columnIndex then try + // placing queen in next column getSolution(boardSize, solutions, columns, columnIndex + 1); } } @@ -111,11 +102,7 @@ private static void getSolution( * @param columnIndex: column in which queen is being placed * @return true: if queen can be placed safely false: otherwise */ - private static boolean isPlacedCorrectly( - int[] columns, - int rowIndex, - int columnIndex - ) { + private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { for (int i = 0; i < columnIndex; i++) { int diff = Math.abs(columns[i] - rowIndex); if (diff == 0 || columnIndex - i == diff) { diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java index dc4738583358..72af17d48bd4 100644 --- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java +++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java @@ -1,11 +1,10 @@ package com.thealgorithms.backtracking; - /* * Problem Statement : - * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers. - * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. - * Therefore output will be 1. + * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers + * of unique, natural numbers. For example, if N=100 and X=3, we have to find all combinations of + * unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. Therefore output will be 1. */ public class PowerSum { @@ -16,26 +15,29 @@ public int powSum(int N, int X) { return count; } - //here i is the natural number which will be raised by X and added in sum. + // here i is the natural number which will be raised by X and added in sum. public void Sum(int N, int X, int i) { - //if sum is equal to N that is one of our answer and count is increased. + // if sum is equal to N that is one of our answer and count is increased. if (sum == N) { count++; return; - } //we will be adding next natural number raised to X only if on adding it in sum the result is less than N. + } // we will be adding next natural number raised to X only if on adding it in sum the + // result is less than N. else if (sum + power(i, X) <= N) { sum += power(i, X); Sum(N, X, i + 1); - //backtracking and removing the number added last since no possible combination is there with it. + // backtracking and removing the number added last since no possible combination is + // there with it. sum -= power(i, X); } if (power(i, X) < N) { - //calling the sum function with next natural number after backtracking if when it is raised to X is still less than X. + // calling the sum function with next natural number after backtracking if when it is + // raised to X is still less than X. Sum(N, X, i + 1); } } - //creating a separate power function so that it can be used again and again when required. + // creating a separate power function so that it can be used again and again when required. private int power(int a, int b) { return (int) Math.pow(a, b); } diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java index affac0ee6ac2..4ab81bfd7d67 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -1,13 +1,12 @@ package com.thealgorithms.backtracking; - /* Word Search Problem (https://en.wikipedia.org/wiki/Word_search) Given an m x n grid of characters board and a string word, return true if word exists in the grid. -The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or -vertically neighboring. The same letter cell may not be used more than once. +The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are +those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = @@ -27,8 +26,8 @@ Word Search Problem (https://en.wikipedia.org/wiki/Word_search) Depth First Search in matrix (as multiple sources possible) with backtracking like finding cycle in a directed graph. Maintain a record of path - Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times - Sx = O(L) : stack size is max L + Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we + do it L times Sx = O(L) : stack size is max L */ public class WordSearch { @@ -52,8 +51,7 @@ private boolean doDFS(int x, int y, int nextIdx) { int yi = y + dy[i]; if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) { boolean exists = doDFS(xi, yi, nextIdx + 1); - if (exists) - return true; + if (exists) return true; } } visited[x][y] = false; @@ -68,12 +66,10 @@ public boolean exist(char[][] board, String word) { if (board[i][j] == word.charAt(0)) { visited = new boolean[board.length][board[0].length]; boolean exists = doDFS(i, j, 1); - if (exists) - return true; + if (exists) return true; } } } return false; } } - diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java index c5cb286c7772..46886cbcb366 100644 --- a/src/main/java/com/thealgorithms/ciphers/AES.java +++ b/src/main/java/com/thealgorithms/ciphers/AES.java @@ -2395,9 +2395,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { // apply S-Box to all 8-Bit Substrings for (int i = 0; i < 4; i++) { - StringBuilder currentByteBits = new StringBuilder( - rBytes.substring(i * 2, (i + 1) * 2) - ); + StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2)); int currentByte = Integer.parseInt(currentByteBits.toString(), 16); currentByte = SBOX[currentByte]; @@ -2407,8 +2405,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { currentByte = currentByte ^ RCON[rconCounter]; } - currentByteBits = - new StringBuilder(Integer.toHexString(currentByte)); + currentByteBits = new StringBuilder(Integer.toHexString(currentByte)); // Add zero padding while (currentByteBits.length() < 2) { @@ -2416,12 +2413,8 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { } // 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); @@ -2438,16 +2431,16 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) { public static BigInteger[] keyExpansion(BigInteger initialKey) { BigInteger[] roundKeys = { initialKey, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, - BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, }; // initialize rcon iteration @@ -2455,23 +2448,18 @@ public static BigInteger[] keyExpansion(BigInteger initialKey) { for (int i = 1; i < 11; i++) { // get the previous 32 bits the key - BigInteger t = - roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); + BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16)); // split previous key into 8-bit segments BigInteger[] prevKey = { roundKeys[i - 1].remainder(new BigInteger("100000000", 16)), - roundKeys[i - 1].remainder( - new BigInteger("10000000000000000", 16) - ) + roundKeys[i - 1] + .remainder(new BigInteger("10000000000000000", 16)) .divide(new BigInteger("100000000", 16)), - roundKeys[i - 1].remainder( - new BigInteger("1000000000000000000000000", 16) - ) + roundKeys[i - 1] + .remainder(new BigInteger("1000000000000000000000000", 16)) .divide(new BigInteger("10000000000000000", 16)), - roundKeys[i - 1].divide( - new BigInteger("1000000000000000000000000", 16) - ), + roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)), }; // run schedule core @@ -2527,9 +2515,7 @@ public static int[] splitBlockIntoCells(BigInteger block) { public static BigInteger mergeCellsIntoBlock(int[] cells) { StringBuilder blockBits = new StringBuilder(); for (int i = 0; i < 16; i++) { - StringBuilder cellBits = new StringBuilder( - Integer.toBinaryString(cells[i]) - ); + StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i])); // Append leading 0 for full "8-bit" strings while (cellBits.length() < 8) { @@ -2545,10 +2531,7 @@ public static BigInteger mergeCellsIntoBlock(int[] cells) { /** * @return ciphertext XOR key */ - public static BigInteger addRoundKey( - BigInteger ciphertext, - BigInteger key - ) { + public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) { return ciphertext.xor(key); } @@ -2669,14 +2652,10 @@ public static BigInteger mixColumns(BigInteger ciphertext) { cells[i * 4 + 3], }; - outputCells[i * 4] = - MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; - outputCells[i * 4 + 1] = - row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; - outputCells[i * 4 + 2] = - row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; - outputCells[i * 4 + 3] = - MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; + outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3]; + outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3]; + outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]]; + outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]]; } return mergeCellsIntoBlock(outputCells); } @@ -2697,26 +2676,13 @@ public static BigInteger mixColumnsDec(BigInteger ciphertext) { cells[i * 4 + 3], }; - outputCells[i * 4] = - MULT14[row[0]] ^ - MULT11[row[1]] ^ - MULT13[row[2]] ^ - MULT9[row[3]]; - outputCells[i * 4 + 1] = - MULT9[row[0]] ^ - MULT14[row[1]] ^ - MULT11[row[2]] ^ - MULT13[row[3]]; - outputCells[i * 4 + 2] = - MULT13[row[0]] ^ - MULT9[row[1]] ^ - MULT14[row[2]] ^ - MULT11[row[3]]; - outputCells[i * 4 + 3] = - MULT11[row[0]] ^ - MULT13[row[1]] ^ - MULT9[row[2]] ^ - MULT14[row[3]]; + outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]]; + outputCells[i * 4 + 1] + = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]]; + outputCells[i * 4 + 2] + = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]]; + outputCells[i * 4 + 3] + = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]]; } return mergeCellsIntoBlock(outputCells); } @@ -2780,9 +2746,7 @@ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) { public static void main(String[] args) { try (Scanner input = new Scanner(System.in)) { - System.out.println( - "Enter (e) letter for encrpyt or (d) letter for decrypt :" - ); + System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :"); char choice = input.nextLine().charAt(0); String in; switch (choice) { diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index 051b34c2293a..c010d532437f 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -1,10 +1,10 @@ package com.thealgorithms.ciphers; +import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.*; import javax.crypto.spec.GCMParameterSpec; -import java.security.InvalidAlgorithmParameterException; /** * This example program shows how AES encryption and decryption can be done in @@ -29,12 +29,8 @@ public static void main(String[] args) throws Exception { String decryptedText = decryptText(cipherText, secKey); System.out.println("Original Text:" + plainText); - System.out.println( - "AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()) - ); - System.out.println( - "Encrypted Text (Hex Form):" + bytesToHex(cipherText) - ); + System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); + System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); System.out.println("Descrypted Text:" + decryptedText); } @@ -45,8 +41,7 @@ public static void main(String[] args) throws Exception { * @return secKey (Secret key that we encrypt using it) * @throws NoSuchAlgorithmException (from KeyGenrator) */ - public static SecretKey getSecretEncryptionKey() - throws NoSuchAlgorithmException { + public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); aesKeyGenerator.init(128); // The AES key size in number of bits return aesKeyGenerator.generateKey(); @@ -63,7 +58,8 @@ public static SecretKey getSecretEncryptionKey() * @throws IllegalBlockSizeException (from Cipher) */ public static byte[] encryptText(String plainText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 aesCipher = Cipher.getInstance("AES/GCM/NoPadding"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); @@ -76,8 +72,8 @@ public static byte[] encryptText(String plainText, SecretKey secKey) * @return plainText */ public static String decryptText(byte[] byteCipherText, SecretKey secKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, - IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, + IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { // AES defaults to AES/ECB/PKCS5Padding in Java 7 Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV()); diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java index a6fe0ab9290f..9ff63ddfe7c5 100644 --- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java @@ -15,8 +15,7 @@ static String encryptMessage(char[] msg) { {here x is msg[i] and m is 26} and added 'A' to bring it in range of ascii alphabet[ 65-90 | A-Z ] */ if (msg[i] != ' ') { - cipher = - cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); + cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); } else { // else simply append space character cipher += msg[i]; } @@ -29,8 +28,8 @@ static String decryptCipher(String cipher) { int a_inv = 0; int flag = 0; - //Find a^-1 (the multiplicative inverse of a - //in the group of integers modulo m.) + // Find a^-1 (the multiplicative inverse of a + // in the group of integers modulo m.) for (int i = 0; i < 26; i++) { flag = (a * i) % 26; @@ -45,12 +44,8 @@ static String decryptCipher(String cipher) { {here x is cipher[i] and m is 26} and added 'A' to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ if (cipher.charAt(i) != ' ') { - msg = - msg + - (char) ( - ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A' - ); - } else { //else simply append space character + msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); + } else { // else simply append space character msg += cipher.charAt(i); } } @@ -67,8 +62,6 @@ public static void main(String[] args) { System.out.println("Encrypted Message is : " + cipherText); // Calling Decryption function - System.out.println( - "Decrypted Message is: " + decryptCipher(cipherText) - ); + System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); } } diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index 8864fc75f342..bce7f699d432 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -10,7 +10,7 @@ public class Blowfish { - //Initializing substitution boxes + // Initializing substitution boxes String[][] S = { { "d1310ba6", @@ -1046,7 +1046,7 @@ public class Blowfish { }, }; - //Initializing subkeys with digits of pi + // Initializing subkeys with digits of pi String[] P = { "243f6a88", "85a308d3", @@ -1068,7 +1068,7 @@ public class Blowfish { "8979fb1b", }; - //Initializing modVal to 2^32 + // Initializing modVal to 2^32 long modVal = 4294967296L; /** @@ -1098,7 +1098,8 @@ private String hexToBin(String hex) { * This method returns hexadecimal representation of the binary number passed as parameter * * @param binary Number for which hexadecimal representation is required - * @return String object which is a hexadecimal representation of the binary number passed as parameter + * @return String object which is a hexadecimal representation of the binary number passed as + * parameter */ private String binToHex(String binary) { long num = Long.parseUnsignedLong(binary, 2); @@ -1109,7 +1110,8 @@ private String binToHex(String binary) { } /** - * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters + * This method returns a string obtained by XOR-ing two strings of same length passed a method + * parameters * * @param String a and b are string objects which will be XORed and are to be of same length * @return String object obtained by XOR operation on String a and String b @@ -1118,17 +1120,19 @@ private String xor(String a, String b) { 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; } /** - * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32 + * This method returns addition of two hexadecimal numbers passed as parameters and moded with + * 2^32 * * @param String a and b are hexadecimal numbers - * @return String object which is a is addition that is then moded with 2^32 of hex numbers passed as parameters + * @return String object which is a is addition that is then moded with 2^32 of hex numbers + * passed as parameters */ private String addBin(String a, String b) { String ans = ""; @@ -1140,20 +1144,17 @@ private String addBin(String a, String b) { return ans.substring(ans.length() - 8); } - /*F-function splits the 32-bit input into four 8-bit quarters - and uses the quarters as input to the S-boxes. - The S-boxes accept 8-bit input and produce 32-bit output. - The outputs are added modulo 232 and XORed to produce the final 32-bit output - */ + /*F-function splits the 32-bit input into four 8-bit quarters + and uses the quarters as input to the S-boxes. + The S-boxes accept 8-bit input and produce 32-bit output. + The outputs are added modulo 232 and XORed to produce the final 32-bit output + */ private String f(String plainText) { String[] a = new String[4]; String ans = ""; for (int i = 0; i < 8; i += 2) { - //column number for S-box is a 8-bit value - long col = Long.parseUnsignedLong( - hexToBin(plainText.substring(i, i + 2)), - 2 - ); + // column number for S-box is a 8-bit value + long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2); a[i / 2] = S[i / 2][(int) col]; } ans = addBin(a[0], a[1]); @@ -1162,30 +1163,30 @@ private String f(String plainText) { return ans; } - //generate subkeys + // generate subkeys private void keyGenerate(String key) { int j = 0; for (int i = 0; i < P.length; i++) { - //XOR-ing 32-bit parts of the key with initial subkeys + // XOR-ing 32-bit parts of the key with initial subkeys P[i] = xor(P[i], key.substring(j, j + 8)); j = (j + 8) % key.length(); } } - //round function + // round function private String round(int time, String plainText) { String left, right; left = plainText.substring(0, 8); right = plainText.substring(8, 16); left = xor(left, P[time]); - //output from F function + // output from F function String fOut = f(left); right = xor(fOut, right); - //swap left and right + // swap left and right return right + left; } @@ -1198,12 +1199,12 @@ private String round(int time, String plainText) { * @return String cipherText is the encrypted value */ String encrypt(String plainText, String key) { - //generating key + // generating key keyGenerate(key); for (int i = 0; i < 16; i++) plainText = round(i, plainText); - //postprocessing + // postprocessing String right = plainText.substring(0, 8); String left = plainText.substring(8, 16); right = xor(right, P[16]); @@ -1220,12 +1221,12 @@ String encrypt(String plainText, String key) { * @return String plainText is the decrypted text */ String decrypt(String cipherText, String key) { - //generating key + // generating key keyGenerate(key); for (int i = 17; i > 1; i--) cipherText = round(i, cipherText); - //postprocessing + // postprocessing String right = cipherText.substring(0, 8); String left = cipherText.substring(8, 16); right = xor(right, P[1]); diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java index a5f89fba7180..6011909abc33 100644 --- a/src/main/java/com/thealgorithms/ciphers/Caesar.java +++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java @@ -23,16 +23,19 @@ public String encode(String message, int shift) { final int length = message.length(); for (int i = 0; i < length; i++) { - // int current = message.charAt(i); //using char to shift characters because ascii + // int current = message.charAt(i); //using char to shift characters because + // ascii // is in-order latin alphabet char current = message.charAt(i); // Java law : char + int = char if (isCapitalLatinLetter(current)) { current += shift; - encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters + 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); } @@ -56,10 +59,12 @@ public String decode(String encryptedMessage, int shift) { 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 35f15e587d2f..70b1f7ea147b 100644 --- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java @@ -12,9 +12,8 @@ public class ColumnarTranspositionCipher { private static String keyword; private static Object[][] table; private static String abecedarium; - public static final String ABECEDARIUM = - "abcdefghijklmnopqrstuvwxyzABCDEFG" + - "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; + public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG" + + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; private static final String ENCRYPTION_FIELD = "≈"; private static final char ENCRYPTION_FIELD_CHAR = '≈'; @@ -50,14 +49,10 @@ public static String encrpyter(String word, String keyword) { * @return a String with the word encrypted by the Columnar Transposition * Cipher Rule */ - public static String encrpyter( - String word, - String keyword, - String abecedarium - ) { + 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(); @@ -120,9 +115,7 @@ private static Object[][] tableBuilder(String word) { * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { - if ( - word.length() / keyword.length() > word.length() / keyword.length() - ) { + if (word.length() / keyword.length() > word.length() / keyword.length()) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); @@ -147,22 +140,12 @@ private static Object[] findElements() { private static Object[][] sortTable(Object[][] table) { Object[][] tableSorted = new Object[table.length][table[0].length]; for (int i = 0; i < tableSorted.length; i++) { - System.arraycopy( - table[i], - 0, - tableSorted[i], - 0, - tableSorted[i].length - ); + System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length); } for (int i = 0; i < tableSorted[0].length; i++) { for (int j = i + 1; j < tableSorted[0].length; j++) { if ((int) tableSorted[0][i] > (int) table[0][j]) { - Object[] column = getColumn( - tableSorted, - tableSorted.length, - i - ); + Object[] column = getColumn(tableSorted, tableSorted.length, i); switchColumns(tableSorted, j, i, column); } } @@ -182,11 +165,7 @@ private static Object[] getColumn(Object[][] table, int rows, int column) { } private static void switchColumns( - Object[][] table, - int firstColumnIndex, - int secondColumnIndex, - Object[] columnToSwitch - ) { + Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { for (int i = 0; i < table.length; i++) { table[i][secondColumnIndex] = table[i][firstColumnIndex]; table[i][firstColumnIndex] = columnToSwitch[i]; @@ -217,22 +196,12 @@ private static void showTable() { public static void main(String[] args) { String keywordForExample = "asd215"; - String wordBeingEncrypted = - "This is a test of the Columnar Transposition Cipher"; - System.out.println( - "### Example of Columnar Transposition Cipher ###\n" - ); + String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; + System.out.println("### Example of Columnar Transposition Cipher ###\n"); System.out.println("Word being encryped ->>> " + wordBeingEncrypted); - System.out.println( - "Word encrypted ->>> " + - ColumnarTranspositionCipher.encrpyter( - wordBeingEncrypted, - keywordForExample - ) - ); - System.out.println( - "Word decryped ->>> " + ColumnarTranspositionCipher.decrypter() - ); + System.out.println("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 aae8282eae42..b6ca8fb8a87d 100644 --- a/src/main/java/com/thealgorithms/ciphers/DES.java +++ b/src/main/java/com/thealgorithms/ciphers/DES.java @@ -1,8 +1,9 @@ package com.thealgorithms.ciphers; /** - * This class is build to demonstrate the application of the DES-algorithm (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a - * plain English message. The supplied key must be in form of a 64 bit binary String. + * This class is build to demonstrate the application of the DES-algorithm + * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied + * key must be in form of a 64 bit binary String. */ public class DES { @@ -12,7 +13,8 @@ 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"); } } @@ -30,170 +32,102 @@ public void setKey(String key) { sanitize(key); this.key = key; } - - //Permutation table to convert initial 64 bit key to 56 bit key - private static int[] PC1 = - { - 57, 49, 41, 33, 25, 17, 9, - 1, 58, 50, 42, 34, 26, 18, - 10, 2, 59, 51, 43, 35, 27, - 19, 11, 3, 60, 52, 44, 36, - 63, 55, 47, 39, 31, 23, 15, - 7, 62, 54, 46, 38, 30, 22, - 14, 6, 61, 53, 45, 37, 29, - 21, 13, 5, 28, 20, 12, 4 - }; - - //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 - }; - - //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 - }; - - //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 - }; - - //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[][] 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[][] 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[][] 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[][] 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 - }; - - //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 - }; + + // 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}; + + // 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}; + + // 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}; + + // 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}; + + // 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[][] 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[][] 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[][] 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[][] 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}; + + // 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}; private String[] getSubkeys(String originalKey) { - StringBuilder permutedKey = new StringBuilder(); //Initial permutation of keys via PC1 + StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1 int i, j; for (i = 0; i < 56; i++) { - permutedKey.append(originalKey.charAt(PC1[i] - 1)); + permutedKey.append(originalKey.charAt(PC1[i] - 1)); } String subKeys[] = new String[16]; String initialPermutedKey = permutedKey.toString(); String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28); - - //We will now operate on the left and right halves of the permutedKey + + // We will now operate on the left and right halves of the permutedKey for (i = 0; i < 16; i++) { String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]); String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]); subKeys[i] = Cn + Dn; - C0 = Cn; //Re-assign the values to create running permutation + C0 = Cn; // Re-assign the values to create running permutation D0 = Dn; } - //Let us shrink the keys to 48 bits (well, characters here) using PC2 + // Let us shrink the keys to 48 bits (well, characters here) using PC2 for (i = 0; i < 16; i++) { String key = subKeys[i]; permutedKey.setLength(0); @@ -244,16 +178,17 @@ private String feistel(String messageBlock, String key) { String mixedKey = XOR(expandedKey.toString(), key); StringBuilder substitutedString = new StringBuilder(); - //Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits + // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits 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); } - StringBuilder permutedString = new StringBuilder(); + StringBuilder permutedString = new StringBuilder(); for (i = 0; i < 32; i++) { permutedString.append(substitutedString.charAt(permutation[i] - 1)); } @@ -269,7 +204,7 @@ private String encryptBlock(String message, String keys[]) { } String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32); - //Iterate 16 times + // Iterate 16 times for (i = 0; i < 16; i++) { String Ln = R0; // Previous Right block String Rn = XOR(L0, feistel(R0, keys[i])); @@ -277,7 +212,7 @@ private String encryptBlock(String message, String keys[]) { R0 = Rn; } - String combinedBlock = R0 + L0; //Reverse the 16th block + String combinedBlock = R0 + L0; // Reverse the 16th block permutedMessage.setLength(0); for (i = 0; i < 64; i++) { permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1)); @@ -285,7 +220,7 @@ private String encryptBlock(String message, String keys[]) { return permutedMessage.toString(); } - //To decode, we follow the same process as encoding, but with reversed keys + // To decode, we follow the same process as encoding, but with reversed keys private String decryptBlock(String message, String keys[]) { String reversedKeys[] = new String[keys.length]; for (int i = 0; i < keys.length; i++) { @@ -307,7 +242,7 @@ public String encrypt(String message) { message = padLast(message, desiredLength); } - for (i = 0; i < l; i+= 8) { + for (i = 0; i < l; i += 8) { String block = message.substring(i, i + 8); StringBuilder bitBlock = new StringBuilder(); byte[] bytes = block.getBytes(); @@ -327,18 +262,19 @@ public String decrypt(String message) { 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) { + for (i = 0; i < l; i += 64) { String block = message.substring(i, i + 64); String result = decryptBlock(block.toString(), subKeys); byte res[] = new byte[8]; - for (j = 0; j < 64; j+=8) { - res[j / 8] = (byte)Integer.parseInt(result.substring(j, j + 8), 2); + for (j = 0; j < 64; j += 8) { + res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2); } 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/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index ffc7e08bedf7..a3226cef7de1 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -4,10 +4,11 @@ /* * Java Implementation of Hill Cipher - * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25. - * To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26. - * To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption. - * The cipher key and plaintext/ciphertext are user inputs. + * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number + * belonging to the set Z26 where A=0 , B=1, ..... Z=25. To encrypt a message, each block of n + * letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against + * modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used + * for encryption. The cipher key and plaintext/ciphertext are user inputs. * @author Ojasva Jain */ public class HillCipher { @@ -28,7 +29,7 @@ static void encrypt(String message) { keyMatrix[i][j] = userInput.nextInt(); } } - //check if det = 0 + // check if det = 0 validateDeterminant(keyMatrix, matrixSize); int[][] messageVector = new int[matrixSize][1]; @@ -62,7 +63,7 @@ static void encrypt(String message) { System.out.println("Ciphertext: " + CipherText); } - //Following function decrypts a message + // Following function decrypts a message static void decrypt(String message) { message = message.toUpperCase(); // Get key matrix @@ -75,10 +76,10 @@ static void decrypt(String message) { keyMatrix[i][j] = userInput.nextInt(); } } - //check if det = 0 + // check if det = 0 validateDeterminant(keyMatrix, n); - //solving for the required plaintext message + // solving for the required plaintext message int[][] messageVector = new int[n][1]; String PlainText = ""; int[][] plainMatrix = new int[n][1]; @@ -157,9 +158,7 @@ static void hillCipher(String message) { static void validateDeterminant(int[][] keyMatrix, int n) { if (determinant(keyMatrix, n) % 26 == 0) { - System.out.println( - "Invalid key, as determinant = 0. Program Terminated" - ); + System.out.println("Invalid key, as determinant = 0. Program Terminated"); } } diff --git a/src/main/java/com/thealgorithms/ciphers/Polybius.java b/src/main/java/com/thealgorithms/ciphers/Polybius.java index 30eba49807f7..7b5a27807bc4 100644 --- a/src/main/java/com/thealgorithms/ciphers/Polybius.java +++ b/src/main/java/com/thealgorithms/ciphers/Polybius.java @@ -7,7 +7,8 @@ * Letters in alphabet takes place to two dimension table. * Encrypted text is created according to row and column in two dimension table * Decrypted text is generated by looking at the row and column respectively - * Additionally, some letters in english alphabet deliberately throws such as U because U is very similar with V + * Additionally, some letters in english alphabet deliberately throws such as U because U is very + * similar with V * * @author Hikmet ÇAKIR * @since 08-07-2022+03:00 @@ -16,11 +17,11 @@ public class Polybius { private static final char[][] key = { // 0 1 2 3 4 - /* 0 */{ 'A', 'B', 'C', 'D', 'E' }, - /* 1 */{ 'F', 'G', 'H', 'I', 'J' }, - /* 2 */{ 'K', 'L', 'M', 'N', 'O' }, - /* 3 */{ 'P', 'Q', 'R', 'S', 'T' }, - /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' }, + /* 0 */ {'A', 'B', 'C', 'D', 'E'}, + /* 1 */ {'F', 'G', 'H', 'I', 'J'}, + /* 2 */ {'K', 'L', 'M', 'N', 'O'}, + /* 3 */ {'P', 'Q', 'R', 'S', 'T'}, + /* 4 */ {'V', 'W', 'X', 'Y', 'Z'}, }; private static String findLocationByCharacter(final char character) { diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index 08f4e1980f92..e28eaecb3d1b 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -20,8 +20,7 @@ public RSA(int bits) { * @return encrypted message */ public synchronized String encrypt(String message) { - return (new BigInteger(message.getBytes())).modPow(publicKey, modulus) - .toString(); + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); } /** @@ -36,9 +35,7 @@ public synchronized BigInteger encrypt(BigInteger message) { */ public synchronized String decrypt(String encryptedMessage) { return new String( - (new BigInteger(encryptedMessage)).modPow(privateKey, modulus) - .toByteArray() - ); + (new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray()); } /** @@ -57,8 +54,7 @@ public synchronized void generateKeys(int bits) { BigInteger q = new BigInteger(bits / 2, 100, r); modulus = p.multiply(q); - BigInteger m = - (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); + BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); publicKey = BigInteger.valueOf(3L); diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java index 32b08f0cc38b..f6c88ef730ec 100644 --- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java @@ -82,5 +82,4 @@ public String decode(String encryptedMessage, String cipherSmall) { return decoded.toString(); } - } diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java index fe7ff8d03dca..1702f1abb94c 100644 --- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java +++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java @@ -16,21 +16,9 @@ public String encrypt(final String message, final String key) { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append( - (char) ( - (c + key.toUpperCase().charAt(j) - 2 * 'A') % - 26 + - 'A' - ) - ); + result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); } else { - result.append( - (char) ( - (c + key.toLowerCase().charAt(j) - 2 * 'a') % - 26 + - 'a' - ) - ); + result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); } } else { result.append(c); @@ -48,17 +36,9 @@ public String decrypt(final String message, final String key) { char c = message.charAt(i); if (Character.isLetter(c)) { if (Character.isUpperCase(c)) { - result.append( - (char) ( - 'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26 - ) - ); + result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); } else { - result.append( - (char) ( - 'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26 - ) - ); + result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); } } else { result.append(c); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java index b7d36db5c809..809f85072e48 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java @@ -6,7 +6,8 @@ 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 7788efc17774..148a49cf0959 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -9,7 +9,8 @@ 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) { @@ -17,9 +18,9 @@ public void initialize(BitSet sessionKey, BitSet frameCounter) { this.frameCounter = (BitSet) frameCounter.clone(); this.initialFrameCounter = (BitSet) frameCounter.clone(); registers.clear(); - LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); - LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 }); - LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 }); + LFSR lfsr1 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); + LFSR lfsr2 = new LFSR(22, 10, new int[] {20, 21}); + LFSR lfsr3 = new LFSR(23, 10, new int[] {7, 20, 21, 22}); registers.add(lfsr1); registers.add(lfsr2); registers.add(lfsr3); @@ -31,11 +32,7 @@ public void reInitialize() { } public BitSet getNextKeyStream() { - for ( - int cycle = 1; - cycle <= INITIAL_CLOCKING_CYCLES; - ++cycle - ) this.clock(); + for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock(); BitSet result = new BitSet(KEY_STREAM_LENGTH); for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) { diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java index 050657166e77..2d0309a98482 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java @@ -29,12 +29,8 @@ private boolean getMajorityBit() { 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/ciphers/a5/Utils.java b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java index b9220d11f868..abdd11d6b72d 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java @@ -1,8 +1,9 @@ package com.thealgorithms.ciphers.a5; -// Source http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html -//package com.java2s; -//License from project: Open Source License +// Source +// http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html +// package com.java2s; +// License from project: Open Source License import java.util.BitSet; @@ -11,7 +12,7 @@ public class Utils { public static boolean increment(BitSet bits, int size) { int i = size - 1; while (i >= 0 && bits.get(i)) { - bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/ + bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/ } if (i < 0) { return false; diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java index b5974dd65f3b..c6450a4555ce 100644 --- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java @@ -30,13 +30,8 @@ public static void main(String[] args) { 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!"); @@ -47,12 +42,7 @@ public static void main(String[] args) { continue; } System.out.print( - "Enter end base (between " + - MINIMUM_BASE + - " and " + - MAXIMUM_BASE + - "): " - ); + "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 df547ffb5610..a77be2f50e07 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java @@ -11,9 +11,7 @@ public class DecimalToAnyBase { public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in) - ); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the decimal input below: "); int decInput = Integer.parseInt(br.readLine()); System.out.println(); @@ -22,15 +20,10 @@ public static void main(String[] args) throws Exception { int base = Integer.parseInt(br.readLine()); System.out.println(); - System.out.println("Decimal Input" + " is: " + decInput); - System.out.println( - "Value of " + - decInput + - " in base " + - base + - " is: " + - convertToAnyBase(decInput, base) - ); + System.out.println("Decimal Input" + + " is: " + decInput); + System.out.println("Value of " + decInput + " in base " + base + + " is: " + convertToAnyBase(decInput, base)); br.close(); } diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java index c87508c62e86..a6119cfbc9bc 100644 --- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java @@ -24,9 +24,7 @@ public static void main(String[] args) { public static void conventionalConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf( - "Conventional conversion.%n Enter the decimal number: " - ); + System.out.printf("Conventional conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = n % 2; diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java index 2a57fbde5c41..69707c80530a 100644 --- a/src/main/java/com/thealgorithms/conversions/HexToOct.java +++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java @@ -61,7 +61,8 @@ public static void main(String[] args) { 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 4fad34ec8844..dc7310061009 100644 --- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java +++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java @@ -19,69 +19,30 @@ public static void main(String[] args) { // Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html // Test hsvToRgb-method - assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 }); - assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 }); - assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 }); - assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 }); - assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 }); - assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 }); - assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 }); - assert Arrays.equals( - hsvToRgb(180, 0.5, 0.5), - new int[] { 64, 128, 128 } - ); - assert Arrays.equals( - hsvToRgb(234, 0.14, 0.88), - new int[] { 193, 196, 224 } - ); - assert Arrays.equals( - hsvToRgb(330, 0.75, 0.5), - new int[] { 128, 32, 80 } - ); + assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0}); + assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255}); + assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0}); + assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0}); + assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0}); + assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255}); + assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255}); + assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128}); + assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224}); + assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80}); // Test rgbToHsv-method // approximate-assertions needed because of small deviations due to converting between // int-values and double-values. - assert approximatelyEqualHsv( - rgbToHsv(0, 0, 0), - new double[] { 0, 0, 0 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 255, 255), - new double[] { 0, 0, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 0, 0), - new double[] { 0, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 255, 0), - new double[] { 60, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(0, 255, 0), - new double[] { 120, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(0, 0, 255), - new double[] { 240, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(255, 0, 255), - new double[] { 300, 1, 1 } - ); - assert approximatelyEqualHsv( - rgbToHsv(64, 128, 128), - new double[] { 180, 0.5, 0.5 } - ); - assert approximatelyEqualHsv( - rgbToHsv(193, 196, 224), - new double[] { 234, 0.14, 0.88 } - ); - assert approximatelyEqualHsv( - rgbToHsv(128, 32, 80), - new double[] { 330, 0.75, 0.5 } - ); + assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[] {0, 0, 0}); + assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[] {0, 0, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[] {0, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[] {60, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[] {120, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[] {240, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[] {300, 1, 1}); + assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[] {180, 0.5, 0.5}); + assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[] {234, 0.14, 0.88}); + assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[] {330, 0.75, 0.5}); } /** @@ -94,35 +55,23 @@ assert approximatelyEqualHsv( */ public static int[] hsvToRgb(double hue, double saturation, double value) { if (hue < 0 || hue > 360) { - throw new IllegalArgumentException( - "hue should be between 0 and 360" - ); + throw new IllegalArgumentException("hue should be between 0 and 360"); } if (saturation < 0 || saturation > 1) { - throw new IllegalArgumentException( - "saturation should be between 0 and 1" - ); + throw new IllegalArgumentException("saturation should be between 0 and 1"); } if (value < 0 || value > 1) { - throw new IllegalArgumentException( - "value should be between 0 and 1" - ); + throw new IllegalArgumentException("value should be between 0 and 1"); } double chroma = value * saturation; double hueSection = hue / 60; - double secondLargestComponent = - chroma * (1 - Math.abs(hueSection % 2 - 1)); + double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1)); double matchValue = value - chroma; - return getRgbBySection( - hueSection, - chroma, - matchValue, - secondLargestComponent - ); + return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent); } /** @@ -135,21 +84,15 @@ public static int[] hsvToRgb(double hue, double saturation, double value) { */ public static double[] rgbToHsv(int red, int green, int blue) { if (red < 0 || red > 255) { - throw new IllegalArgumentException( - "red should be between 0 and 255" - ); + throw new IllegalArgumentException("red should be between 0 and 255"); } if (green < 0 || green > 255) { - throw new IllegalArgumentException( - "green should be between 0 and 255" - ); + throw new IllegalArgumentException("green should be between 0 and 255"); } if (blue < 0 || blue > 255) { - throw new IllegalArgumentException( - "blue should be between 0 and 255" - ); + throw new IllegalArgumentException("blue should be between 0 and 255"); } double dRed = (double) red / 255; @@ -172,7 +115,7 @@ public static double[] rgbToHsv(int red, int green, int blue) { hue = (hue + 360) % 360; - return new double[] { hue, saturation, value }; + return new double[] {hue, saturation, value}; } private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { @@ -184,11 +127,7 @@ private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) { } private static int[] getRgbBySection( - double hueSection, - double chroma, - double matchValue, - double secondLargestComponent - ) { + double hueSection, double chroma, double matchValue, double secondLargestComponent) { int red; int green; int blue; @@ -219,7 +158,7 @@ private static int[] getRgbBySection( blue = convertToInt(secondLargestComponent + matchValue); } - return new int[] { red, green, blue }; + return new int[] {red, green, blue}; } private static int convertToInt(double input) { diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java index 81c8d9bd1f3c..39e0c4438a6e 100644 --- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java +++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java @@ -58,11 +58,8 @@ public static String convertTurkishToLatin(String param) { '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/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java index 96c72fc04d6a..5e1c815ff9b3 100644 --- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java +++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java @@ -9,7 +9,7 @@ public class CircularBuffer<Item> { private final AtomicInteger size = new AtomicInteger(0); public CircularBuffer(int size) { - //noinspection unchecked + // noinspection unchecked this.buffer = (Item[]) new Object[size]; this.putPointer = new CircularPointer(0, size); this.getPointer = new CircularPointer(0, size); @@ -24,8 +24,7 @@ public boolean isFull() { } public Item get() { - if (isEmpty()) - return null; + if (isEmpty()) return null; Item item = buffer[getPointer.getAndIncrement()]; size.decrementAndGet(); @@ -33,8 +32,7 @@ public Item get() { } public boolean put(Item item) { - if (isFull()) - return false; + if (isFull()) return false; buffer[putPointer.getAndIncrement()] = item; size.incrementAndGet(); @@ -51,8 +49,7 @@ public CircularPointer(int pointer, int max) { } public int getAndIncrement() { - if (pointer == max) - pointer = 0; + if (pointer == max) pointer = 0; int tmp = pointer; pointer++; return tmp; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java index de1f6af64de0..03a1d59e1b20 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java @@ -43,7 +43,8 @@ public LFUCache(Integer capacity) { * This method returns value present in the cache corresponding to the key passed as parameter * * @param <K> key for which value is to be retrieved - * @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is not present in the cache + * @returns <V> object corresponding to the key passed as parameter, returns null if <K> key is + * not present in the cache */ public V get(K key) { if (this.map.get(key) == null) { diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java index 976a4fef1c29..fcb7d975bdb4 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java @@ -126,14 +126,10 @@ static final class Entry<I, J> { private I key; private J value; - public Entry() {} - - public Entry( - Entry<I, J> preEntry, - Entry<I, J> nextEntry, - I key, - J value - ) { + public Entry() { + } + + public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java index fc55c4e4d730..30f914968c3b 100644 --- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java +++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java @@ -124,14 +124,10 @@ static final class Entry<I, J> { private I key; private J value; - public Entry() {} - - public Entry( - Entry<I, J> preEntry, - Entry<I, J> nextEntry, - I key, - J value - ) { + public Entry() { + } + + public Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; diff --git a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java index 1b6dd0c5470f..fb7783575e57 100644 --- a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java +++ b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java @@ -44,8 +44,7 @@ public DynamicArray() { */ public void add(final E element) { if (this.size == this.elements.length) { - this.elements = - Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); + this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity)); } this.elements[this.size] = element; @@ -84,8 +83,7 @@ public E remove(final int index) { fastRemove(this.elements, index); if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) { - this.elements = - Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); + this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2)); } return oldElement; } @@ -116,13 +114,7 @@ private void fastRemove(final Object[] elements, final int index) { final int newSize = this.size - 1; if (newSize > index) { - System.arraycopy( - elements, - index + 1, - elements, - index, - newSize - index - ); + System.arraycopy(elements, index + 1, elements, index, newSize - index); } elements[this.size = newSize] = null; @@ -144,9 +136,7 @@ private int newCapacity(int capacity) { */ @Override public String toString() { - return Arrays.toString( - Arrays.stream(this.elements).filter(Objects::nonNull).toArray() - ); + return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray()); } /** 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 fe01cecde42e..ea75e067f949 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java @@ -1,5 +1,5 @@ /* - Time Complexity = O(E), where E is equal to the number of edges + Time Complexity = O(E), where E is equal to the number of edges */ package com.thealgorithms.datastructures.graphs; @@ -64,13 +64,10 @@ private static class PathAndDistance { private int distance; // distance advanced so far. private ArrayList<Integer> path; // list of visited nodes in this path. - private int estimated; // heuristic value associated to the last node od the path (current node). + private int + estimated; // heuristic value associated to the last node od the path (current node). - public PathAndDistance( - int distance, - ArrayList<Integer> path, - int estimated - ) { + public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) { this.distance = distance; this.path = path; this.estimated = estimated; @@ -90,25 +87,16 @@ public int getEstimated() { private void printSolution() { if (this.path != null) { - System.out.println( - "Optimal path: " + - this.path + - ", distance: " + - this.distance - ); + System.out.println("Optimal path: " + this.path + ", distance: " + this.distance); } else { - System.out.println( - "There is no path available to connect the points" - ); + System.out.println("There is no path available to connect the points"); } } } private static void initializeGraph(Graph graph, ArrayList<Integer> data) { for (int i = 0; i < data.size(); i += 4) { - graph.addEdge( - new Edge(data.get(i), data.get(i + 1), data.get(i + 2)) - ); + graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); } /* .x. node @@ -165,123 +153,24 @@ public static void main(String[] args) { }; Graph graph = new Graph(20); - ArrayList<Integer> graphData = new ArrayList<>( - Arrays.asList( - 0, - 19, - 75, - null, - 0, - 15, - 140, - null, - 0, - 16, - 118, - null, - 19, - 12, - 71, - null, - 12, - 15, - 151, - null, - 16, - 9, - 111, - null, - 9, - 10, - 70, - null, - 10, - 3, - 75, - null, - 3, - 2, - 120, - null, - 2, - 14, - 146, - null, - 2, - 13, - 138, - null, - 2, - 6, - 115, - null, - 15, - 14, - 80, - null, - 15, - 5, - 99, - null, - 14, - 13, - 97, - null, - 5, - 1, - 211, - null, - 13, - 1, - 101, - null, - 6, - 1, - 160, - null, - 1, - 17, - 85, - null, - 17, - 7, - 98, - null, - 7, - 4, - 86, - null, - 17, - 18, - 142, - null, - 18, - 8, - 92, - null, - 8, - 11, - 87 - ) - ); + ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140, + null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10, + 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6, + 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, + 101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18, + 142, null, 18, 8, 92, null, 8, 11, 87)); initializeGraph(graph, graphData); PathAndDistance solution = aStar(3, 1, graph, heuristic); solution.printSolution(); } - public static PathAndDistance aStar( - int from, - int to, - Graph graph, - int[] heuristic - ) { + public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { // nodes are prioritised by the less value of the current distance of their paths, and the // estimated value // given by the heuristic function to reach the destination point from the current point. PriorityQueue<PathAndDistance> queue = new PriorityQueue<>( - Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())) - ); + 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)); @@ -290,34 +179,25 @@ public static PathAndDistance aStar( PathAndDistance currentData = new PathAndDistance(-1, null, -1); while (!queue.isEmpty() && !solutionFound) { currentData = queue.poll(); // first in the queue, best node so keep exploring. - int currentPosition = currentData - .getPath() - .get(currentData.getPath().size() - 1); // current node. + int currentPosition + = currentData.getPath().get(currentData.getPath().size() - 1); // current node. if (currentPosition == to) { solutionFound = true; } else { for (Edge edge : graph.getNeighbours(currentPosition)) { if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles - ArrayList<Integer> updatedPath = new ArrayList<>( - currentData.getPath() - ); - updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance, + ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath()); + updatedPath.add( + edge.getTo()); // Add the new node to the path, update the distance, // and the heuristic function value associated to that path. - queue.add( - new PathAndDistance( - currentData.getDistance() + edge.getWeight(), - updatedPath, - heuristic[edge.getTo()] - ) - ); + queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), + updatedPath, heuristic[edge.getTo()])); } } } } - return (solutionFound) - ? currentData - : new PathAndDistance(-1, null, -1); - // Out of while loop, if there is a solution, the current Data stores the optimal path, and its - // distance + return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); + // Out of while loop, if there is a solution, the current Data stores the optimal path, and + // its distance } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java index aba377329aa0..2998f7e90b52 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java @@ -2,8 +2,10 @@ import java.util.*; -class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have -start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{ +class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs +in form of edges which have start vertex, end vertex and weights. Vertices should be labelled with a +number between 0 and total number of vertices-1,both inclusive*/ +{ int vertex, edge; private Edge[] edges; @@ -49,7 +51,8 @@ public static void main(String[] args) { obj.go(); } - public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and + public void go() { // shows distance to all vertices // Interactive run for understanding the + // class first time. Assumes source vertex is 0 and Scanner sc = new Scanner(System.in); // Grab scanner object for user input int i, v, e, u, ve, w, j, neg = 0; System.out.println("Enter no. of vertices and edges please"); @@ -63,7 +66,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde w = sc.nextInt(); arr[i] = new Edge(u, ve, w); } - int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source + int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance + // between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { @@ -73,10 +77,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde 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; } @@ -84,10 +86,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde } // Final cycle for negative checking 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) { neg = 1; System.out.println("Negative cycle"); break; @@ -113,9 +112,13 @@ public void go() { // shows distance to all vertices // Interactive run for unde * @param end Ending vertex * @param Edge Array of edges */ - public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should + public void show(int source, int end, + Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() + // method // Just shows results of computation, if graph is passed to it. The + // graph should int i, j, v = vertex, e = edge, neg = 0; - double[] dist = new double[v]; // Distance array for holding the finalized shortest path distance between source + double[] dist = new double[v]; // Distance array for holding the finalized shortest path + // distance between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { @@ -125,10 +128,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd 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; } @@ -136,10 +137,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd } // 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 651b3e617794..0bdc5340f897 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java @@ -17,11 +17,7 @@ public class BipartiteGrapfDFS { private static boolean bipartite( - int V, - ArrayList<ArrayList<Integer>> adj, - int[] color, - int node - ) { + int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) { if (color[node] == -1) { color[node] = 1; } @@ -38,10 +34,7 @@ private static boolean bipartite( return true; } - public static boolean isBipartite( - int V, - ArrayList<ArrayList<Integer>> adj - ) { + public static boolean isBipartite(int V, ArrayList<ArrayList<Integer>> adj) { // Code here int[] color = new int[V + 1]; Arrays.fill(color, -1); @@ -57,9 +50,7 @@ public static boolean isBipartite( } public static void main(String[] args) throws IOException { - BufferedReader read = new BufferedReader( - new InputStreamReader(System.in) - ); + BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(read.readLine().trim()); while (t-- > 0) { String[] S = read.readLine().trim().split(" "); diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java index 306abd7e39df..b0add255f59a 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java @@ -137,11 +137,7 @@ public static void main(String[] args) { graphInts.addEdge(8, 10); graphInts.addEdge(10, 8); - System.out.println( - "Amount of different char-graphs: " + graphChars.countGraphs() - ); - System.out.println( - "Amount of different int-graphs: " + graphInts.countGraphs() - ); + System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); + System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); } } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java index 3d6e8a51ebd6..5d5bd3c7469c 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java @@ -24,9 +24,7 @@ public Cycle() { visited[i] = false; } - System.out.println( - "Enter the details of each edges <Start Node> <End Node>" - ); + System.out.println("Enter the details of each edges <Start Node> <End Node>"); for (int i = 0; i < edges; i++) { int start, end; 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 31ed7ef2de2a..1811d4a109ca 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java @@ -1,6 +1,6 @@ /* Refer https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ -for better understanding +for better understanding */ package com.thealgorithms.datastructures.graphs; @@ -45,12 +45,8 @@ void dijkstra(int[][] graph, int src) { 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]; } } @@ -61,23 +57,23 @@ void dijkstra(int[][] graph, int src) { public static void main(String[] args) { int[][] graph = new int[][] { - { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, - { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, - { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, - { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, - { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, - { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, - { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, - { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, - { 0, 0, 2, 0, 0, 0, 6, 7, 0 }, + {0, 4, 0, 0, 0, 0, 0, 8, 0}, + {4, 0, 8, 0, 0, 0, 0, 11, 0}, + {0, 8, 0, 7, 0, 4, 0, 0, 2}, + {0, 0, 7, 0, 9, 14, 0, 0, 0}, + {0, 0, 0, 9, 0, 10, 0, 0, 0}, + {0, 0, 4, 14, 10, 0, 2, 0, 0}, + {0, 0, 0, 0, 0, 2, 0, 1, 6}, + {8, 11, 0, 0, 0, 0, 1, 0, 7}, + {0, 0, 2, 0, 0, 0, 6, 7, 0}, }; dijkstras t = new dijkstras(); t.dijkstra(graph, 0); - } //main -} //djikstras + } // main +} // djikstras /* OUTPUT : -Vertex Distance +Vertex Distance 0 0 1 4 2 12 diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java index bf3ef8e6eab9..673b795b1563 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java @@ -9,42 +9,32 @@ 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]; + for (int destination = 1; destination <= numberofvertices; destination++) { + DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination]; } } - for ( - int intermediate = 1; - intermediate <= numberofvertices; - intermediate++ - ) { + 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]; + 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]; } } } @@ -55,11 +45,7 @@ public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the dista System.out.println(); for (int source = 1; source <= numberofvertices; source++) { System.out.print(source + "\t"); - for ( - int destination = 1; - destination <= numberofvertices; - destination++ - ) { + for (int destination = 1; destination <= numberofvertices; destination++) { System.out.print(DistanceMatrix[source][destination] + "\t"); } System.out.println(); @@ -70,15 +56,10 @@ public static void main(String... arg) { Scanner scan = new Scanner(System.in); System.out.println("Enter the number of vertices"); int numberOfVertices = scan.nextInt(); - int[][] adjacencyMatrix = new int[numberOfVertices + - 1][numberOfVertices + 1]; + int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1]; System.out.println("Enter the Weighted Matrix for the graph"); for (int source = 1; source <= numberOfVertices; source++) { - for ( - int destination = 1; - destination <= numberOfVertices; - destination++ - ) { + for (int destination = 1; destination <= numberOfVertices; destination++) { adjacencyMatrix[source][destination] = scan.nextInt(); if (source == destination) { adjacencyMatrix[source][destination] = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java index 1430f1a246dd..d4d6a381e89e 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java @@ -21,7 +21,7 @@ public int[] findHamiltonianCycle(int[][] graph) { this.V = graph.length; this.cycle = new int[this.V + 1]; - //Initialize path array with -1 value + // Initialize path array with -1 value for (int i = 0; i < this.cycle.length; i++) { this.cycle[i] = -1; } @@ -41,13 +41,15 @@ public int[] findHamiltonianCycle(int[][] graph) { return cycle; } - /** function to find paths recursively + /** + * 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; } @@ -83,7 +85,8 @@ public boolean isPathFound(int vertex) { return false; } - /** function to check if path is already selected + /** + * function to check if path is already selected * Check if path is already selected * @param vertex Starting vertex */ diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java index 350d7d270b2e..e978ddc1e764 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java @@ -133,7 +133,7 @@ ArrayList<E> topSortOrder() { public class KahnsAlgorithm { public static void main(String[] args) { - //Graph definition and initialization + // Graph definition and initialization AdjacencyList<String> graph = new AdjacencyList<>(); graph.addEdge("a", "b"); graph.addEdge("c", "a"); @@ -144,7 +144,7 @@ public static void main(String[] args) { TopologicalSort<String> topSort = new TopologicalSort<>(graph); - //Printing the order + // Printing the order for (String s : topSort.topSortOrder()) { System.out.print(s + " "); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java index f24791dce596..c24046f510af 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java @@ -7,17 +7,18 @@ /** * Java program that implements Kosaraju Algorithm. * @author Shivanagouda S A (https://github.com/shivu2002a) - * + * */ /** - * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a - directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the transpose - graph (same graph with all the edges reversed) has exactly the same SCCs as the original graph. - - * A graph is said to be strongly connected if every vertex is reachable from every other vertex. - The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected. - Single node is always a SCC. + * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a + directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the + transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original + graph. + + * A graph is said to be strongly connected if every vertex is reachable from every other vertex. + The SCCs of a directed graph form a partition into subgraphs that are themselves strongly + connected. Single node is always a SCC. * Example: @@ -26,19 +27,20 @@ | / | \ / | / | \ / v / v \ / - 1 5 --> 6 + 1 5 --> 6 For the above graph, the SCC list goes as follows: - 0, 1, 2 + 0, 1, 2 3 4, 5, 6 7 - + We can also see that order of the nodes in an SCC doesn't matter since they are in cycle. {@summary} - * Kosaraju Algorithm: - 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges sorted by lowest finish time. + * Kosaraju Algorithm: + 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges + sorted by lowest finish time. 2. Find the transpose graph by reversing the edges. 3. Pop nodes one by one from the stack and again to DFS on the modified graph. @@ -48,7 +50,7 @@ | / | \ / | / | \ / | v | v v - 1 5 <--- 6 + 1 5 <--- 6 We can observe that this graph has the same SCC as that of original graph. @@ -59,33 +61,33 @@ public class Kosaraju { // Sort edges according to lowest finish time Stack<Integer> stack = new Stack<Integer>(); - //Store each component + // Store each component private List<Integer> scc = new ArrayList<>(); - //All the strongly connected components + // All the strongly connected components private List<List<Integer>> sccsList = new ArrayList<>(); /** - * + * * @param v Node count * @param list Adjacency list of graph * @return List of SCCs */ - public List<List<Integer>> kosaraju(int v, List<List<Integer>> list){ - + public List<List<Integer>> kosaraju(int v, List<List<Integer>> list) { + sortEdgesByLowestFinishTime(v, list); - + List<List<Integer>> transposeGraph = createTransposeMatrix(v, list); findStronglyConnectedComponents(v, transposeGraph); - + return sccsList; } - private void sortEdgesByLowestFinishTime(int v, List<List<Integer>> list){ + private void sortEdgesByLowestFinishTime(int v, List<List<Integer>> list) { int[] vis = new int[v]; for (int i = 0; i < v; i++) { - if(vis[i] == 0){ + if (vis[i] == 0) { dfs(i, vis, list); } } @@ -105,15 +107,15 @@ private List<List<Integer>> createTransposeMatrix(int v, List<List<Integer>> lis } /** - * + * * @param v Node count * @param transposeGraph Transpose of the given adjacency list */ - public void findStronglyConnectedComponents(int v, List<List<Integer>> transposeGraph){ + public void findStronglyConnectedComponents(int v, List<List<Integer>> transposeGraph) { int[] vis = new int[v]; while (!stack.isEmpty()) { var node = stack.pop(); - if(vis[node] == 0){ + if (vis[node] == 0) { dfs2(node, vis, transposeGraph); sccsList.add(scc); scc = new ArrayList<>(); @@ -121,24 +123,21 @@ public void findStronglyConnectedComponents(int v, List<List<Integer>> transpose } } - //Dfs to store the nodes in order of lowest finish time - private void dfs(int node, int[] vis, List<List<Integer>> list){ + // Dfs to store the nodes in order of lowest finish time + private void dfs(int node, int[] vis, List<List<Integer>> list) { vis[node] = 1; - for(Integer neighbour : list.get(node)){ - if(vis[neighbour] == 0) - dfs(neighbour, vis, list); + for (Integer neighbour : list.get(node)) { + if (vis[neighbour] == 0) dfs(neighbour, vis, list); } stack.push(node); } - //Dfs to find all the nodes of each strongly connected component - private void dfs2(int node, int[] vis, List<List<Integer>> list){ + // Dfs to find all the nodes of each strongly connected component + private void dfs2(int node, int[] vis, List<List<Integer>> list) { vis[node] = 1; - for(Integer neighbour : list.get(node)){ - if(vis[neighbour] == 0) - dfs2(neighbour, vis, list); + for (Integer neighbour : list.get(node)) { + if (vis[neighbour] == 0) dfs2(neighbour, vis, list); } scc.add(node); } - } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java index 5d326576ffec..3c41a30b86a8 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java @@ -15,8 +15,8 @@ public class Kruskal { - // Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of - // vertices + // Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number + // of vertices private static class Edge { private int from; @@ -30,12 +30,7 @@ public Edge(int from, int to, int weight) { } } - private static void addEdge( - HashSet<Edge>[] graph, - int from, - int to, - int weight - ) { + private static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) { graph[from].add(new Edge(from, to, weight)); } @@ -58,9 +53,7 @@ public static void main(String[] args) { System.out.println("Initial Graph: "); for (int i = 0; i < graph.length; i++) { for (Edge edge : graph[i]) { - System.out.println( - i + " <-- weight " + edge.weight + " --> " + edge.to - ); + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); } } @@ -70,9 +63,7 @@ public static void main(String[] args) { System.out.println("\nMinimal Graph: "); for (int i = 0; i < solGraph.length; i++) { for (Edge edge : solGraph[i]) { - System.out.println( - i + " <-- weight " + edge.weight + " --> " + edge.to - ); + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); } } } @@ -83,9 +74,8 @@ public HashSet<Edge>[] kruskal(HashSet<Edge>[] graph) { // captain of i, stores the set with all the connected nodes to i HashSet<Integer>[] connectedGroups = new HashSet[nodes]; HashSet<Edge>[] minGraph = new HashSet[nodes]; - PriorityQueue<Edge> edges = new PriorityQueue<>( - (Comparator.comparingInt(edge -> edge.weight)) - ); + PriorityQueue<Edge> edges + = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); for (int i = 0; i < nodes; i++) { minGraph[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>(); @@ -98,18 +88,12 @@ public HashSet<Edge>[] kruskal(HashSet<Edge>[] graph) { 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]] - ); + connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); // update captains of the elements merged - connectedGroups[captain[edge.from]].forEach(i -> - captain[i] = captain[edge.from] - ); + connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); // add Edge to minimal graph addEdge(minGraph, edge.from, edge.to, edge.weight); // count how many elements have been merged diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java index 7593a9cfc253..701eec60b7bf 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java @@ -71,9 +71,7 @@ class AdjacencyMatrixGraph { public AdjacencyMatrixGraph(int givenNumberOfVertices) { this.setNumberOfVertices(givenNumberOfVertices); this.setNumberOfEdges(0); - this.setAdjacency( - new int[givenNumberOfVertices][givenNumberOfVertices] - ); + this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); for (int i = 0; i < givenNumberOfVertices; i++) { for (int j = 0; j < givenNumberOfVertices; j++) { this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; @@ -247,11 +245,7 @@ public List<Integer> depthFirstOrder(int startVertex) { * has been visited * @param orderList the list to add vertices to as they are visited */ - private void depthFirstOrder( - int currentVertex, - boolean[] visited, - List<Integer> orderList - ) { + private void depthFirstOrder(int currentVertex, boolean[] visited, List<Integer> orderList) { // If this vertex has already been visited, do nothing and return if (visited[currentVertex]) { return; @@ -264,11 +258,9 @@ private void depthFirstOrder( // 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); } @@ -317,11 +309,9 @@ public List<Integer> breadthFirstOrder(int startVertex) { // 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 893b835e0ed9..e187628928d4 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java @@ -31,9 +31,7 @@ int minKey(int[] key, Boolean[] mstSet) { void printMST(int[] parent, int n, int[][] graph) { System.out.println("Edge Weight"); for (int i = 1; i < V; i++) { - System.out.println( - parent[i] + " - " + i + " " + graph[i][parent[i]] - ); + System.out.println(parent[i] + " - " + i + " " + graph[i][parent[i]]); } } @@ -72,17 +70,12 @@ void primMST(int[][] graph) { // 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] - ) { + if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } @@ -104,11 +97,11 @@ public static void main(String[] args) { 9 */ PrimMST t = new PrimMST(); int[][] graph = new int[][] { - { 0, 2, 0, 6, 0 }, - { 2, 0, 3, 8, 5 }, - { 0, 3, 0, 0, 7 }, - { 6, 8, 0, 0, 9 }, - { 0, 5, 7, 9, 0 }, + {0, 2, 0, 6, 0}, + {2, 0, 3, 8, 5}, + {0, 3, 0, 0, 7}, + {6, 8, 0, 0, 9}, + {0, 5, 7, 9, 0}, }; // Print the solution diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java index 497daeca4428..e63de0ad9ad3 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java @@ -8,16 +8,16 @@ /** * Java program that implements Tarjan's Algorithm. * @author Shivanagouda S A (https://github.com/shivu2002a) - * + * */ /** - * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a - directed graph, which, from here onwards will be referred as SCC. - - * A graph is said to be strongly connected if every vertex is reachable from every other vertex. - The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected. - Single node is always a SCC. + * Tarjan's algorithm is a linear time algorithm to find the strongly connected components of a + directed graph, which, from here onwards will be referred as SCC. + + * A graph is said to be strongly connected if every vertex is reachable from every other vertex. + The SCCs of a directed graph form a partition into subgraphs that are themselves strongly + connected. Single node is always a SCC. * Example: 0 --------> 1 -------> 3 --------> 4 @@ -38,24 +38,25 @@ 1, 2, 0 3 4 - + We can also see that order of the nodes in an SCC doesn't matter since they are in cycle. {@summary} - Tarjan's Algorithm: - * DFS search produces a DFS tree - * Strongly Connected Components form subtrees of the DFS tree. - * If we can find the head of these subtrees, we can get all the nodes in that subtree (including the head) - and that will be one SCC. - * There is no back edge from one SCC to another (here can be cross edges, but they will not be used). + Tarjan's Algorithm: + * DFS search produces a DFS tree + * Strongly Connected Components form subtrees of the DFS tree. + * If we can find the head of these subtrees, we can get all the nodes in that subtree (including + the head) and that will be one SCC. + * There is no back edge from one SCC to another (here can be cross edges, but they will not be + used). - * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s algorithm does - the same in a single DFS, which leads to much lower constant factors in the latter. + * Kosaraju Algorithm aims at doing the same but uses two DFS traversalse whereas Tarjan’s + algorithm does the same in a single DFS, which leads to much lower constant factors in the latter. */ public class TarjansAlgorithm { - //Timer for tracking lowtime and insertion time + // Timer for tracking lowtime and insertion time private int Time; private List<List<Integer>> SCClist = new ArrayList<List<Integer>>(); @@ -66,15 +67,15 @@ public List<List<Integer>> stronglyConnectedComponents(int V, List<List<Integer> // insertionTime:Time when a node is visited 1st time while DFS traversal - // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can - // be reached from a subtree rooted with a particular node. + // lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) + // that can be reached from a subtree rooted with a particular node. int[] lowTime = new int[V]; int[] insertionTime = new int[V]; for (int i = 0; i < V; i++) { insertionTime[i] = -1; lowTime[i] = -1; } - + // To check if element is present in stack boolean[] isInStack = new boolean[V]; @@ -90,36 +91,36 @@ public List<List<Integer>> stronglyConnectedComponents(int V, List<List<Integer> } private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, - boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) { + boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) { // Initialize insertion time and lowTime value of current node insertionTime[u] = Time; lowTime[u] = Time; Time += 1; - //Push current node into stack + // Push current node into stack isInStack[u] = true; st.push(u); // Go through all vertices adjacent to this for (Integer vertex : graph.get(u)) { - //If the adjacent node is unvisited, do DFS + // If the adjacent node is unvisited, do DFS if (insertionTime[vertex] == -1) { stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph); - //update lowTime for the current node comparing lowtime of adj node + // update lowTime for the current node comparing lowtime of adj node lowTime[u] = Math.min(lowTime[u], lowTime[vertex]); } else if (isInStack[vertex]) { - //If adj node is in stack, update low + // If adj node is in stack, update low lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]); } } - //If lowtime and insertion time are same, current node is the head of an SCC - // head node found, get all the nodes in this SCC + // If lowtime and insertion time are same, current node is the head of an SCC + // head node found, get all the nodes in this SCC if (lowTime[u] == insertionTime[u]) { int w = -1; var scc = new ArrayList<Integer>(); - //Stack has all the nodes of the current SCC + // Stack has all the nodes of the current SCC while (w != u) { w = st.pop(); scc.add(w); @@ -128,5 +129,4 @@ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, SCClist.add(scc); } } - } 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 a7f1cbf14b37..d4f8cda9e74d 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -33,7 +33,8 @@ public HashMapCuckooHashing(int tableSize) { } /** - * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive ways to minimize collisions + * The 2 Hash Functions takes a given key and finds an index based on its data, 2 distinctive + * ways to minimize collisions * * @param key the desired key to be converted * @return int an index corresponding to the key @@ -57,10 +58,10 @@ public int hashFunction2(int key) { } /** - * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop to insert new key - * if desired place is empty, return. - * if already occupied, continue while loop over the new key that has just been pushed out. - * if while loop continues more than Thresh, rehash table to new size, then push again. + * inserts the key into the hash map by wrapping it as an Integer object, then uses while loop + * to insert new key if desired place is empty, return. if already occupied, continue while loop + * over the new key that has just been pushed out. if while loop continues more than Thresh, + * rehash table to new size, then push again. * * @param key the desired key to be inserted in the hash map */ @@ -70,26 +71,19 @@ public void insertKey2HashTable(int key) { int hash, loopCounter = 0; if (isFull()) { - System.out.println( - "Hash table is full, lengthening & rehashing table" - ); + System.out.println("Hash table is full, lengthening & rehashing table"); reHashTableIncreasesTableSize(); } if (checkTableContainsKey(key)) { - throw new IllegalArgumentException( - "Key already inside, no duplicates allowed" - ); + throw new IllegalArgumentException("Key already inside, no duplicates allowed"); } while (loopCounter <= thresh) { loopCounter++; hash = hashFunction1(key); - if ( - (buckets[hash] == null) || - Objects.equals(buckets[hash], AVAILABLE) - ) { + if ((buckets[hash] == null) || Objects.equals(buckets[hash], AVAILABLE)) { buckets[hash] = wrappedInt; size++; checkLoadFactor(); @@ -116,16 +110,14 @@ public void insertKey2HashTable(int key) { buckets[hash] = wrappedInt; wrappedInt = temp; } - System.out.println( - "Infinite loop occurred, lengthening & rehashing table" - ); + System.out.println("Infinite loop occurred, lengthening & rehashing table"); reHashTableIncreasesTableSize(); insertKey2HashTable(key); } /** - * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous table to it with its new hash functions. - * then refers current array to new table. + * creates new HashMapCuckooHashing object, then inserts each of the elements in the previous + * table to it with its new hash functions. then refers current array to new table. * */ public void reHashTableIncreasesTableSize() { @@ -164,9 +156,7 @@ public void deleteKeyFromHashTable(int key) { size--; return; } - throw new IllegalArgumentException( - "Key " + key + " already inside, no duplicates allowed" - ); + throw new IllegalArgumentException("Key " + key + " already inside, no duplicates allowed"); } /** @@ -177,9 +167,7 @@ public void displayHashtable() { if ((buckets[i] == null) || Objects.equals(buckets[i], AVAILABLE)) { System.out.println("Bucket " + i + ": Empty"); } else { - System.out.println( - "Bucket " + i + ": " + buckets[i].toString() - ); + System.out.println("Bucket " + i + ": " + buckets[i].toString()); } } System.out.println(); @@ -202,11 +190,9 @@ public int findKeyInTable(int key) { if (Objects.equals(buckets[hash], wrappedInt)) return hash; hash = hashFunction2(key); - if ( - !Objects.equals(buckets[hash], wrappedInt) - ) throw new IllegalArgumentException( - "Key " + key + " not found in table" - ); else { + if (!Objects.equals(buckets[hash], wrappedInt)) + throw new IllegalArgumentException("Key " + key + " not found in table"); + else { return hash; } } @@ -218,16 +204,8 @@ public int findKeyInTable(int key) { * @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)); } /** @@ -237,10 +215,7 @@ public boolean checkTableContainsKey(int key) { public double checkLoadFactor() { double factor = (double) size / tableSize; if (factor > .7) { - System.out.printf( - "Load factor is %.2f , rehashing table\n", - factor - ); + System.out.printf("Load factor is %.2f , rehashing table\n", factor); reHashTableIncreasesTableSize(); } return factor; diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java index f89f9204299b..ad3f617cef5a 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java @@ -15,9 +15,7 @@ public class Intersection { public static List<Integer> intersection(int[] arr1, int[] arr2) { - if ( - arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0 - ) { + if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) { return Collections.emptyList(); } Map<Integer, Integer> cnt = new HashMap<>(16); @@ -34,5 +32,6 @@ public static List<Integer> intersection(int[] arr1, int[] arr2) { return res; } - private Intersection() {} + private Intersection() { + } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java index f6aa18b4c60b..d68e01284ddd 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java @@ -20,31 +20,27 @@ public static void main(String[] args) { choice = In.nextInt(); switch (choice) { - case 1: - { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertHash(key); - break; - } - case 2: - { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteHash(key); - break; - } - case 3: - { - System.out.println("Print table"); - h.displayHashtable(); - break; - } - case 4: - { - In.close(); - return; - } + case 1: { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertHash(key); + break; + } + case 2: { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteHash(key); + break; + } + case 3: { + System.out.println("Print table"); + h.displayHashtable(); + break; + } + case 4: { + In.close(); + return; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java index 90ff839c7ce1..94d370b66976 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java @@ -24,59 +24,41 @@ public static void main(String[] args) { choice = In.nextInt(); switch (choice) { - case 1: - { - System.out.println("Enter the Key: "); - key = In.nextInt(); - h.insertKey2HashTable(key); - break; - } - case 2: - { - System.out.println("Enter the Key delete: "); - key = In.nextInt(); - h.deleteKeyFromHashTable(key); - break; - } - case 3: - { - System.out.println("Print table:\n"); - h.displayHashtable(); - break; - } - case 4: - { - In.close(); - return; - } - case 5: - { - System.out.println( - "Enter the Key to find and print: " - ); - key = In.nextInt(); - System.out.println( - "Key: " + - key + - " is at index: " + - h.findKeyInTable(key) + - "\n" - ); - break; - } - case 6: - { - System.out.printf( - "Load factor is: %.2f\n", - h.checkLoadFactor() - ); - break; - } - case 7: - { - h.reHashTableIncreasesTableSize(); - break; - } + case 1: { + System.out.println("Enter the Key: "); + key = In.nextInt(); + h.insertKey2HashTable(key); + break; + } + case 2: { + System.out.println("Enter the Key delete: "); + key = In.nextInt(); + h.deleteKeyFromHashTable(key); + break; + } + case 3: { + System.out.println("Print table:\n"); + h.displayHashtable(); + break; + } + case 4: { + In.close(); + return; + } + case 5: { + System.out.println("Enter the Key to find and print: "); + key = In.nextInt(); + System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n"); + break; + } + case 6: { + System.out.printf("Load factor is: %.2f\n", h.checkLoadFactor()); + break; + } + case 7: { + h.reHashTableIncreasesTableSize(); + break; + } } } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java index 5231431e9bf7..e3364b0e16fb 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java @@ -1,31 +1,32 @@ package com.thealgorithms.datastructures.hashmap.hashing; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.ArrayList; /* This class finds the majority element(s) in an array of integers. -A majority element is an element that appears more than or equal to n/2 times, where n is the length of the array. +A majority element is an element that appears more than or equal to n/2 times, where n is the length +of the array. */ public class MajorityElement { - /* - This method returns the majority element(s) in the given array of integers. - @param nums: an array of integers - @return a list of majority elements - */ - public static List<Integer> majority(int[] nums){ - HashMap<Integer,Integer> numToCount = new HashMap<>(); + /* + This method returns the majority element(s) in the given array of integers. + @param nums: an array of integers + @return a list of majority elements + */ + public static List<Integer> majority(int[] nums) { + HashMap<Integer, Integer> numToCount = new HashMap<>(); int n = nums.length; for (int i = 0; i < n; i++) { - if (numToCount.containsKey(nums[i])){ - numToCount.put(nums[i],numToCount.get(nums[i])+1); + if (numToCount.containsKey(nums[i])) { + numToCount.put(nums[i], numToCount.get(nums[i]) + 1); } else { - numToCount.put(nums[i],1); + numToCount.put(nums[i], 1); } } List<Integer> majorityElements = new ArrayList<>(); - for (int key: numToCount.keySet()) { - if (numToCount.get(key) >= n/2){ + for (int key : numToCount.keySet()) { + if (numToCount.get(key) >= n / 2) { majorityElements.add(key); } } diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java index cd27b0a795b2..4605883fbbb1 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java @@ -19,5 +19,4 @@ public boolean contains(Key key) { protected int hash(Key key, int size) { return (key.hashCode() & Integer.MAX_VALUE) % size; } - } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index eeeb591c2e02..34afa4206b23 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -47,10 +47,10 @@ public boolean empty() { * $ret = the HeapNode we inserted */ public HeapNode insert(int key) { - HeapNode toInsert = new HeapNode(key); //creates the node + HeapNode toInsert = new HeapNode(key); // creates the node if (this.empty()) { this.min = toInsert; - } else { //tree is not empty + } else { // tree is not empty min.setNext(toInsert); this.updateMin(toInsert); } @@ -69,14 +69,14 @@ public void deleteMin() { if (this.empty()) { return; } - if (this.numOfHeapNodes == 1) { //if there is only one tree + if (this.numOfHeapNodes == 1) { // if there is only one tree this.min = null; this.numOfTrees--; this.numOfHeapNodes--; return; } - //change all children's parent to null// - if (this.min.child != null) { //min has a child + // change all children's parent to null// + if (this.min.child != null) { // min has a child HeapNode child = this.min.child; HeapNode tmpChild = child; child.parent = null; @@ -85,14 +85,14 @@ public void deleteMin() { child.parent = null; } } - //delete the node// + // delete the node// if (this.numOfTrees > 1) { (this.min.prev).next = this.min.next; (this.min.next).prev = this.min.prev; if (this.min.child != null) { (this.min.prev).setNext(this.min.child); } - } else { //this.numOfTrees = 1 + } else { // this.numOfTrees = 1 this.min = this.min.child; } this.numOfHeapNodes--; @@ -136,17 +136,15 @@ public int size() { } /** - * Return a counters array, where the value of the i-th index is the number of trees with rank i in the heap. - * returns an empty array for an empty heap + * Return a counters array, where the value of the i-th index is the number of trees with rank i + * in the heap. returns an empty array for an empty heap */ public int[] countersRep() { if (this.empty()) { - return new int[0]; ///return an empty array + return new int[0]; /// return an empty array } - int[] rankArray = new int[(int) Math.floor( - Math.log(this.size()) / Math.log(GOLDEN_RATIO) - ) + - 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) { @@ -163,8 +161,8 @@ public int[] countersRep() { * @post (numOfnodes = = $prev numOfnodes - 1) */ public void delete(HeapNode x) { - this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1) - this.deleteMin(); //delete it + this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1) + this.deleteMin(); // delete it } /** @@ -176,13 +174,13 @@ public void delete(HeapNode x) { private void decreaseKey(HeapNode x, int delta) { int newKey = x.getKey() - delta; x.key = newKey; - if (x.isRoot()) { //no parent to x + if (x.isRoot()) { // no parent to x this.updateMin(x); return; } if (x.getKey() >= x.parent.getKey()) { return; - } //we don't need to cut + } // we don't need to cut HeapNode prevParent = x.parent; this.cut(x); this.cascadingCuts(prevParent); @@ -197,17 +195,18 @@ public int potential() { } /** - * This static function returns the total number of link operations made during the run-time of the program. - * A link operation is the operation which gets as input two trees of the same rank, and generates a tree of - * rank bigger by one. + * This static function returns the total number of link operations made during the run-time of + * the program. A link operation is the operation which gets as input two trees of the same + * rank, and generates a tree of rank bigger by one. */ public static int totalLinks() { return totalLinks; } /** - * This static function returns the total number of cut operations made during the run-time of the program. - * A cut operation is the operation which disconnects a subtree from its parent (during decreaseKey/delete methods). + * This static function returns the total number of cut operations made during the run-time of + * the program. A cut operation is the operation which disconnects a subtree from its parent + * (during decreaseKey/delete methods). */ public static int totalCuts() { return totalCuts; @@ -231,7 +230,7 @@ private void updateMin(HeapNode posMin) { * @post (numOfnodes == $prev numOfnodes) */ private void cascadingCuts(HeapNode curr) { - if (!curr.isMarked()) { //stop the recursion + if (!curr.isMarked()) { // stop the recursion curr.mark(); if (!curr.isRoot()) this.markedHeapNoodesCounter++; } else { @@ -255,10 +254,10 @@ private void cut(HeapNode curr) { this.markedHeapNoodesCounter--; curr.marked = false; } - if (curr.parent.child == curr) { //we should change the parent's child - if (curr.next == curr) { //curr do not have brothers + if (curr.parent.child == curr) { // we should change the parent's child + if (curr.next == curr) { // curr do not have brothers curr.parent.child = null; - } else { //curr have brothers + } else { // curr have brothers curr.parent.child = curr.next; } } @@ -285,10 +284,8 @@ private void successiveLink(HeapNode curr) { * */ 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) { @@ -398,7 +395,7 @@ private boolean isMarked() { private void mark() { if (this.isRoot()) { return; - } //check if the node is a root + } // check if the node is a root this.marked = true; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java index 2ceb86a727e9..23c26cfd0aab 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java @@ -45,16 +45,10 @@ private void downHeapify(int pi) { int lci = 2 * pi + 1; int rci = 2 * pi + 2; int mini = pi; - if ( - lci < this.size() && - isLarger(this.data.get(lci), this.data.get(mini)) > 0 - ) { + if (lci < this.size() && isLarger(this.data.get(lci), this.data.get(mini)) > 0) { mini = lci; } - if ( - rci < this.size() && - isLarger(this.data.get(rci), this.data.get(mini)) > 0 - ) { + if (rci < this.size() && isLarger(this.data.get(rci), this.data.get(mini)) > 0) { mini = rci; } if (mini != pi) { @@ -67,7 +61,7 @@ public T get() { return this.data.get(0); } - //t has higher property then return +ve + // t has higher property then return +ve private int isLarger(T t, T o) { return t.compareTo(o); } @@ -83,7 +77,7 @@ private void swap(int i, int j) { public void updatePriority(T item) { int index = map.get(item); - //because we enter lesser value then old vale + // because we enter lesser value then old vale upHeapify(index); } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index bf095706a5a5..be5e42c900e2 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -122,10 +122,8 @@ public boolean equals(Object o) { 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; } @@ -134,10 +132,7 @@ public boolean equals(Object o) { public int hashCode() { int result = 0; result = 31 * result + (int) key; - result = - 31 * - result + - (additionalInfo != null ? additionalInfo.hashCode() : 0); + result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); return result; } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java index 66861ac1d111..f64781f19857 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java @@ -2,117 +2,113 @@ import java.util.ArrayList; -/* +/* * This is a leftist heap that follows the same operations as a * binary min heap, but may be unbalanced at times and follows a * leftist property, in which the left side is more heavy on the * right based on the null-path length (npl) values. - * + * * Source: https://iq.opengenus.org/leftist-heap/ - * + * */ public class LeftistHeap { - private class Node { - private int element, npl; - private Node left, right; - - // Node constructor setting the data element and left/right pointers to null - private Node(int element) { - this.element = element; - left = right = null; - npl = 0; - } - } - - private Node root; - - // Constructor - public LeftistHeap() { - root = null; - } - - // Checks if heap is empty - public boolean isEmpty() { - return root == null; - } - - // Resets structure to initial state - public void clear() { - // We will put head is null - root = null; - } - - // Merge function that merges the contents of another leftist heap with the - // current one - public void merge(LeftistHeap h1) { - // If the present function is rhs then we ignore the merge - root = merge(root, h1.root); - h1.root = null; - } - - // Function merge with two Nodes a and b - public Node merge(Node a, Node b) { - if (a == null) - return b; - - if (b == null) - return a; - - // Violates leftist property, so must do a swap - if (a.element > b.element) { - Node temp = a; - a = b; - b = temp; - } - - // Now we call the function merge to merge a and b - a.right = merge(a.right, b); - - // Violates leftist property so must swap here - if (a.left == null) { - a.left = a.right; - a.right = null; - } else { - if (a.left.npl < a.right.npl) { - Node temp = a.left; - a.left = a.right; - a.right = temp; - } - a.npl = a.right.npl + 1; - } - return a; - } - - // Function insert. Uses the merge function to add the data - public void insert(int a) { - root = merge(new Node(a), root); - } - - // Returns and removes the minimum element in the heap - public int extract_min() { - // If is empty return -1 - if (isEmpty()) - return -1; - - int min = root.element; - root = merge(root.left, root.right); - return min; - } - - // Function returning a list of an in order traversal of the data structure - public ArrayList<Integer> in_order() { - ArrayList<Integer> lst = new ArrayList<>(); - in_order_aux(root, lst); - return new ArrayList<>(lst); - } - - // Auxiliary function for in_order - private void in_order_aux(Node n, ArrayList<Integer> lst) { - if (n == null) - return; - in_order_aux(n.left, lst); - lst.add(n.element); - in_order_aux(n.right, lst); - } + private class Node { + private int element, npl; + private Node left, right; + + // Node constructor setting the data element and left/right pointers to null + private Node(int element) { + this.element = element; + left = right = null; + npl = 0; + } + } + + private Node root; + + // Constructor + public LeftistHeap() { + root = null; + } + + // Checks if heap is empty + public boolean isEmpty() { + return root == null; + } + + // Resets structure to initial state + public void clear() { + // We will put head is null + root = null; + } + + // Merge function that merges the contents of another leftist heap with the + // current one + public void merge(LeftistHeap h1) { + // If the present function is rhs then we ignore the merge + root = merge(root, h1.root); + h1.root = null; + } + + // Function merge with two Nodes a and b + public Node merge(Node a, Node b) { + if (a == null) return b; + + if (b == null) return a; + + // Violates leftist property, so must do a swap + if (a.element > b.element) { + Node temp = a; + a = b; + b = temp; + } + + // Now we call the function merge to merge a and b + a.right = merge(a.right, b); + + // Violates leftist property so must swap here + if (a.left == null) { + a.left = a.right; + a.right = null; + } else { + if (a.left.npl < a.right.npl) { + Node temp = a.left; + a.left = a.right; + a.right = temp; + } + a.npl = a.right.npl + 1; + } + return a; + } + + // Function insert. Uses the merge function to add the data + public void insert(int a) { + root = merge(new Node(a), root); + } + + // Returns and removes the minimum element in the heap + public int extract_min() { + // If is empty return -1 + if (isEmpty()) return -1; + + int min = root.element; + root = merge(root.left, root.right); + return min; + } + + // Function returning a list of an in order traversal of the data structure + public ArrayList<Integer> in_order() { + ArrayList<Integer> lst = new ArrayList<>(); + in_order_aux(root, lst); + return new ArrayList<>(lst); + } + + // Auxiliary function for in_order + private void in_order_aux(Node n, ArrayList<Integer> lst) { + if (n == null) return; + in_order_aux(n.left, lst); + lst.add(n.element); + in_order_aux(n.right, lst); + } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 64731fd2f5ba..591b4439c397 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -70,30 +70,20 @@ private void toggleUp(int elementIndex) { // 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()))); } } @@ -112,12 +102,10 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { if (maxHeap.isEmpty()) try { - throw new EmptyHeapException( - "Attempt to delete an element from an empty heap" - ); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) { throw new IndexOutOfBoundsException("Index out of heap range"); } @@ -125,22 +113,13 @@ public void deleteElement(int elementIndex) { maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); maxHeap.remove(maxHeap.size()); // Shall the new element be moved up... - if ( - getElementKey(elementIndex) > - getElementKey((int) Math.floor(elementIndex / 2.0)) - ) { + 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); } } @@ -150,9 +129,7 @@ public HeapElement getElement() throws EmptyHeapException { try { return extractMax(); } catch (Exception e) { - throw new EmptyHeapException( - "Heap is empty. Error retrieving element" - ); + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index a28a8e5f1cf9..5c2cb5ccd69d 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -64,30 +64,20 @@ private void toggleUp(int elementIndex) { // 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()))); } } @@ -106,12 +96,10 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { if (minHeap.isEmpty()) try { - throw new EmptyHeapException( - "Attempt to delete an element from an empty heap" - ); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) { throw new IndexOutOfBoundsException("Index out of heap range"); } @@ -119,22 +107,13 @@ public void deleteElement(int elementIndex) { minHeap.set(elementIndex - 1, getElement(minHeap.size())); minHeap.remove(minHeap.size()); // Shall the new element be moved up... - if ( - getElementKey(elementIndex) < - getElementKey((int) Math.floor(elementIndex / 2.0)) - ) { + 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); } } @@ -144,9 +123,7 @@ public HeapElement getElement() throws EmptyHeapException { try { return extractMin(); } catch (Exception e) { - throw new EmptyHeapException( - "Heap is empty. Error retrieving element" - ); + throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java index 23ac5d3aaabf..2ad4ed5320c9 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java @@ -82,10 +82,7 @@ private void sink() { while (2 * k <= this.size || 2 * k + 1 <= this.size) { int minIndex; if (this.heap[2 * k] >= this.heap[k]) { - if ( - 2 * k + 1 <= this.size && - this.heap[2 * k + 1] >= this.heap[k] - ) { + if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { break; } else if (2 * k + 1 > this.size) { break; @@ -94,14 +91,8 @@ private void sink() { if (2 * k + 1 > this.size) { minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; } else { - if ( - this.heap[k] > this.heap[2 * k] || - this.heap[k] > this.heap[2 * k + 1] - ) { - minIndex = - this.heap[2 * k] < this.heap[2 * k + 1] - ? 2 * k - : 2 * k + 1; + if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { + minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; } else { minIndex = k; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java index f5edc6c09811..5d9f0b3a1d28 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java @@ -38,9 +38,7 @@ public int getSize() { public void append(E value) { if (value == null) { // we do not want to add null elements to the list. - throw new NullPointerException( - "Cannot add null element to the list" - ); + throw new NullPointerException("Cannot add null element to the list"); } // head.next points to the last element; if (tail == null) { @@ -70,9 +68,7 @@ public String toString() { public E remove(int pos) { if (pos > size || pos < 0) { // catching errors - throw new IndexOutOfBoundsException( - "position cannot be greater than size or negative" - ); + throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); } // we need to keep track of the element before the element we want to remove we can see why // bellow. diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java index 6ed317d6d4ef..cefc47c27169 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java @@ -120,8 +120,7 @@ public void remove(T element) { while (current_index != -1) { T current_element = cursorSpace[current_index].element; if (current_element.equals(element)) { - cursorSpace[prev_index].next = - cursorSpace[current_index].next; + cursorSpace[prev_index].next = cursorSpace[current_index].next; free(current_index); break; } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java index 2d048d9967b5..74aa4b8b1ae0 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java @@ -217,7 +217,8 @@ public void insertHead(int x, DoublyLinkedList doublyLinkedList) { 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 { @@ -234,15 +235,9 @@ public void insertTail(int x, DoublyLinkedList doublyLinkedList) { * @param x Element to be inserted * @param index Index(from start) at which the element x to be inserted */ - public void insertElementByIndex( - int x, - int index, - DoublyLinkedList doublyLinkedList - ) { + public void insertElementByIndex(int x, int index, DoublyLinkedList doublyLinkedList) { if (index > size) { - throw new IndexOutOfBoundsException( - "Index: " + index + ", Size: " + size - ); + throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } if (index == 0) { insertHead(x, doublyLinkedList); @@ -277,7 +272,8 @@ public Link deleteHead() { if (head == null) { tail = null; } else { - head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so + // will be removed } --size; return temp; @@ -314,9 +310,7 @@ public void delete(int x) { if (current != tail) { current = current.next; } else { // If we reach the tail and the element is still not found - throw new RuntimeException( - "The element to be deleted does not exist!" - ); + throw new RuntimeException("The element to be deleted does not exist!"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java index f9a80d984cc7..80b36b8e4ab1 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java @@ -36,11 +36,7 @@ public static void main(String[] args) { * @param listB the second list to merge * @param listC the result list after merging */ - public static void merge( - List<Integer> listA, - List<Integer> listB, - List<Integer> listC - ) { + public static void merge(List<Integer> listA, List<Integer> listB, List<Integer> listC) { int pa = 0; /* the index of listA */ int pb = 0; diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java index 4ea0127f4ae0..2bee945c9db6 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java @@ -12,9 +12,7 @@ public static void main(String[] args) { } assert listA.toString().equals("2->4->6->8->10"); assert listB.toString().equals("1->3->5->7->9"); - assert merge(listA, listB) - .toString() - .equals("1->2->3->4->5->6->7->8->9->10"); + assert merge(listA, listB).toString().equals("1->2->3->4->5->6->7->8->9->10"); } /** @@ -24,10 +22,7 @@ assert merge(listA, listB) * @param listB the second sored list * @return merged sorted list */ - public static SinglyLinkedList merge( - SinglyLinkedList listA, - SinglyLinkedList listB - ) { + public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) { Node headA = listA.getHead(); Node headB = listB.getHead(); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java index 840b935ef84a..9d26645c2f9c 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/Merge_K_SortedLinkedlist.java @@ -18,9 +18,7 @@ public class Merge_K_SortedLinkedlist { */ Node mergeKList(Node[] a, int N) { // Min Heap - PriorityQueue<Node> min = new PriorityQueue<>( - Comparator.comparingInt(x -> x.data) - ); + PriorityQueue<Node> min = new PriorityQueue<>(Comparator.comparingInt(x -> x.data)); // adding head of all linkedList in min heap min.addAll(Arrays.asList(a).subList(0, N)); diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java index e173da2fb4f7..7318b8027f8c 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java @@ -1,25 +1,30 @@ -/** Author : Suraj Kumar +/** + * Author : Suraj Kumar * Github : https://github.com/skmodi649 */ -/** PROBLEM DESCRIPTION : +/** + * PROBLEM DESCRIPTION : * There is a single linked list and we are supposed to find a random node in the given linked list */ -/** ALGORITHM : +/** + * ALGORITHM : * Step 1 : START * Step 2 : Create an arraylist of type integer * Step 3 : Declare an integer type variable for size and linked list type for head - * Step 4 : We will use two methods, one for traversing through the linked list using while loop and also increase the size by 1 + * Step 4 : We will use two methods, one for traversing through the linked list using while loop and + * also increase the size by 1 * * (a) RandomNode(head) * (b) run a while loop till null; * (c) add the value to arraylist; * (d) increase the size; * - * Step 5 : Now use another method for getting random values using Math.random() and return the value present in arraylist for the calculated index - * Step 6 : Now in main() method we will simply insert nodes in the linked list and then call the appropriate method and then print the random node generated - * Step 7 : STOP + * Step 5 : Now use another method for getting random values using Math.random() and return the + * value present in arraylist for the calculated index Step 6 : Now in main() method we will simply + * insert nodes in the linked list and then call the appropriate method and then print the random + * node generated Step 7 : STOP */ package com.thealgorithms.datastructures.lists; @@ -86,6 +91,7 @@ public static void main(String[] args) { * Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ -/** Time Complexity : O(n) +/** + * Time Complexity : O(n) * Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java index bd3dd51ba39a..35f8c9a95b56 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java @@ -23,10 +23,7 @@ public static void main(String[] args) { * {@code false}. */ private boolean searchRecursion(Node node, int key) { - return ( - node != null && - (node.value == key || searchRecursion(node.next, key)) - ); + return (node != null && (node.value == key || searchRecursion(node.next, key))); } @Override diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java index df460938390a..8d15059367f1 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java @@ -125,19 +125,20 @@ public void swapNodes(int valueFirst, int valueSecond) { public Node reverseList(Node node) { Node prev = null; Node curr = node; - + while (curr != null && curr.next != null) { - Node next=curr.next; + Node next = curr.next; curr.next = prev; prev = curr; curr = next; } - //when curr.next==null, the current element is left without pointing it to its prev,so - if(curr != null){ + // when curr.next==null, the current element is left without pointing it to its prev,so + if (curr != null) { curr.next = prev; - prev=curr; + prev = curr; } - //prev will be pointing to the last element in the Linkedlist, it will be the new head of the reversed linkedlist + // prev will be pointing to the last element in the Linkedlist, it will be the new head of + // the reversed linkedlist return prev; } @@ -244,9 +245,7 @@ public void deleteDuplicates() { // skip all duplicates if (newHead.next != null && newHead.value == newHead.next.value) { // move till the end of duplicates sublist - while ( - newHead.next != null && newHead.value == newHead.next.value - ) { + while (newHead.next != null && newHead.value == newHead.next.value) { newHead = newHead.next; } // skip all duplicates @@ -412,15 +411,10 @@ public static void main(String[] arg) { assert list.toString().equals("10->7->5->3->1"); System.out.println(list); /* Test search function */ - assert list.search(10) && - list.search(5) && - list.search(1) && - !list.search(100); + assert list.search(10) && list.search(5) && list.search(1) && !list.search(100); /* Test get function */ - assert list.getNth(0) == 10 && - list.getNth(2) == 5 && - list.getNth(4) == 1; + assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1; /* Test delete function */ list.deleteHead(); @@ -443,10 +437,7 @@ public static void main(String[] arg) { } SinglyLinkedList instance = new SinglyLinkedList(); - Node head = new Node( - 0, - new Node(2, new Node(3, new Node(3, new Node(4)))) - ); + Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4))))); instance.setHead(head); instance.deleteDuplicates(); instance.print(); @@ -469,7 +460,8 @@ class Node { */ Node next; - Node() {} + Node() { + } /** * Constructor diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java index 34efde769ed9..6a079ac879a3 100644 --- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java +++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java @@ -189,25 +189,23 @@ public String toString() { } Collections.reverse(layers); - String result = layers - .stream() - .map(layer -> { - StringBuilder acc = new StringBuilder(); - for (boolean b : layer) { - if (b) { - acc.append("[ ]"); - } else { - acc.append("---"); - } - acc.append(" "); - } - return acc.toString(); - }) - .collect(Collectors.joining("\n")); - String positions = IntStream - .range(0, sizeWithHeader - 1) - .mapToObj(i -> String.format("%3d", i)) - .collect(Collectors.joining(" ")); + String result = layers.stream() + .map(layer -> { + StringBuilder acc = new StringBuilder(); + for (boolean b : layer) { + if (b) { + acc.append("[ ]"); + } else { + acc.append("---"); + } + acc.append(" "); + } + return acc.toString(); + }) + .collect(Collectors.joining("\n")); + 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); } @@ -299,17 +297,14 @@ public BernoulliHeightStrategy() { public BernoulliHeightStrategy(double probability) { if (probability <= 0 || probability >= 1) { throw new IllegalArgumentException( - "Probability should be from 0 to 1. But was: " + probability - ); + "Probability should be from 0 to 1. But was: " + probability); } this.probability = probability; } @Override public int height(int expectedSize) { - long height = Math.round( - Math.log10(expectedSize) / Math.log10(1 / probability) - ); + long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability)); if (height > Integer.MAX_VALUE) { throw new IllegalArgumentException(); } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java index e5bedd9beae3..9530c5a69d8c 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java @@ -1,7 +1,7 @@ package com.thealgorithms.datastructures.queues; -//This program implements the concept of CircularQueue in Java -//Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer) +// This program implements the concept of CircularQueue in Java +// Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer) public class CircularQueue { int[] arr; @@ -23,7 +23,8 @@ public boolean isEmpty() { public boolean isFull() { if (topOfQueue + 1 == beginningOfQueue) { return true; - } else return topOfQueue == size - 1 && beginningOfQueue == 0; + } else + return topOfQueue == size - 1 && beginningOfQueue == 0; } public void enQueue(int value) { diff --git a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java index 79fddb0ef518..7fa769c615ce 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java @@ -124,11 +124,9 @@ public T peekRear() { public T peek(int pos) { if (pos > size) - throw new IndexOutOfBoundsException( - "Position %s out of range!".formatted(pos)); + throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); Node<T> node = front; - while (pos-- > 0) - node = node.next; + while (pos-- > 0) node = node.next; return node.data; } @@ -140,7 +138,6 @@ public T peek(int pos) { @Override public Iterator<T> iterator() { return new Iterator<>() { - Node<T> node = front; @Override @@ -168,16 +165,14 @@ public int size() { * Clear all nodes in queue */ public void clear() { - while (size > 0) - dequeue(); + while (size > 0) dequeue(); } @Override public String toString() { StringJoiner join = new StringJoiner(", "); // separator of ', ' Node<T> travel = front; - while ((travel = travel.next) != null) - join.add(String.valueOf(travel.data)); + while ((travel = travel.next) != null) join.add(String.valueOf(travel.data)); return '[' + join.toString() + ']'; } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java index 21432a53ce5c..dec25d2ff694 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -1,8 +1,5 @@ package com.thealgorithms.datastructures.queues; - - - /** * This class implements a PriorityQueue. * @@ -126,7 +123,8 @@ public int remove() { if (isEmpty()) { throw new RuntimeException("Queue is Empty"); } else { - int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is the greatest + int max = queueArray[1]; // By defintion of our max-heap, value at queueArray[1] pos is + // the greatest // Swap max and last element int temp = queueArray[1]; @@ -175,4 +173,3 @@ public int getSize() { return nItems; } } - diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java index 2e2b572c1054..d80502d88e22 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/BalancedBrackets.java @@ -28,16 +28,13 @@ class BalancedBrackets { */ public static boolean isPaired(char leftBracket, char rightBracket) { char[][] pairedBrackets = { - { '(', ')' }, - { '[', ']' }, - { '{', '}' }, - { '<', '>' }, + {'(', ')'}, + {'[', ']'}, + {'{', '}'}, + {'<', '>'}, }; for (char[] pairedBracket : pairedBrackets) { - if ( - pairedBracket[0] == leftBracket && - pairedBracket[1] == rightBracket - ) { + if (pairedBracket[0] == leftBracket && pairedBracket[1] == rightBracket) { return true; } } @@ -58,24 +55,21 @@ public static boolean isBalanced(String brackets) { Stack<Character> bracketsStack = new Stack<>(); for (char bracket : brackets.toCharArray()) { switch (bracket) { - case '(': - case '[': - case '{': - bracketsStack.push(bracket); - break; - case ')': - case ']': - case '}': - if ( - bracketsStack.isEmpty() || - !isPaired(bracketsStack.pop(), bracket) - ) { - return false; - } - break; - default: - /* other character is invalid */ + case '(': + case '[': + case '{': + bracketsStack.push(bracket); + break; + case ')': + case ']': + case '}': + if (bracketsStack.isEmpty() || !isPaired(bracketsStack.pop(), bracket)) { return false; + } + break; + default: + /* other character is invalid */ + return false; } } return bracketsStack.isEmpty(); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java index 7a76c62e8964..df7279bb217e 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java @@ -1,8 +1,12 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ -/** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */ +/** + * Program description - Given an integer array. The task is to find the maximum of the minimum of + * the array + */ package com.thealgorithms.datastructures.stacks; import java.util.*; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java index 28302793977a..a0d364136bcd 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java @@ -24,12 +24,7 @@ public static void main(String[] args) { 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 - ) - ); + String.format("Invalid input -> number:%d,radius:%d", number, radix)); } char[] tables = { '0', diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java index d47f5b193077..fb976360c9f5 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java @@ -1,7 +1,8 @@ package com.thealgorithms.datastructures.stacks; // 1. You are given a string exp representing an expression. -// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each other. +// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each +// other. // 3. But, some of the pair of brackets maybe extra/needless. // 4. You are required to print true if you detect extra brackets and false otherwise. // e.g.' diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java index 9df7330d808b..b009223330f0 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java @@ -10,8 +10,7 @@ public static void main(String[] args) throws Exception { assert "34+5*6-".equals(infix2PostFix("(3+4)*5-6")); } - public static String infix2PostFix(String infixExpression) - throws Exception { + public static String infix2PostFix(String infixExpression) throws Exception { if (!BalancedBrackets.isBalanced(infixExpression)) { throw new Exception("invalid expression"); } @@ -28,10 +27,7 @@ public static String infix2PostFix(String infixExpression) } stack.pop(); } else { - while ( - !stack.isEmpty() && - precedence(element) <= precedence(stack.peek()) - ) { + while (!stack.isEmpty() && precedence(element) <= precedence(stack.peek())) { output.append(stack.pop()); } stack.push(element); @@ -45,16 +41,16 @@ public static String infix2PostFix(String infixExpression) private static int precedence(char operator) { switch (operator) { - case '+': - case '-': - return 0; - case '*': - case '/': - return 1; - case '^': - return 2; - default: - return -1; + case '+': + case '-': + return 0; + case '*': + case '/': + return 1; + case '^': + return 2; + default: + return -1; } } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java index 9cc4f0f7035c..f076d5d6a97e 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java @@ -19,7 +19,7 @@ public static String largestRectanglehistogram(int[] heights) { maxArea = Math.max(maxArea, tmp[1] * (i - tmp[0])); start = tmp[0]; } - st.push(new int[] { start, heights[i] }); + st.push(new int[] {start, heights[i]}); } while (!st.isEmpty()) { int[] tmp = st.pop(); @@ -29,8 +29,7 @@ public static String largestRectanglehistogram(int[] heights) { } public static void main(String[] args) { - assert largestRectanglehistogram(new int[] { 2, 1, 5, 6, 2, 3 }) - .equals("10"); - assert largestRectanglehistogram(new int[] { 2, 4 }).equals("4"); + assert largestRectanglehistogram(new int[] {2, 1, 5, 6, 2, 3}).equals("10"); + assert largestRectanglehistogram(new int[] {2, 4}).equals("4"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java index 53a502798caa..88228000e904 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java @@ -97,8 +97,8 @@ public static int[] calculateMaxOfMin(int[] arr, int n) { } public static void main(String[] args) { - int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 }; - int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 }; + int[] arr = new int[] {10, 20, 30, 50, 10, 70, 30}; + int[] target = new int[] {70, 30, 20, 10, 10, 10, 10}; int[] res = calculateMaxOfMin(arr, arr.length); assert Arrays.equals(target, res); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java index 2497158a20bb..294e436c24a2 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java @@ -37,7 +37,8 @@ Next Grater element between (6 to n) is -1 popped elements. d. Finally, push the next in the stack. - 3. If elements are left in stack after completing while loop then their Next Grater element is -1. + 3. If elements are left in stack after completing while loop then their Next Grater element is + -1. */ public class NextGraterElement { @@ -61,7 +62,7 @@ public static int[] findNextGreaterElements(int[] array) { } public static void main(String[] args) { - int[] input = { 2, 7, 3, 5, 4, 6, 8 }; + int[] input = {2, 7, 3, 5, 4, 6, 8}; int[] result = findNextGreaterElements(input); System.out.println(Arrays.toString(result)); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java index 6073d4819361..b25e5346d574 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java @@ -4,10 +4,10 @@ import java.util.Stack; /* - Given an array "input" you need to print the first smaller element for each element to the left side of an array. - For a given element x of an array, the Next Smaller element of that element is the - first smaller element to the left side of it. If no such element is present print -1. - + Given an array "input" you need to print the first smaller element for each element to the left + side of an array. For a given element x of an array, the Next Smaller element of that element is + the first smaller element to the left side of it. If no such element is present print -1. + Example input = { 2, 7, 3, 5, 4, 6, 8 }; At i = 0 @@ -24,17 +24,17 @@ Next smaller element between (0 , 3) is 3 Next smaller element between (0 , 4) is 4 At i = 6 Next smaller element between (0 , 5) is 6 - + result : [-1, 2, 2, 3, 3, 4, 6] - + 1) Create a new empty stack st - + 2) Iterate over array "input" , where "i" goes from 0 to input.length -1. - a) We are looking for value just smaller than `input[i]`. So keep popping from "stack" + a) We are looking for value just smaller than `input[i]`. So keep popping from "stack" till elements in "stack.peek() >= input[i]" or stack becomes empty. - b) If the stack is non-empty, then the top element is our previous element. Else the previous element does not exist. - c) push input[i] in stack. - 3) If elements are left then their answer is -1 + b) If the stack is non-empty, then the top element is our previous element. Else the + previous element does not exist. c) push input[i] in stack. 3) If elements are left then their + answer is -1 */ public class NextSmallerElement { @@ -61,7 +61,7 @@ public static int[] findNextSmallerElements(int[] array) { } public static void main(String[] args) { - int[] input = { 2, 7, 3, 5, 4, 6, 8 }; + int[] input = {2, 7, 3, 5, 4, 6, 8}; int[] result = findNextSmallerElements(input); System.out.println(Arrays.toString(result)); } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java index b4ab7860ddd0..ffdfc962224d 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java @@ -50,7 +50,8 @@ public static void main(String[] args) { /** * Constructors for the NodeStack. */ - public NodeStack() {} + public NodeStack() { + } private NodeStack(Item item) { this.data = item; diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java index 868aa778a626..0d67a7939513 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java @@ -20,12 +20,12 @@ public class PostfixToInfix { public static boolean isOperator(char token) { switch (token) { - case '+': - case '-': - case '/': - case '*': - case '^': - return true; + case '+': + case '-': + case '/': + case '*': + case '^': + return true; } return false; @@ -42,7 +42,8 @@ public static boolean isValidPostfixExpression(String postfix) { int operandCount = 0; int operatorCount = 0; - /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 */ + /* Traverse the postfix string to check if --> Number of operands = Number of operators + 1 + */ for (int i = 0; i < postfix.length(); i++) { char token = postfix.charAt(i); @@ -59,8 +60,8 @@ public static boolean isValidPostfixExpression(String postfix) { /* Operand count is set to 2 because:- * - * 1) the previous set of operands & operators combined have become a single valid expression, - * which could be considered/assigned as a single operand. + * 1) the previous set of operands & operators combined have become a single valid + * expression, which could be considered/assigned as a single operand. * * 2) the operand in the current iteration. */ @@ -123,7 +124,6 @@ public static void main(String[] args) { assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))"); assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)"); assert getPostfixToInfix("ABCDE^*/-").equals("(A-(B/(C*(D^E))))"); - assert getPostfixToInfix("AB+CD^/E*FGH+-^") - .equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); + assert getPostfixToInfix("AB+CD^/E*FGH+-^").equals("((((A+B)/(C^D))*E)^(F-(G+H)))"); } } diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java index 1dd9fe11d891..f269d08b5678 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java @@ -12,9 +12,7 @@ public class ReverseStack { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println( - "Enter the number of elements you wish to insert in the stack" - ); + System.out.println("Enter the number of elements you wish to insert in the stack"); int n = sc.nextInt(); int i; Stack<Integer> stack = new Stack<Integer>(); @@ -36,28 +34,29 @@ private static void reverseStack(Stack<Integer> stack) { return; } - //Store the topmost element + // Store the topmost element int element = stack.peek(); - //Remove the topmost element + // Remove the topmost element stack.pop(); - //Reverse the stack for the leftover elements + // Reverse the stack for the leftover elements reverseStack(stack); - //Insert the topmost element to the bottom of the stack + // Insert the topmost element to the bottom of the stack insertAtBottom(stack, element); } private static void insertAtBottom(Stack<Integer> stack, int element) { if (stack.isEmpty()) { - //When stack is empty, insert the element so it will be present at the bottom of the stack + // When stack is empty, insert the element so it will be present at the bottom of the + // stack stack.push(element); return; } int ele = stack.peek(); - /*Keep popping elements till stack becomes empty. Push the elements once the topmost element has - moved to the bottom of the stack. + /*Keep popping elements till stack becomes empty. Push the elements once the topmost element + has moved to the bottom of the stack. */ stack.pop(); insertAtBottom(stack, element); diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java index 8f8931d1e972..0463018fde82 100644 --- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java +++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java @@ -23,9 +23,7 @@ public static void main(String[] args) { assert stack.pop() == 5; assert stack.pop() == 4; - System.out.println( - "Top element of stack currently is: " + stack.peek() - ); + System.out.println("Top element of stack currently is: " + stack.peek()); } } @@ -120,9 +118,7 @@ public String toString() { builder.append(cur.data).append("->"); cur = cur.next; } - return builder - .replace(builder.length() - 2, builder.length(), "") - .toString(); + return builder.replace(builder.length() - 2, builder.length(), "").toString(); } /** diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java index 85c44707ea24..1032daa240f8 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java @@ -3,23 +3,23 @@ /* * Avl is algo that balance itself while adding new alues to tree * by rotating branches of binary tree and make itself Binary seaarch tree -* there are four cases which has to tackle -* rotating - left right ,left left,right right,right left +* there are four cases which has to tackle +* rotating - left right ,left left,right right,right left Test Case: AVLTree tree=new AVLTree(); - tree.insert(20); - tree.insert(25); - tree.insert(30); - tree.insert(10); - tree.insert(5); - tree.insert(15); - tree.insert(27); - tree.insert(19); - tree.insert(16); - - tree.display(); + tree.insert(20); + tree.insert(25); + tree.insert(30); + tree.insert(10); + tree.insert(5); + tree.insert(15); + tree.insert(27); + tree.insert(19); + tree.insert(16); + + tree.display(); @@ -59,16 +59,16 @@ private Node insert(Node node, int item) { } node.height = Math.max(height(node.left), height(node.right)) + 1; int bf = bf(node); - //LL case + // LL case if (bf > 1 && item < node.left.data) return rightRotate(node); - //RR case + // RR case if (bf < -1 && item > node.right.data) return leftRotate(node); - //RL case + // RL case if (bf < -1 && item < node.right.data) { node.right = rightRotate(node.right); return leftRotate(node); } - //LR case + // LR case if (bf > 1 && item > node.left.data) { node.left = leftRotate(node.left); return rightRotate(node); @@ -84,11 +84,15 @@ public void display() { private void display(Node node) { String str = ""; - if (node.left != null) str += node.left.data + "=>"; else str += - "END=>"; + if (node.left != null) + str += node.left.data + "=>"; + else + str += "END=>"; str += node.data + ""; - if (node.right != null) str += "<=" + node.right.data; else str += - "<=END"; + if (node.right != null) + str += "<=" + node.right.data; + else + str += "<=END"; System.out.println(str); if (node.left != null) display(node.left); if (node.right != null) display(node.right); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java index f7fecdb3fe86..b70fcb280ac3 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java @@ -39,17 +39,20 @@ public static void main(String[] args) { integerTree.add(5); integerTree.add(10); integerTree.add(9); - assert !integerTree.find(4) : "4 is not yet present in BST"; - assert integerTree.find(10) : "10 should be present in BST"; + assert !integerTree.find(4) + : "4 is not yet present in BST"; + assert integerTree.find(10) + : "10 should be present in BST"; integerTree.remove(9); - assert !integerTree.find(9) : "9 was just deleted from BST"; + assert !integerTree.find(9) + : "9 was just deleted from BST"; integerTree.remove(1); - assert !integerTree.find( - 1 - ) : "Since 1 was not present so find deleting would do no change"; + assert !integerTree.find(1) + : "Since 1 was not present so find deleting would do no change"; integerTree.add(20); integerTree.add(70); - assert integerTree.find(70) : "70 was inserted but not found"; + assert integerTree.find(70) + : "70 was inserted but not found"; /* Will print in following order 5 10 20 70 @@ -63,17 +66,20 @@ public static void main(String[] args) { stringTree.add("banana"); stringTree.add("pineapple"); stringTree.add("date"); - assert !stringTree.find("girl") : "girl is not yet present in BST"; - assert stringTree.find("pineapple") : "10 should be present in BST"; + assert !stringTree.find("girl") + : "girl is not yet present in BST"; + assert stringTree.find("pineapple") + : "10 should be present in BST"; stringTree.remove("date"); - assert !stringTree.find("date") : "date was just deleted from BST"; + assert !stringTree.find("date") + : "date was just deleted from BST"; stringTree.remove("boy"); - assert !stringTree.find( - "boy" - ) : "Since boy was not present so deleting would do no change"; + assert !stringTree.find("boy") + : "Since boy was not present so deleting would do no change"; stringTree.add("india"); stringTree.add("hills"); - assert stringTree.find("hills") : "hills was inserted but not found"; + assert stringTree.find("hills") + : "hills was inserted but not found"; /* Will print in following order banana hills india pineapple diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java index fc0db9b8cd92..d86130dff470 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java @@ -143,7 +143,8 @@ public boolean remove(int value) { if (temp.right == null && temp.left == null) { if (temp == root) { root = null; - } // This if/else assigns the new node to be either the left or right child of the parent + } // This if/else assigns the new node to be either the left or right child of the + // parent else if (temp.parent.data < temp.data) { temp.parent.right = null; } else { @@ -179,7 +180,8 @@ else if (temp.left != null && temp.right != null) { else { successor.parent = temp.parent; - // This if/else assigns the new node to be either the left or right child of the parent + // This if/else assigns the new node to be either the left or right child of the + // parent if (temp.parent.data < temp.data) { temp.parent.right = successor; } else { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java index 13246944737c..19fbb6a8357f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java @@ -24,8 +24,6 @@ private static boolean isBSTUtil(BinaryTree.Node node, int min, int max) { } return ( - isBSTUtil(node.left, min, node.data - 1) && - isBSTUtil(node.right, node.data + 1, max) - ); + isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); } } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java index e953a37d1c82..c4d6ff94ae61 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java @@ -80,11 +80,7 @@ public boolean isBalancedRecursive(BinaryTree binaryTree) { * @param depth The current depth of the node * @param isBalanced The array of length 1 keeping track of our balance */ - private int isBalancedRecursive( - BTNode node, - int depth, - boolean[] isBalanced - ) { + private int isBalancedRecursive(BTNode node, int depth, boolean[] isBalanced) { // If the node is null, we should not explore it and the height is 0 // If the tree is already not balanced, might as well stop because we // can't make it balanced now! @@ -94,11 +90,7 @@ private int isBalancedRecursive( // Visit the left and right children, incrementing their depths by 1 int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced); - int rightHeight = isBalancedRecursive( - node.right, - depth + 1, - isBalanced - ); + int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced); // If the height of either of the left or right subtrees differ by more // than 1, we cannot be balanced @@ -174,10 +166,7 @@ public boolean isBalancedIterative(BinaryTree binaryTree) { // The height of the subtree containing this node is the // max of the left and right subtree heighs plus 1 - subtreeHeights.put( - node, - Math.max(rightHeight, leftHeight) + 1 - ); + subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1); // We've now visited this node, so we pop it from the stack nodeStack.pop(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java index 0df93cefb9e3..bb592bd4131a 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java @@ -48,10 +48,12 @@ private static boolean isSymmetric(Node leftSubtreeRoot, Node rightSubtreRoot) { 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 99b1fb4efe97..5c08a0021450 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java @@ -1,7 +1,6 @@ package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; - import java.util.HashMap; import java.util.Map; @@ -37,13 +36,8 @@ public static Node createTreeOptimized(final Integer[] preorder, final Integer[] 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; } @@ -55,32 +49,15 @@ private static Node createTree( } 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.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount); + root.right + = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount); return root; } - private static Node createTreeOptimized( - final Integer[] preorder, - final Map<Integer, Integer> inorderMap, - final int preStart, - final int inStart, - final int size - ) { + private static Node createTreeOptimized(final Integer[] preorder, + final Map<Integer, Integer> inorderMap, final int preStart, final int inStart, + final int size) { if (size == 0) { return null; } @@ -89,22 +66,10 @@ private static Node createTreeOptimized( 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/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java index c22bdab08f2b..d4bbf0c9aad6 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java @@ -35,9 +35,7 @@ private Node create_treeG(Node node, int childindx, Scanner scn) { if (node == null) { System.out.println("Enter root's data"); } else { - System.out.println( - "Enter data of parent of index " + node.data + " " + childindx - ); + System.out.println("Enter data of parent of index " + node.data + " " + childindx); } // input node = new Node(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index cd28f93c9d56..f0f8fac8e528 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -34,15 +34,11 @@ public class KDTree { * @param points Array of initial points */ KDTree(Point[] points) { - if (points.length == 0) throw new IllegalArgumentException( - "Points array cannot be empty" - ); + if (points.length == 0) throw new IllegalArgumentException("Points array cannot be empty"); this.k = points[0].getDimension(); - for (Point point : points) if ( - point.getDimension() != k - ) throw new IllegalArgumentException( - "Points must have the same dimension" - ); + for (Point point : points) + if (point.getDimension() != k) + throw new IllegalArgumentException("Points must have the same dimension"); this.root = build(points, 0); } @@ -53,19 +49,13 @@ 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" - ); + 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"); this.root = build(points, 0); } @@ -125,11 +115,7 @@ public static int comparableDistance(Point p1, Point p2) { * * @return The distance between the two points */ - public static int comparableDistanceExceptAxis( - Point p1, - Point p2, - int axis - ) { + public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { if (i == axis) continue; @@ -177,9 +163,10 @@ public int getAxis() { * @return The nearest child Node */ public Node getNearChild(Point point) { - if ( - point.getCoordinate(axis) < this.point.getCoordinate(axis) - ) return left; else return right; + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + return left; + else + return right; } /** @@ -190,9 +177,10 @@ public Node getNearChild(Point point) { * @return The farthest child Node */ public Node getFarChild(Point point) { - if ( - point.getCoordinate(axis) < this.point.getCoordinate(axis) - ) return right; else return left; + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + return right; + else + return left; } /** @@ -221,18 +209,11 @@ private Node build(Point[] points, int depth) { if (points.length == 0) return null; int axis = depth % k; if (points.length == 1) return new Node(points[0], axis); - Arrays.sort( - points, - Comparator.comparingInt(o -> o.getCoordinate(axis)) - ); + Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis))); int median = points.length >> 1; Node node = new Node(points[median], axis); node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1); - node.right = - build( - Arrays.copyOfRange(points, median + 1, points.length), - depth + 1 - ); + node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1); return node; } @@ -243,9 +224,8 @@ private Node build(Point[] points, int depth) { * */ 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); } @@ -261,9 +241,10 @@ public void insert(Point point) { private Node insert(Node root, Point point, int depth) { int axis = depth % k; if (root == null) return new Node(point, axis); - if (point.getCoordinate(axis) < root.getAxisCoordinate()) root.left = - insert(root.left, point, depth + 1); else root.right = - insert(root.right, point, depth + 1); + if (point.getCoordinate(axis) < root.getAxisCoordinate()) + root.left = insert(root.left, point, depth + 1); + else + root.right = insert(root.right, point, depth + 1); return root; } @@ -276,9 +257,8 @@ private Node insert(Node root, Point point, int depth) { * @return The Node corresponding to the specified point */ public Optional<Node> search(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException( - "Point has wrong dimension" - ); + if (point.getDimension() != k) + throw new IllegalArgumentException("Point has wrong dimension"); return search(root, point); } @@ -323,9 +303,8 @@ public Node findMin(Node root, int axis) { } else { Node left = findMin(root.left, axis); Node right = findMin(root.right, axis); - Node[] candidates = { left, root, right }; - return Arrays - .stream(candidates) + Node[] candidates = {left, root, right}; + return Arrays.stream(candidates) .filter(Objects::nonNull) .min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) .orElse(null); @@ -359,9 +338,8 @@ public Node findMax(Node root, int axis) { } else { Node left = findMax(root.left, axis); Node right = findMax(root.right, axis); - Node[] candidates = { left, root, right }; - return Arrays - .stream(candidates) + Node[] candidates = {left, root, right}; + return Arrays.stream(candidates) .filter(Objects::nonNull) .max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))) .orElse(null); @@ -374,8 +352,8 @@ public Node findMax(Node root, int axis) { * @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); } @@ -398,12 +376,13 @@ private Node delete(Node root, Node node) { Node min = findMin(root.left, root.getAxis()); root.point = min.point; root.left = delete(root.left, min); - } else return null; + } else + return null; } - if ( - root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis()) - ) root.left = delete(root.left, node); else root.right = - delete(root.right, node); + if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) + root.left = delete(root.left, node); + else + root.right = delete(root.right, node); return root; } @@ -427,17 +406,12 @@ private Node findNearest(Node root, Point point, Node nearest) { 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() - ); - if (distance < Point.comparableDistance(nearest.point, point)) nearest = - root; + 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 1fe83e0c0de5..d7bdb0af5486 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LCA.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LCA.java @@ -8,17 +8,17 @@ public class LCA { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { - //The adjacency list representation of a tree: + // The adjacency list representation of a tree: ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); - //v is the number of vertices and e is the number of edges + // v is the number of vertices and e is the number of edges int v = scanner.nextInt(), e = v - 1; for (int i = 0; i < v; i++) { adj.add(new ArrayList<Integer>()); } - //Storing the given tree as an adjacency list + // Storing the given tree as an adjacency list int to, from; for (int i = 0; i < e; i++) { to = scanner.nextInt(); @@ -28,19 +28,19 @@ public static void main(String[] args) { adj.get(from).add(to); } - //parent[v1] gives parent of a vertex v1 + // parent[v1] gives parent of a vertex v1 int[] parent = new int[v]; - //depth[v1] gives depth of vertex v1 with respect to the root + // depth[v1] gives depth of vertex v1 with respect to the root int[] depth = new int[v]; - //Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex + // Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex dfs(adj, 0, -1, parent, depth); - //Inputting the two vertices whose LCA is to be calculated + // Inputting the two vertices whose LCA is to be calculated int v1 = scanner.nextInt(), v2 = scanner.nextInt(); - //Outputting the LCA + // Outputting the LCA System.out.println(getLCA(v1, v2, depth, parent)); } @@ -54,12 +54,7 @@ public static void main(String[] args) { * @param depth An array to store depth of all vertices */ private static void dfs( - ArrayList<ArrayList<Integer>> adj, - int s, - int p, - int[] parent, - int[] depth - ) { + ArrayList<ArrayList<Integer>> 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/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java index a98ec9ddd86b..b5a9db9f5e11 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java @@ -24,7 +24,8 @@ public Node(int start, int end, int value) { this.right = null; } - /** Update the value of this node with the given value diff. + /** + * Update the value of this node with the given value diff. * * @param diff The value to add to every index of this node range. */ @@ -33,7 +34,8 @@ public void applyUpdate(int diff) { this.value += (this.end - this.start) * diff; } - /** Shift the lazy value of this node to its children. + /** + * Shift the lazy value of this node to its children. */ public void shift() { if (lazy == 0) return; @@ -44,7 +46,8 @@ public void shift() { this.lazy = 0; } - /** Create a new node that is the sum of this node and the given node. + /** + * Create a new node that is the sum of this node and the given node. * * @param left The left Node of merging * @param right The right Node of merging @@ -53,11 +56,7 @@ public void shift() { static Node merge(Node left, Node right) { if (left == null) return right; if (right == null) return left; - Node result = new Node( - left.start, - right.end, - left.value + right.value - ); + Node result = new Node(left.start, right.end, left.value + right.value); result.left = left; result.right = right; return result; @@ -78,7 +77,8 @@ public Node getRight() { private final Node root; - /** Create a new LazySegmentTree with the given array. + /** + * Create a new LazySegmentTree with the given array. * * @param array The array to create the LazySegmentTree from. */ @@ -86,7 +86,8 @@ public LazySegmentTree(int[] array) { this.root = buildTree(array, 0, array.length); } - /** Build a new LazySegmentTree from the given array in O(n) time. + /** + * Build a new LazySegmentTree from the given array in O(n) time. * * @param array The array to build the LazySegmentTree from. * @param start The start index of the current node. @@ -101,7 +102,8 @@ private Node buildTree(int[] array, int start, int end) { return Node.merge(left, right); } - /** Update the value of given range with the given value diff in O(log n) time. + /** + * Update the value of given range with the given value diff in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. @@ -121,7 +123,8 @@ private void updateRange(int left, int right, int diff, Node curr) { curr.value = merge.value; } - /** Get Node of given range in O(log n) time. + /** + * Get Node of given range in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. @@ -131,10 +134,7 @@ private Node getRange(int left, int right, Node curr) { if (left <= curr.start && curr.end <= right) return curr; if (left >= curr.end || right <= curr.start) return null; curr.shift(); - return Node.merge( - getRange(left, right, curr.left), - getRange(left, right, curr.right) - ); + return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right)); } public int getRange(int left, int right) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java index 7103a9ead2ca..fbb51701471f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java @@ -28,14 +28,8 @@ public void printTree(Node node) { 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); } @@ -43,14 +37,8 @@ public void printTreepre(Node node) { 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/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java index 6a2258b5e065..aede2a23b544 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java @@ -5,9 +5,8 @@ /** * Given 2 binary trees. - * This code checks whether they are the same (structurally identical and have the same values) or not. - * <p> - * Example: + * This code checks whether they are the same (structurally identical and have the same values) or + * not. <p> Example: * 1. Binary trees: * 1 1 * / \ / \ diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java index e24db38da08f..d7674f4a4086 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java @@ -26,21 +26,14 @@ public int constructTree(int[] arr, int start, int end, int index) { } 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]; } /* A function which will update the value at a index i. This will be called by the update function internally*/ - private void updateTree( - int start, - int end, - int index, - int diff, - int seg_index - ) { + private void updateTree(int start, int end, int index, int diff, int seg_index) { if (index < start || index > end) { return; } @@ -64,14 +57,9 @@ public void update(int index, int value) { updateTree(0, n - 1, index, diff, 0); } - /* A function to get the sum of the elements from index l to index r. This will be called internally*/ - private int getSumTree( - int start, - int end, - int q_start, - int q_end, - int seg_index - ) { + /* A function to get the sum of the elements from index l to index r. This will be called + * internally*/ + private int getSumTree(int start, int end, int q_start, int q_end, int seg_index) { if (q_start <= start && q_end >= end) { return this.seg_t[seg_index]; } @@ -81,10 +69,8 @@ private int getSumTree( } 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/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java index 369eaf57cc2a..d9f5a6f0ec43 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java @@ -5,7 +5,8 @@ */ /* PROBLEM DESCRIPTION : - There is a Binary Search Tree given, and we are supposed to find a random node in the given binary tree. + There is a Binary Search Tree given, and we are supposed to find a random node in the given binary + tree. */ /* ALGORITHM : @@ -14,9 +15,9 @@ Step 3: Now use a method inOrder() that takes a node as input parameter to traverse through the binary tree in inorder fashion as also store the values in a ArrayList simultaneously. Step 4: Now define a method getRandom() that takes a node as input parameter, in this first call - the inOrder() method to store the values in the arraylist, then find the size of the binary tree and now just generate a random number between 0 to n-1. - Step 5: After generating the number display the value of the ArrayList at the generated index - Step 6: STOP + the inOrder() method to store the values in the arraylist, then find the size of the + binary tree and now just generate a random number between 0 to n-1. Step 5: After generating the + number display the value of the ArrayList at the generated index Step 6: STOP */ import java.util.ArrayList; @@ -65,7 +66,7 @@ public void getRandom(Node val) { int n = list.size(); int min = 0; int max = n - 1; - //Generate random int value from 0 to n-1 + // Generate random int value from 0 to n-1 int b = (int) (Math.random() * (max - min + 1) + min); // displaying the value at the generated index int random = list.get(b); @@ -74,9 +75,10 @@ public void getRandom(Node val) { } /* Explanation of the Approach : (a) Form the required binary tree - (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list' - (c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number - from the arraylist using get() method and finally display the result. + (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the + given arraylist 'list' (c) Using the getRandom() method generate a random number between 0 to n-1, + then get the value at the generated random number from the arraylist using get() method and + finally display the result. */ /* OUTPUT : First output : diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java index 5829f920cac8..79c66cb90f01 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java @@ -83,57 +83,56 @@ public static boolean isValid(String word) { public static void main(String[] args) { TrieImp obj = new TrieImp(); String word; - @SuppressWarnings("resource") - Scanner scan = new Scanner(System.in); + @SuppressWarnings("resource") Scanner scan = new Scanner(System.in); sop("string should contain only a-z character for all operation"); while (true) { sop("1. Insert\n2. Search\n3. Delete\n4. Quit"); try { int t = scan.nextInt(); switch (t) { - case 1: - word = scan.next(); - if (isValid(word)) { - obj.insert(word); - } else { - sop("Invalid string: allowed only a-z"); - } - break; - case 2: - word = scan.next(); - boolean resS = false; - if (isValid(word)) { - resS = obj.search(word); - } else { - sop("Invalid string: allowed only a-z"); - } - if (resS) { - sop("word found"); - } else { - sop("word not found"); - } - break; - case 3: - word = scan.next(); - boolean resD = false; - if (isValid(word)) { - resD = obj.delete(word); - } else { - sop("Invalid string: allowed only a-z"); - } - if (resD) { - sop("word got deleted successfully"); - } else { - sop("word not found"); - } - break; - case 4: - sop("Quit successfully"); - System.exit(1); - break; - default: - sop("Input int from 1-4"); - break; + case 1: + word = scan.next(); + if (isValid(word)) { + obj.insert(word); + } else { + sop("Invalid string: allowed only a-z"); + } + break; + case 2: + word = scan.next(); + boolean resS = false; + if (isValid(word)) { + resS = obj.search(word); + } else { + sop("Invalid string: allowed only a-z"); + } + if (resS) { + sop("word found"); + } else { + sop("word not found"); + } + break; + case 3: + word = scan.next(); + boolean resD = false; + if (isValid(word)) { + resD = obj.delete(word); + } else { + sop("Invalid string: allowed only a-z"); + } + if (resD) { + sop("word got deleted successfully"); + } else { + sop("word not found"); + } + break; + case 4: + sop("Quit successfully"); + System.exit(1); + break; + default: + sop("Input int from 1-4"); + break; } } catch (Exception e) { String badInput = scan.next(); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java index 15fd348ea1eb..a42b4370de68 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java @@ -23,7 +23,7 @@ public class VerticalOrderTraversal { /*Function that receives a root Node and prints the tree - in Vertical Order.*/ + in Vertical Order.*/ public static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { if (root == null) { return new ArrayList<>(); @@ -32,19 +32,19 @@ public static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { /*Queue to store the Nodes.*/ Queue<BinaryTree.Node> queue = new LinkedList<>(); - /*Queue to store the index of particular vertical - column of a tree , with root at 0, Nodes on left - with negative index and Nodes on right with positive - index. */ + /*Queue to store the index of particular vertical + column of a tree , with root at 0, Nodes on left + with negative index and Nodes on right with positive + index. */ Queue<Integer> index = new LinkedList<>(); - /*Map of Integer and ArrayList to store all the - elements in a particular index in a single arrayList - that will have a key equal to the index itself. */ + /*Map of Integer and ArrayList to store all the + elements in a particular index in a single arrayList + that will have a key equal to the index itself. */ Map<Integer, ArrayList<Integer>> map = new HashMap<>(); /* min and max stores leftmost and right most index to - later print the tree in vertical fashion.*/ + later print the tree in vertical fashion.*/ int max = 0, min = 0; queue.offer(root); index.offer(0); @@ -52,38 +52,38 @@ public static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { while (!queue.isEmpty()) { if (queue.peek().left != null) { /*Adding the left Node if it is not null - and its index by subtracting 1 from it's - parent's index*/ + and its index by subtracting 1 from it's + parent's index*/ queue.offer(queue.peek().left); index.offer(index.peek() - 1); } if (queue.peek().right != null) { /*Adding the right Node if it is not null - and its index by adding 1 from it's - parent's index*/ + and its index by adding 1 from it's + parent's index*/ queue.offer(queue.peek().right); index.offer(index.peek() + 1); } /*If the map does not contains the index a new - ArrayList is created with the index as key.*/ + ArrayList is created with the index as key.*/ if (!map.containsKey(index.peek())) { ArrayList<Integer> a = new ArrayList<>(); map.put(index.peek(), a); } /*For a index, corresponding Node data is added - to the respective ArrayList present at that - index. */ + to the respective ArrayList present at that + index. */ map.get(index.peek()).add(queue.peek().data); max = Math.max(max, index.peek()); min = Math.min(min, index.peek()); /*The Node and its index are removed - from their respective queues.*/ + from their respective queues.*/ index.poll(); queue.poll(); } /*Finally map data is printed here which has keys - from min to max. Each ArrayList represents a - vertical column that is added in ans ArrayList.*/ + from min to max. Each ArrayList represents a + vertical column that is added in ans ArrayList.*/ ArrayList<Integer> ans = new ArrayList<>(); for (int i = min; i <= max; i++) { ans.addAll(map.get(i)); diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java index 7aafcdf83b3d..d5bfd68e97e4 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java @@ -17,7 +17,8 @@ * This solution implements the breadth-first search (BFS) algorithm using a queue. * 1. The algorithm starts with a root node. This node is added to a queue. * 2. While the queue is not empty: - * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes at the current level. + * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes + * at the current level. * - we traverse all the level nodes in 2 ways: from left to right OR from right to left * (this state is stored on `prevLevelFromLeftToRight` variable) * - if the current node has children we add them to a queue diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java index 773d30743ab2..f0626c1dae47 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java @@ -27,7 +27,7 @@ public static NRKTree BuildTree() { } public static int nearestRightKey(NRKTree root, int x0) { - //Check whether tree is empty + // Check whether tree is empty if (root == null) { return 0; } else { diff --git a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java index 873e46367841..388fb3fd9056 100644 --- a/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java +++ b/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java @@ -25,7 +25,6 @@ public int getBurstTime() { return burstTime; } - public int getWaitingTime() { return waitingTime; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java index 7a60741d5d96..bfd30f9f3f24 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java @@ -54,10 +54,7 @@ public LargeTreeNode(E data, LargeTreeNode<E> parentNode) { * @see TreeNode#TreeNode(Object, Node) */ public LargeTreeNode( - E data, - LargeTreeNode<E> parentNode, - Collection<LargeTreeNode<E>> childNodes - ) { + E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) { super(data, parentNode); this.childNodes = childNodes; } diff --git a/src/main/java/com/thealgorithms/devutils/nodes/Node.java b/src/main/java/com/thealgorithms/devutils/nodes/Node.java index e6be58f5f616..a10817830962 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/Node.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/Node.java @@ -20,7 +20,8 @@ public abstract class Node<E> { /** * Empty constructor. */ - public Node() {} + public Node() { + } /** * Initializes the Nodes' data. diff --git a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java index 7230db73fb87..61f430bda3f3 100644 --- a/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java +++ b/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java @@ -57,12 +57,8 @@ public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode) { * @param rightNode Value to which the nodes' right child reference will be * set. */ - public SimpleTreeNode( - E data, - SimpleTreeNode<E> parentNode, - SimpleTreeNode<E> leftNode, - SimpleTreeNode<E> rightNode - ) { + public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode, + SimpleTreeNode<E> rightNode) { super(data, parentNode); this.leftNode = leftNode; this.rightNode = rightNode; diff --git a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java index 365eb48cb245..da45d5b90cae 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java +++ b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java @@ -5,7 +5,7 @@ /* * Binary Exponentiation is a method to calculate a to the power of b. * It is used to calculate a^n in O(log n) time. - * + * * Reference: * https://iq.opengenus.org/binary-exponentiation/ */ diff --git a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java index ad0c6867e5a2..aa453539ac94 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java +++ b/src/main/java/com/thealgorithms/divideandconquer/ClosestPair.java @@ -135,11 +135,7 @@ public int yPartition(final Location[] a, final int first, final int last) { * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> */ - public void xQuickSort( - final Location[] a, - final int first, - final int last - ) { + public void xQuickSort(final Location[] a, final int first, final int last) { if (first < last) { int q = xPartition(a, first, last); // pivot xQuickSort(a, first, q - 1); // Left @@ -154,11 +150,7 @@ public void xQuickSort( * @param first (IN Parameter) first point <br> * @param last (IN Parameter) last point <br> */ - public void yQuickSort( - final Location[] a, - final int first, - final int last - ) { + public void yQuickSort(final Location[] a, final int first, final int last) { if (first < last) { int q = yPartition(a, first, last); // pivot yQuickSort(a, first, q - 1); // Left @@ -186,13 +178,7 @@ public double closestPair(final Location[] a, final int indexNum) { // divide-left array System.arraycopy(divideArray, 0, leftArray, 0, divideX); // divide-right array - System.arraycopy( - divideArray, - divideX, - rightArray, - 0, - indexNum - divideX - ); + System.arraycopy(divideArray, divideX, rightArray, 0, indexNum - divideX); double minLeftArea; // Minimum length of left array double minRightArea; // Minimum length of right array diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java index f7ba384c6fbe..610b1b78a36a 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java +++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java @@ -92,16 +92,10 @@ public ArrayList<Point> produceSubSkyLines(ArrayList<Point> list) { * @param right the skyline of the right part of points * @return left the final skyline */ - public ArrayList<Point> produceFinalSkyLine( - ArrayList<Point> left, - ArrayList<Point> right - ) { + public ArrayList<Point> produceFinalSkyLine(ArrayList<Point> left, ArrayList<Point> right) { // dominated points of ArrayList left are removed for (int i = 0; i < left.size() - 1; i++) { - if ( - left.get(i).x == left.get(i + 1).x && - left.get(i).y > left.get(i + 1).y - ) { + if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { left.remove(i); i--; } @@ -172,10 +166,7 @@ public int getY() { */ public boolean dominates(Point p1) { // checks if p1 is dominated - return ( - (this.x < p1.x && this.y <= p1.y) || - (this.x <= p1.x && this.y < p1.y) - ); + return ((this.x < p1.x && this.y <= p1.y) || (this.x <= p1.x && this.y < p1.y)); } } diff --git a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java index 7fe4fe186062..4c25066a3553 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java +++ b/src/main/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplication.java @@ -4,12 +4,12 @@ /* * Uses the divide and conquer approach to multiply two matrices. - * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication algorithm. - * Space Complexity: O(n^2) - * - * This Matrix multiplication can be performed only on square matrices + * Time Complexity: O(n^2.8074) better than the O(n^3) of the standard matrix multiplication + * algorithm. Space Complexity: O(n^2) + * + * This Matrix multiplication can be performed only on square matrices * where n is a power of 2. Order of both of the matrices are n × n. - * + * * Reference: * https://www.tutorialspoint.com/design_and_analysis_of_algorithms/design_and_analysis_of_algorithms_strassens_matrix_multiplication.htm#:~:text=Strassen's%20Matrix%20multiplication%20can%20be,matrices%20are%20n%20%C3%97%20n. * https://www.geeksforgeeks.org/strassens-matrix-multiplication/ @@ -139,5 +139,4 @@ public void join(int[][] C, int[][] P, int iB, int jB) { } } } - } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java index 0f2a14282240..7deb81448b55 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java @@ -11,16 +11,16 @@ here target is 10 int n=10; - startAlgo(); - System.out.println(bpR(0,n)); - System.out.println(endAlgo()+"ms"); - int[] strg=new int [n+1]; - startAlgo(); - System.out.println(bpRS(0,n,strg)); - System.out.println(endAlgo()+"ms"); - startAlgo(); - System.out.println(bpIS(0,n,strg)); - System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpR(0,n)); + System.out.println(endAlgo()+"ms"); + int[] strg=new int [n+1]; + startAlgo(); + System.out.println(bpRS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpIS(0,n,strg)); + System.out.println(endAlgo()+"ms"); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java index 514f9e4ccac8..d09d2d9b1b1f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java @@ -13,11 +13,7 @@ public class BoundaryFill { * @param x_co_ordinate The x co-ordinate of which color is to be obtained * @param y_co_ordinate The y co-ordinate of which color is to be obtained */ - public static int getPixel( - int[][] image, - int x_co_ordinate, - int y_co_ordinate - ) { + public static int getPixel(int[][] image, int x_co_ordinate, int y_co_ordinate) { return image[x_co_ordinate][y_co_ordinate]; } @@ -29,11 +25,7 @@ public static int getPixel( * @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 - ) { + int[][] image, int x_co_ordinate, int y_co_ordinate, int new_color) { image[x_co_ordinate][y_co_ordinate] = new_color; } @@ -47,75 +39,19 @@ public static void putPixel( * @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 - ) { + 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 - ); - boundaryFill( - image, - x_co_ordinate, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate, - y_co_ordinate - 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate + 1, - y_co_ordinate - 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate - 1, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate + 1, - y_co_ordinate + 1, - new_color, - boundary_color - ); - boundaryFill( - image, - x_co_ordinate - 1, - y_co_ordinate - 1, - new_color, - boundary_color - ); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate, new_color, boundary_color); + boundaryFill(image, x_co_ordinate, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate, y_co_ordinate - 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate - 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate + 1, y_co_ordinate + 1, new_color, boundary_color); + boundaryFill(image, x_co_ordinate - 1, y_co_ordinate - 1, new_color, boundary_color); } } @@ -136,30 +72,30 @@ public static void printImageArray(int[][] image) { // Driver Program public static void main(String[] args) { - //Input 2D image matrix + // Input 2D image matrix int[][] image = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 0, 0, 3, 0, 0 }, - { 0, 3, 0, 0, 3, 3, 3 }, - { 0, 3, 3, 3, 0, 0, 3 }, - { 0, 0, 0, 3, 0, 0, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 0, 0, 3, 0, 0}, + {0, 3, 0, 0, 3, 3, 3}, + {0, 3, 3, 3, 0, 0, 3}, + {0, 0, 0, 3, 0, 0, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; boundaryFill(image, 2, 2, 5, 3); /* Output ==> - * 0 0 0 0 0 0 0 - 0 3 3 3 3 0 0 - 0 3 5 5 3 0 0 - 0 3 5 5 3 3 3 - 0 3 3 3 5 5 3 - 0 0 0 3 5 5 3 + * 0 0 0 0 0 0 0 + 0 3 3 3 3 0 0 + 0 3 5 5 3 0 0 + 0 3 5 5 3 3 3 + 0 3 3 3 5 5 3 + 0 0 0 3 5 5 3 0 0 0 3 3 3 3 - * */ + * */ - //print 2D image matrix + // print 2D image matrix printImageArray(image); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java index c6f555609a24..5b17a10105f4 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java @@ -22,16 +22,15 @@ static int knapSack(int W, int[] wt, int[] val, int n) { // (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)); } } // Driver code public static void main(String[] args) { - int[] val = new int[] { 60, 100, 120 }; - int[] wt = new int[] { 10, 20, 30 }; + int[] val = new int[] {60, 100, 120}; + int[] wt = new int[] {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java index 9744f3c03c7e..5db7d39f1d99 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java @@ -47,9 +47,7 @@ static long findNthCatalan(int n) { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println( - "Enter the number n to find nth Catalan number (n <= 50)" - ); + System.out.println("Enter the number n to find nth Catalan number (n <= 50)"); int n = sc.nextInt(); System.out.println(n + "th Catalan number is " + findNthCatalan(n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java index 376a6532c102..58ba1351109c 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java @@ -9,7 +9,7 @@ public class ClimbingStairs { public static int numberOfWays(int n) { - if(n == 1 || n == 0){ + if (n == 1 || n == 0) { return n; } int prev = 1; @@ -17,14 +17,13 @@ public static int numberOfWays(int n) { int next; - for(int i = 2; i <= n; i++){ - next = curr+prev; + for (int i = 2; i <= n; i++) { + next = curr + prev; prev = curr; curr = next; } return curr; - } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java index d7bd476f5071..7d74e2a8a5e5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java @@ -8,20 +8,12 @@ public class CoinChange { // Driver Program public static void main(String[] args) { int amount = 12; - int[] coins = { 2, 4, 5 }; + 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)); } /** @@ -67,10 +59,7 @@ public static int minimumCoins(int[] coins, int amount) { for (int coin : coins) { if (coin <= i) { int sub_res = minimumCoins[i - coin]; - if ( - sub_res != Integer.MAX_VALUE && - sub_res + 1 < minimumCoins[i] - ) { + if (sub_res != Integer.MAX_VALUE && sub_res + 1 < minimumCoins[i]) { minimumCoins[i] = sub_res + 1; } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java index 75189b61d53f..e18725405394 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java @@ -1,8 +1,10 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ /** - * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence. + * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal + * to number of times n appears in the sequence. */ /** diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java index 5744e4f84217..84f9cf6a83d8 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java @@ -15,11 +15,12 @@ And it can be done using Dynamic Programming(DP). // dice where every dice has 'm' faces class DP { - /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m faces. */ + /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m + * faces. */ public static long findWays(int m, int n, int x) { - /* Create a table to store the results of subproblems. - One extra row and column are used for simplicity - (Number of dice is directly used as row index and sum is directly used as column index). + /* Create a table to store the results of subproblems. + One extra row and column are used for simplicity + (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ long[][] table = new long[n + 1][x + 1]; @@ -28,7 +29,7 @@ public static long findWays(int m, int n, int x) { table[1][j] = 1; } - /* Fill rest of the entries in table using recursive relation + /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for (int i = 2; i <= n; i++) { for (int j = 1; j <= x; j++) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java index 3b501f669ade..042dff375acd 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java @@ -27,8 +27,8 @@ static int knapSack(int W, int[] wt, int[] val, int n) { // Driver code public static void main(String[] args) { - int[] val = new int[] { 60, 100, 120 }; - int[] wt = new int[] { 10, 20, 30 }; + int[] val = new int[] {60, 100, 120}; + int[] wt = new int[] {10, 20, 30}; int W = 50; int n = val.length; System.out.println(knapSack(W, wt, val, n)); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java index 5141e12db2a5..bba637294643 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java @@ -77,13 +77,7 @@ public static void main(String[] args) { // 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 - ); + "The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans); input.close(); } @@ -108,8 +102,7 @@ public static int editDistance(String s1, String s2, int[][] storage) { return storage[m][n]; } if (s1.charAt(0) == s2.charAt(0)) { - storage[m][n] = - editDistance(s1.substring(1), s2.substring(1), storage); + storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage); } else { int op1 = editDistance(s1, s2.substring(1), storage); int op2 = editDistance(s1.substring(1), s2, storage); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java index eee6ab7878e4..ef1ff49465f3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java @@ -25,9 +25,7 @@ public static int minTrials(int n, int m) { for (int j = 2; j <= m; j++) { eggFloor[i][j] = Integer.MAX_VALUE; for (x = 1; x <= j; x++) { - result = - 1 + - Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); // choose min of all values for particular x if (result < eggFloor[i][j]) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java index 521bb2a9d1ba..5d250cd54e3f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java @@ -91,21 +91,22 @@ public static int fibOptimized(int n) { res = next; } return res; -} - + } + /** - * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will look at Binet's formula to calculate the nth Fibonacci number in constant time. - * The Fibonacci terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced ‘phi'. - * First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 = 1.6180339887... - * Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 - * We first calculate the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get the required term. - * Time Complexity will be O(1) - */ - + * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will + * look at Binet's formula to calculate the nth Fibonacci number in constant time. The Fibonacci + * terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced + * ‘phi'. First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 + * = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 We first calculate + * the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get + * the required term. Time Complexity will be O(1) + */ + public static int fibBinet(int n) { double squareRootOf5 = Math.sqrt(5); - double phi = (1 + squareRootOf5)/2; - int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n))/squareRootOf5); + double phi = (1 + squareRootOf5) / 2; + int nthTerm = (int) ((Math.pow(phi, n) - Math.pow(-phi, -n)) / squareRootOf5); return nthTerm; } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java index 1b9f1deea884..63ec477c4590 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java @@ -26,9 +26,7 @@ public static void main(String[] args) { capacity[3][4] = 15; capacity[4][5] = 17; - System.out.println( - "Max capacity in networkFlow : " + networkFlow(0, 5) - ); + System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); } private static int networkFlow(int source, int sink) { @@ -46,10 +44,7 @@ private static int networkFlow(int source, int sink) { int here = q.peek(); q.poll(); for (int there = 0; there < V; ++there) { - if ( - capacity[here][there] - flow[here][there] > 0 && - parent.get(there) == -1 - ) { + if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { q.add(there); parent.set(there, here); } @@ -63,11 +58,7 @@ private static int networkFlow(int source, int sink) { String printer = "path : "; StringBuilder sb = new StringBuilder(); for (int p = sink; p != source; p = parent.get(p)) { - amount = - Math.min( - capacity[parent.get(p)][p] - flow[parent.get(p)][p], - amount - ); + amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); sb.append(p + "-"); } sb.append(source); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index 0c15e2febeb6..51cd6e50ea43 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java index 13296b8456a2..712a028ee960 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java @@ -5,8 +5,7 @@ */ public class Knapsack { - private static int knapSack(int W, int[] wt, int[] val, int n) - throws IllegalArgumentException { + private static int knapSack(int W, int[] wt, int[] val, int n) throws IllegalArgumentException { if (wt == null || val == null) { throw new IllegalArgumentException(); } @@ -19,11 +18,7 @@ private static int knapSack(int W, int[] wt, int[] val, int n) if (i == 0 || w == 0) { rv[i][w] = 0; } else if (wt[i - 1] <= w) { - rv[i][w] = - Math.max( - val[i - 1] + rv[i - 1][w - wt[i - 1]], - rv[i - 1][w] - ); + rv[i][w] = Math.max(val[i - 1] + rv[i - 1][w - wt[i - 1]], rv[i - 1][w]); } else { rv[i][w] = rv[i - 1][w]; } @@ -35,8 +30,8 @@ private static int knapSack(int W, int[] wt, int[] val, int n) // Driver program to test above function public static void main(String[] args) { - int[] val = new int[] { 50, 100, 130 }; - int[] wt = new int[] { 10, 20, 40 }; + int[] val = new int[] {50, 100, 130}; + int[] wt = new int[] {10, 20, 40}; int W = 50; System.out.println(knapSack(W, wt, val, val.length)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java index bcf1909d49d6..161a910bfe99 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java @@ -25,9 +25,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) { } // 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; @@ -39,11 +38,15 @@ int solveKnapsackRecursive(int capacity, int[] weights, 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)), + 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 f2a96187bc91..23222becff8f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java @@ -32,12 +32,9 @@ public static int calculateLevenshteinDistance(String str1, String str2) { 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]); } } } @@ -48,9 +45,7 @@ public static void main(String[] args) { String str1 = ""; // enter your string here String str2 = ""; // enter your string here - System.out.print( - "Levenshtein distance between " + str1 + " and " + str2 + " is: " - ); + System.out.print("Levenshtein distance between " + str1 + " and " + str2 + " is: "); System.out.println(calculateLevenshteinDistance(str1, str2)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java index bfa75a908441..5b508e036ae3 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java @@ -2,12 +2,13 @@ /* - * Problem Statement: - + * Problem Statement: - * Find Longest Alternating Subsequence - * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations : + * A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following + relations : - x1 < x2 > x3 < x4 > x5 < …. xn or + x1 < x2 > x3 < x4 > x5 < …. xn or x1 > x2 < x3 > x4 < x5 > …. xn */ public class LongestAlternatingSubsequence { @@ -16,16 +17,16 @@ public class LongestAlternatingSubsequence { static int AlternatingLength(int[] arr, int n) { /* - las[i][0] = Length of the longest - alternating subsequence ending at - index i and last element is - greater than its previous element + las[i][0] = Length of the longest + alternating subsequence ending at + index i and last element is + greater than its previous element - las[i][1] = Length of the longest - alternating subsequence ending at - index i and last element is - smaller than its previous - element + las[i][1] = Length of the longest + alternating subsequence ending at + index i and last element is + smaller than its previous + element */ int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence @@ -61,12 +62,9 @@ static int AlternatingLength(int[] arr, int n) { } public static void main(String[] args) { - int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 }; + int[] arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.length; - System.out.println( - "Length of Longest " + - "alternating subsequence is " + - AlternatingLength(arr, n) - ); + System.out.println("Length of Longest " + + "alternating subsequence is " + AlternatingLength(arr, n)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java index a2711a810cf8..72fbc89397c0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java @@ -37,11 +37,7 @@ public static String getLCS(String str1, String str2) { return lcsString(str1, str2, lcsMatrix); } - public static String lcsString( - String str1, - String str2, - int[][] lcsMatrix - ) { + public static String lcsString(String str1, String str2, int[][] lcsMatrix) { StringBuilder lcs = new StringBuilder(); int i = str1.length(), j = str2.length(); while (i > 0 && j > 0) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java index 373077e88e4c..e7a54f213ac1 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java @@ -56,8 +56,8 @@ else if (array[i] > tail[length - 1]) { } // array[i] will become end candidate of an existing subsequence or // Throw away larger elements in all LIS, to make room for upcoming grater elements than // array[i] - // (and also, array[i] would have already appeared in one of LIS, identify the location and - // replace it) + // (and also, array[i] would have already appeared in one of LIS, identify the location + // and replace it) else { tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java index d3d7c36b2ef1..68fd6edbaeb5 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java @@ -31,32 +31,21 @@ private static String recursiveLPS(String original, String reverse) { bestResult = ""; } 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) - ); + 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)); - bestResult = - reverse.charAt(reverse.length() - 1) + bestSubResult; + bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; } else { - // otherwise (1) ignore the last character of reverse, and recur on original and updated - // reverse again - // (2) ignore the last character of original and recur on the 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 - ); + // otherwise (1) ignore the last character of reverse, and recur on original and + // updated reverse again (2) ignore the last character of original and recur on the + // 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); if (bestSubResult1.length() > bestSubResult2.length()) { bestResult = bestSubResult1; } else { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java index a2a5427e55c9..f8de2d848294 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java @@ -31,10 +31,7 @@ public static int getLongestValidParentheses(String s) { int index = i - res[i - 1] - 1; if (index >= 0 && chars[index] == '(') { // ()(()) - res[i] = - res[i - 1] + - 2 + - (index - 1 >= 0 ? res[index - 1] : 0); + res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); } } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java index 7a3213558ef2..6dec5b418c50 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java @@ -16,9 +16,7 @@ public class MatrixChainMultiplication { public static void main(String[] args) { int count = 1; while (true) { - String[] mSize = input( - "input size of matrix A(" + count + ") ( ex. 10 20 ) : " - ); + String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); int col = Integer.parseInt(mSize[0]); if (col == 0) { break; @@ -30,12 +28,7 @@ public static void main(String[] args) { count++; } for (Matrix m : mArray) { - System.out.format( - "A(%d) = %2d x %2d%n", - m.count(), - m.col(), - m.row() - ); + System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); } size = mArray.size(); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java index 0bcff7678bd4..b1bf31520d74 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java @@ -28,10 +28,8 @@ static int Lookup_Chain(int[][] m, int[] p, int i, int j) { 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; } @@ -40,12 +38,10 @@ static int Lookup_Chain(int[][] m, int[] p, int i, int j) { return m[i][j]; } - // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively - // output should be Minimum number of multiplications is 38 + // in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 + // respectively output should be Minimum number of multiplications is 38 public static void main(String[] args) { - int[] arr = { 1, 2, 3, 4, 5 }; - System.out.println( - "Minimum number of multiplications is " + Memoized_Matrix_Chain(arr) - ); + int[] arr = {1, 2, 3, 4, 5}; + System.out.println("Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java index 22e77c047754..cd1f25a46664 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java @@ -28,22 +28,22 @@ The Space Complexity of your algorithm should be smaller than or equal to O(mn). public class MinimumPathSum { public void testRegular() { - int[][] grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } }; + int[][] grid = {{1, 3, 1}, {1, 5, 1}, {4, 2, 1}}; System.out.println(minimumPathSum(grid)); } public void testLessColumns() { - int[][] grid = { { 1, 2 }, { 5, 6 }, { 1, 1 } }; + int[][] grid = {{1, 2}, {5, 6}, {1, 1}}; System.out.println(minimumPathSum(grid)); } public void testLessRows() { - int[][] grid = { { 2, 3, 3 }, { 7, 2, 1 } }; + int[][] grid = {{2, 3, 3}, {7, 2, 1}}; System.out.println(minimumPathSum(grid)); } public void testOneRowOneColumn() { - int[][] grid = { { 2 } }; + int[][] grid = {{2}}; System.out.println(minimumPathSum(grid)); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java index 78676c0085b4..c15c0186fc62 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java @@ -82,8 +82,8 @@ public static int getMin(int[] arr, int sum) { * Driver Code */ public static void main(String[] args) { - assert subSet(new int[] { 1, 6, 11, 5 }) == 1; - assert subSet(new int[] { 36, 7, 46, 40 }) == 23; - assert subSet(new int[] { 1, 2, 3, 9 }) == 3; + assert subSet(new int[] {1, 6, 11, 5}) == 1; + assert subSet(new int[] {36, 7, 46, 40}) == 23; + assert subSet(new int[] {1, 2, 3, 9}) == 3; } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java index d41135b1f118..5aa0bf027c02 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index 071880af5d9d..52ffaf191bae 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -22,9 +22,11 @@ public class OptimalJobScheduling { * @param numberProcesses ,refers to the number of precedent processes(N) * @param numberMachines ,refers to the number of different machines in our disposal(M) * @param Run , N*M matrix refers to the cost of running each process to each machine - * @param Transfer ,M*M symmetric matrix refers to the transportation delay for each pair of machines + * @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; @@ -35,7 +37,7 @@ public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] Run /** * Function which computes the cost of process scheduling to a number of VMs. */ - public void execute(){ + public void execute() { this.calculateCost(); this.showResults(); } @@ -43,11 +45,11 @@ public void execute(){ /** * Function which computes the cost of running each Process to each and every Machine */ - private void calculateCost(){ + private void calculateCost() { - for (int i=0; i < numberProcesses; i++){ //for each Process + for (int i = 0; i < numberProcesses; i++) { // for each Process - for (int j=0; j < numberMachines; j++) { //for each Machine + for (int j = 0; j < numberMachines; j++) { // for each Machine Cost[i][j] = runningCost(i, j); } @@ -55,10 +57,12 @@ private void calculateCost(){ } /** - * Function which returns the minimum cost of running a certain Process to a certain Machine.In order for the Machine to execute the Process ,he requires the output - * of the previously executed Process, which may have been executed to the same Machine or some other.If the previous Process has been executed to another Machine,we - * have to transfer her result, which means extra cost for transferring the data from one Machine to another(if the previous Process has been executed to the same - * Machine, there is no transport cost). + * Function which returns the minimum cost of running a certain Process to a certain Machine.In + * order for the Machine to execute the Process ,he requires the output of the previously + * executed Process, which may have been executed to the same Machine or some other.If the + * previous Process has been executed to another Machine,we have to transfer her result, which + * means extra cost for transferring the data from one Machine to another(if the previous + * Process has been executed to the same Machine, there is no transport cost). * * @param process ,refers to the Process * @param machine ,refers to the Machine @@ -66,32 +70,38 @@ private void calculateCost(){ */ private int runningCost(int process, int machine) { - if (process==0) //refers to the first process,which does not require for a previous one to have been executed + if (process == 0) // refers to the first process,which does not require for a previous one + // to have been executed 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 + 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 - return findMin(runningCosts); //returns the minimum running cost + return findMin(runningCosts); // returns the minimum running cost } } /** * Function used in order to return the minimum Cost. - * @param cost ,an Array of size M which refers to the costs of executing a Process to each Machine + * @param cost ,an Array of size M which refers to the costs of executing a Process to each + * Machine * @return the minimum cost */ private int findMin(int[] cost) { - int min=0; + int min = 0; - for (int i=1;i<cost.length;i++){ + for (int i = 1; i < cost.length; i++) { - if (cost[i]<cost[min]) - min=i; + if (cost[i] < cost[min]) min = i; } return cost[min]; } @@ -99,11 +109,11 @@ private int findMin(int[] cost) { /** * Method used in order to present the overall costs. */ - private void showResults(){ + private void showResults() { - for (int i=0; i < numberProcesses; i++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++) { + for (int j = 0; j < numberMachines; j++) { System.out.print(Cost[i][j]); System.out.print(" "); } @@ -116,7 +126,7 @@ private void showResults(){ /** * Getter for the running Cost of i process on j machine. */ - public int getCost(int process,int machine) { + public int getCost(int process, int machine) { return Cost[process][machine]; } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java index 98b9d163141c..00a9bda25b0b 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java @@ -22,9 +22,9 @@ public class PalindromicPartitioning { public static int minimalpartitions(String word) { int len = word.length(); /* We Make two arrays to create a bottom-up solution. - minCuts[i] = Minimum number of cuts needed for palindrome partitioning of substring word[0..i] - isPalindrome[i][j] = true if substring str[i..j] is palindrome - Base Condition: C[i] is 0 if P[0][i]= true + minCuts[i] = Minimum number of cuts needed for palindrome partitioning of substring + word[0..i] isPalindrome[i][j] = true if substring str[i..j] is palindrome Base Condition: + C[i] is 0 if P[0][i]= true */ int[] minCuts = new int[len]; boolean[][] isPalindrome = new boolean[len][len]; @@ -36,7 +36,8 @@ public static int minimalpartitions(String word) { isPalindrome[i][i] = true; } - /* L is substring length. Build the solution in bottom up manner by considering all substrings of length starting from 2 to n. */ + /* L is substring length. Build the solution in bottom up manner by considering all + * substrings of length starting from 2 to n. */ for (L = 2; L <= len; L++) { // For substring of length L, set different possible starting indexes for (i = 0; i < len - L + 1; i++) { @@ -48,23 +49,20 @@ public static int minimalpartitions(String word) { 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]; } } } - //We find the minimum for each index + // We find the minimum for each index for (i = 0; i < len; i++) { if (isPalindrome[0][i]) { minCuts[i] = 0; } else { minCuts[i] = Integer.MAX_VALUE; for (j = 0; j < i; j++) { - if ( - isPalindrome[j + 1][i] && - 1 + minCuts[j] < minCuts[i] - ) { + if (isPalindrome[j + 1][i] && 1 + minCuts[j] < minCuts[i]) { minCuts[i] = 1 + minCuts[j]; } } @@ -84,11 +82,7 @@ public static void main(String[] args) { // 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 - ); + "The minimum cuts needed to partition \"" + word + "\" into palindromes is " + ans); input.close(); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java index 1fbbaf469342..efe5cc883daf 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java @@ -27,14 +27,14 @@ public class PartitionProblem { * @param nums the array contains integers. * @return {@code true} if two subset exists, otherwise {@code false}. */ - public static boolean partition(int[] nums) - { + public static boolean partition(int[] nums) { // calculate the sum of all the elements in the array int sum = Arrays.stream(nums).sum(); - // it will return true if the sum is even and the array can be divided into two subarrays/subset with equal sum. - // and here i reuse the SubsetSum class from dynamic programming section to check if there is exists a - // subsetsum into nums[] array same as the given sum - return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum/2); + // it will return true if the sum is even and the array can be divided into two + // subarrays/subset with equal sum. and here i reuse the SubsetSum class from dynamic + // programming section to check if there is exists a subsetsum into nums[] array same as the + // given sum + return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum / 2); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java index f30267ecc646..57a4707840a0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java @@ -52,12 +52,7 @@ static boolean regexRecursion(String src, String pat) { // Method 2: Using Recursion and breaking string using virtual index // Time Complexity=0(2^(N+M)) Space Complexity=Recursion Extra Space - static boolean regexRecursion( - String src, - String pat, - int svidx, - int pvidx - ) { + static boolean regexRecursion(String src, String pat, int svidx, int pvidx) { if (src.length() == svidx && pat.length() == pvidx) { return true; } @@ -90,13 +85,7 @@ static boolean regexRecursion( // Method 3: Top-Down DP(Memoization) // Time Complexity=0(N*M) Space Complexity=0(N*M)+Recursion Extra Space - static boolean regexRecursion( - String src, - String pat, - int svidx, - int pvidx, - int[][] strg - ) { + static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[][] strg) { if (src.length() == svidx && pat.length() == pvidx) { return true; } @@ -171,9 +160,7 @@ public static void main(String[] args) { 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()]) - ); + "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/RodCutting.java b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java index 066113a235f1..28ff41d1a2d1 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java @@ -25,7 +25,7 @@ private static int cutRod(int[] price, int n) { // main function to test public static void main(String[] args) { - int[] arr = new int[] { 2, 5, 13, 19, 20 }; + int[] arr = new int[] {2, 5, 13, 19, 20}; int result = cutRod(arr, arr.length); System.out.println("Maximum Obtainable Value is " + result); } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java index c24bdeda6485..78baaa32e1a4 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java @@ -49,10 +49,7 @@ public static void main(String[] args) { String X = "AGGTAB"; String Y = "GXTXAYB"; - System.out.println( - "Length of the shortest " + - "supersequence is " + - shortestSuperSequence(X, Y) - ); + System.out.println("Length of the shortest " + + "supersequence is " + shortestSuperSequence(X, Y)); } } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java index 46ba3999c8ad..ef1c6c8f89f0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java @@ -2,68 +2,66 @@ /** * Find the number of subsets present in the given array with a sum equal to target. - * Based on Solution discussed on StackOverflow(https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k) + * Based on Solution discussed on + * StackOverflow(https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k) * @author Samrat Podder(https://github.com/samratpodder) */ public class SubsetCount { - /** * Dynamic Programming Implementation. - * Method to find out the number of subsets present in the given array with a sum equal to target. - * Time Complexity is O(n*target) and Space Complexity is O(n*target) + * Method to find out the number of subsets present in the given array with a sum equal to + * target. Time Complexity is O(n*target) and Space Complexity is O(n*target) * @param arr is the input array on which subsets are to searched * @param target is the sum of each element of the subset taken together * */ - public int getCount(int[] arr, int target){ + public int getCount(int[] arr, int target) { /** * Base Cases - If target becomes zero, we have reached the required sum for the subset - * If we reach the end of the array arr then, either if target==arr[end], then we add one to the final count - * Otherwise we add 0 to the final count + * If we reach the end of the array arr then, either if target==arr[end], then we add one to + * the final count Otherwise we add 0 to the final count */ int n = arr.length; - int[][] dp = new int[n][target+1]; + int[][] dp = new int[n][target + 1]; for (int i = 0; i < n; i++) { dp[i][0] = 1; } - if(arr[0]<=target) dp[0][arr[0]] = 1; - for(int t=1;t<=target;t++){ + if (arr[0] <= target) dp[0][arr[0]] = 1; + for (int t = 1; t <= target; t++) { for (int idx = 1; idx < n; idx++) { - int notpick = dp[idx-1][t]; - int pick =0; - if(arr[idx]<=t) pick+=dp[idx-1][target-t]; - dp[idx][target] = pick+notpick; + int notpick = dp[idx - 1][t]; + int pick = 0; + if (arr[idx] <= t) pick += dp[idx - 1][target - t]; + dp[idx][target] = pick + notpick; } } - return dp[n-1][target]; + return dp[n - 1][target]; } - /** - * This Method is a Space Optimized version of the getCount(int[], int) method and solves the same problem - * This approach is a bit better in terms of Space Used - * Time Complexity is O(n*target) and Space Complexity is O(target) + * This Method is a Space Optimized version of the getCount(int[], int) method and solves the + * same problem This approach is a bit better in terms of Space Used Time Complexity is + * O(n*target) and Space Complexity is O(target) * @param arr is the input array on which subsets are to searched * @param target is the sum of each element of the subset taken together */ - public int getCountSO(int[] arr, int target){ + public int getCountSO(int[] arr, int target) { int n = arr.length; - int[] prev =new int[target+1]; - prev[0] =1; - if(arr[0]<=target) prev[arr[0]] = 1; - for(int ind = 1; ind<n; ind++){ - int[] cur =new int[target+1]; - cur[0]=1; - for(int t= 1; t<=target; t++){ + int[] prev = new int[target + 1]; + prev[0] = 1; + if (arr[0] <= target) prev[arr[0]] = 1; + for (int ind = 1; ind < n; ind++) { + int[] cur = new int[target + 1]; + cur[0] = 1; + for (int t = 1; t <= target; t++) { int notTaken = prev[t]; int taken = 0; - if(arr[ind]<=t) taken = prev[t-arr[ind]]; - cur[t]= notTaken + taken; + if (arr[ind] <= t) taken = prev[t - arr[ind]]; + cur[t] = notTaken + taken; } prev = cur; } return prev[target]; } - } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java index 07cb448a8353..33696947c008 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java @@ -6,7 +6,7 @@ public class SubsetSum { * Driver Code */ public static void main(String[] args) { - int[] arr = new int[] { 50, 4, 10, 15, 34 }; + int[] arr = new int[] {50, 4, 10, 15, 34}; assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */ assert subsetSum(arr, 99); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java b/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java index 896907757c89..90c07889a57f 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java @@ -3,7 +3,7 @@ public class Sum_Of_Subset { public static void main(String[] args) { - int[] arr = { 7, 3, 2, 5, 8 }; + int[] arr = {7, 3, 2, 5, 8}; int Key = 14; if (subsetSum(arr, arr.length - 1, Key)) { diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java index 7068c2890320..2cfb8ef25058 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java @@ -1,12 +1,13 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ /** * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. - * The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). - * How many possible unique paths are there? + * The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram + * below). How many possible unique paths are there? */ /** Program description - To find the number of unique paths possible */ @@ -51,11 +52,8 @@ public static boolean uniquePaths2(int m, int n, int ans) { /** * OUTPUT : * Input - m = 3, n = 7 - * Output: it returns either true if expected answer matches with the predicted answer else it returns false - * 1st approach Time Complexity : O(n) - * Auxiliary Space Complexity : O(n) - * Input - m = 3, n = 7 - * Output: it returns either true if expected answer matches with the predicted answer else it returns false - * 2nd approach Time Complexity : O(m*n) - * Auxiliary Space Complexity : O(m*n) + * Output: it returns either true if expected answer matches with the predicted answer else it + * returns false 1st approach Time Complexity : O(n) Auxiliary Space Complexity : O(n) Input - m = + * 3, n = 7 Output: it returns either true if expected answer matches with the predicted answer else + * it returns false 2nd approach Time Complexity : O(m*n) Auxiliary Space Complexity : O(m*n) */ diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java index 8e48218063c6..dd35842899c6 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java @@ -73,12 +73,10 @@ public static int WPBU(int[] arr) { } public static void main(String[] args) { - int[] arr = { 2, 3, 5, 1, 4 }; + int[] arr = {2, 3, 5, 1, 4}; System.out.println("Method 1: " + WPRecursion(arr, 0, arr.length - 1)); System.out.println( - "Method 2: " + - WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length]) - ); + "Method 2: " + WPTD(arr, 0, arr.length - 1, new int[arr.length][arr.length])); System.out.println("Method 3: " + WPBU(arr)); } } diff --git a/src/main/java/com/thealgorithms/geometry/GrahamScan.java b/src/main/java/com/thealgorithms/geometry/GrahamScan.java index 9b527597100e..3325a65829e0 100644 --- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java +++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java @@ -22,8 +22,8 @@ public class GrahamScan { public GrahamScan(Point[] points) { /* - * pre-process the points by sorting them with respect to the bottom-most point, then we'll push the - * first point in the array to be our first extreme point. + * pre-process the points by sorting them with respect to the bottom-most point, then we'll + * push the first point in the array to be our first extreme point. */ Arrays.sort(points); Arrays.sort(points, 1, points.length, points[0].polarOrder()); @@ -37,9 +37,9 @@ public GrahamScan(Point[] points) { if (indexPoint1 == points.length) return; int indexPoint2; - for (indexPoint2 = indexPoint1+1; indexPoint2 < points.length; indexPoint2++) + for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) break; - hull.push(points[indexPoint2-1]); + hull.push(points[indexPoint2 - 1]); // Now we simply add the point to the stack based on the orientation. for (int i = indexPoint2; i < points.length; i++) { @@ -68,88 +68,98 @@ public record Point(int x, int y) implements Comparable<Point> { * @param x x-coordinate * @param y y-coordinate */ - public Point { } - - /** - * @return the x-coordinate - */ - @Override - public int x() { - return x; - } + public Point { + } - /** - * @return the y-coordinate - */ - @Override - public int y() { return y; } - - /** - * Finds the orientation of ordered triplet. - * - * @param a Co-ordinates of point a <int, int> - * @param b Co-ordinates of point a <int, int> - * @param c Co-ordinates of point a <int, int> - * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise } turn. - */ - public static int orientation(Point a, Point b, Point c) { - int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); - if (val == 0) { - return 0; - } - return (val > 0) ? +1 : -1; - } + /** + * @return the x-coordinate + */ + @Override + public int x() { + return x; + } - /** - * @param p2 Co-ordinate of point to compare to. - * This function will compare the points and will return a positive integer it the - * point is greater than the argument point and a negative integer if the point is - * less than the argument point. - */ - public int compareTo(Point p2) { - if (this.y < p2.y) return -1; - if (this.y > p2.y) return +1; - if (this.x < p2.x) return -1; - if (this.x > p2.x) return +1; + /** + * @return the y-coordinate + */ + @Override + public int y() { + return y; + } + + /** + * Finds the orientation of ordered triplet. + * + * @param a Co-ordinates of point a <int, int> + * @param b Co-ordinates of point a <int, int> + * @param c Co-ordinates of point a <int, int> + * @return { -1, 0, +1 } if a -→ b -→ c is a { clockwise, collinear; counterclockwise } + * turn. + */ + public static int orientation(Point a, Point b, Point c) { + int val = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); + if (val == 0) { return 0; } + return (val > 0) ? +1 : -1; + } - /** - * A helper function that will let us sort points by their polar order - * This function will compare the angle between 2 polar Co-ordinates - * - * @return the comparator - */ - public Comparator<Point> polarOrder() { - return new PolarOrder(); - } + /** + * @param p2 Co-ordinate of point to compare to. + * This function will compare the points and will return a positive integer it the + * point is greater than the argument point and a negative integer if the point is + * less than the argument point. + */ + public int compareTo(Point p2) { + if (this.y < p2.y) return -1; + if (this.y > p2.y) return +1; + if (this.x < p2.x) return -1; + if (this.x > p2.x) return +1; + return 0; + } - private class PolarOrder implements Comparator<Point> { - public int compare(Point p1, Point p2) { - int dx1 = p1.x - x; - int dy1 = p1.y - y; - int dx2 = p2.x - x; - int dy2 = p2.y - y; - - if (dy1 >= 0 && dy2 < 0) return -1; // q1 above; q2 below - else if (dy2 >= 0 && dy1 < 0) return +1; // q1 below; q2 above - else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal - if (dx1 >= 0 && dx2 < 0) return -1; - else if (dx2 >= 0 && dx1 < 0) return +1; - else return 0; - } else return -orientation(Point.this, p1, p2); // both above or below - } - } + /** + * A helper function that will let us sort points by their polar order + * This function will compare the angle between 2 polar Co-ordinates + * + * @return the comparator + */ + public Comparator<Point> polarOrder() { + return new PolarOrder(); + } - /** - * Override of the toString method, necessary to compute the difference - * between the expected result and the derived result - * - * @return a string representation of any given 2D point in the format (x, y) - */ - @Override - public String toString() { - return "(" + x + ", " + y + ")"; + private class PolarOrder implements Comparator<Point> { + public int compare(Point p1, Point p2) { + int dx1 = p1.x - x; + int dy1 = p1.y - y; + int dx2 = p2.x - x; + int dy2 = p2.y - y; + + if (dy1 >= 0 && dy2 < 0) + return -1; // q1 above; q2 below + else if (dy2 >= 0 && dy1 < 0) + return +1; // q1 below; q2 above + else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal + if (dx1 >= 0 && dx2 < 0) + return -1; + else if (dx2 >= 0 && dx1 < 0) + return +1; + else + return 0; + } else + return -orientation(Point.this, p1, p2); // both above or below } } + + /** + * Override of the toString method, necessary to compute the difference + * between the expected result and the derived result + * + * @return a string representation of any given 2D point in the format (x, y) + */ + @Override + public String toString() { + return "(" + x + ", " + y + ")"; + } + } } diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java index 1012ce79690f..8bd96cc9d132 100644 --- a/src/main/java/com/thealgorithms/io/BufferedReader.java +++ b/src/main/java/com/thealgorithms/io/BufferedReader.java @@ -13,181 +13,175 @@ */ public class BufferedReader { - private static final int DEFAULT_BUFFER_SIZE = 5; - - /** - * Maximum number of bytes the buffer can hold. - * Value is changed when encountered Eof to not - * cause overflow read of 0 bytes - */ - - private int bufferSize; - private final byte[] buffer; - - /** - * posRead -> indicates the next byte to read - */ - private int posRead = 0, bufferPos = 0; - - private boolean foundEof = false; - - private InputStream input; - - public BufferedReader(byte[] input) throws IOException { - this(new ByteArrayInputStream(input)); - } - - public BufferedReader(InputStream input) throws IOException { - this(input, DEFAULT_BUFFER_SIZE); - } - - public BufferedReader(InputStream input, int bufferSize) throws IOException { - this.input = input; - if (input.available() == -1) - throw new IOException("Empty or already closed stream provided"); - - this.bufferSize = bufferSize; - buffer = new byte[bufferSize]; - } - - /** - * Reads a single byte from the stream - */ - public int read() throws IOException { - if (needsRefill()) { - if (foundEof) - return -1; - // the buffer is empty, or the buffer has - // been completely read and needs to be refilled - refill(); + private static final int DEFAULT_BUFFER_SIZE = 5; + + /** + * Maximum number of bytes the buffer can hold. + * Value is changed when encountered Eof to not + * cause overflow read of 0 bytes + */ + + private int bufferSize; + private final byte[] buffer; + + /** + * posRead -> indicates the next byte to read + */ + private int posRead = 0, bufferPos = 0; + + private boolean foundEof = false; + + private InputStream input; + + public BufferedReader(byte[] input) throws IOException { + this(new ByteArrayInputStream(input)); + } + + public BufferedReader(InputStream input) throws IOException { + this(input, DEFAULT_BUFFER_SIZE); + } + + public BufferedReader(InputStream input, int bufferSize) throws IOException { + this.input = input; + if (input.available() == -1) + throw new IOException("Empty or already closed stream provided"); + + this.bufferSize = bufferSize; + buffer = new byte[bufferSize]; } - return buffer[posRead++] & 0xff; // read and un-sign it - } - - /** - * Number of bytes not yet been read - */ - - public int available() throws IOException { - int available = input.available(); - if (needsRefill()) - // since the block is already empty, - // we have no responsibility yet - return available; - return bufferPos - posRead + available; - } - - /** - * Returns the next character - */ - - public int peek() throws IOException { - return peek(1); - } - - /** - * Peeks and returns a value located at next {n} - */ - - 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)); - pushRefreshData(); - - if (n >= bufferSize) - throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)" - .formatted(n, bufferSize)); - return buffer[n]; - } - - /** - * Removes the already read bytes from the buffer - * in-order to make space for new bytes to be filled up. - * <p> - * This may also do the job to read first time data (whole buffer is empty) - */ - - private void pushRefreshData() throws IOException { - for (int i = posRead, j = 0; i < bufferSize; i++, j++) - buffer[j] = buffer[i]; - - bufferPos -= posRead; - posRead = 0; - - // fill out the spaces that we've - // emptied - justRefill(); - } - - /** - * Reads one complete block of size {bufferSize} - * if found eof, the total length of array will - * be that of what's available - * - * @return a completed block - */ - public byte[] readBlock() throws IOException { - pushRefreshData(); - - byte[] cloned = new byte[bufferSize]; - // arraycopy() function is better than clone() - if (bufferPos >= 0) - System.arraycopy(buffer, - 0, - cloned, - 0, - // important to note that, bufferSize does not stay constant - // once the class is defined. See justRefill() function - bufferSize); - // we assume that already a chunk - // has been read - refill(); - return cloned; - } - - private boolean needsRefill() { - return bufferPos == 0 || posRead == bufferSize; - } - - private void refill() throws IOException { - posRead = 0; - bufferPos = 0; - justRefill(); - } - - private void justRefill() throws IOException { - assertStreamOpen(); - - // try to fill in the maximum we can until - // we reach EOF - while (bufferPos < bufferSize) { - int read = input.read(); - if (read == -1) { - // reached end-of-file, no more data left - // to be read - foundEof = true; - // rewrite the BUFFER_SIZE, to know that we've reached - // EOF when requested refill - bufferSize = bufferPos; - } - buffer[bufferPos++] = (byte) read; + + /** + * Reads a single byte from the stream + */ + public int read() throws IOException { + if (needsRefill()) { + if (foundEof) return -1; + // the buffer is empty, or the buffer has + // been completely read and needs to be refilled + refill(); + } + return buffer[posRead++] & 0xff; // read and un-sign it + } + + /** + * Number of bytes not yet been read + */ + + public int available() throws IOException { + int available = input.available(); + if (needsRefill()) + // since the block is already empty, + // we have no responsibility yet + return available; + return bufferPos - posRead + available; } - } - - private void assertStreamOpen() { - if (input == null) - throw new IllegalStateException("Input Stream already closed!"); - } - - public void close() throws IOException { - if (input != null) { - try { - input.close(); - } finally { - input = null; - } + + /** + * Returns the next character + */ + + public int peek() throws IOException { + return peek(1); + } + + /** + * Peeks and returns a value located at next {n} + */ + + 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)); + pushRefreshData(); + + if (n >= bufferSize) + throw new IllegalAccessError( + "Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + return buffer[n]; + } + + /** + * Removes the already read bytes from the buffer + * in-order to make space for new bytes to be filled up. + * <p> + * This may also do the job to read first time data (whole buffer is empty) + */ + + private void pushRefreshData() throws IOException { + for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i]; + + bufferPos -= posRead; + posRead = 0; + + // fill out the spaces that we've + // emptied + justRefill(); + } + + /** + * Reads one complete block of size {bufferSize} + * if found eof, the total length of array will + * be that of what's available + * + * @return a completed block + */ + public byte[] readBlock() throws IOException { + pushRefreshData(); + + byte[] cloned = new byte[bufferSize]; + // arraycopy() function is better than clone() + if (bufferPos >= 0) + System.arraycopy(buffer, 0, cloned, 0, + // important to note that, bufferSize does not stay constant + // once the class is defined. See justRefill() function + bufferSize); + // we assume that already a chunk + // has been read + refill(); + return cloned; + } + + private boolean needsRefill() { + return bufferPos == 0 || posRead == bufferSize; + } + + private void refill() throws IOException { + posRead = 0; + bufferPos = 0; + justRefill(); + } + + private void justRefill() throws IOException { + assertStreamOpen(); + + // try to fill in the maximum we can until + // we reach EOF + while (bufferPos < bufferSize) { + int read = input.read(); + if (read == -1) { + // reached end-of-file, no more data left + // to be read + foundEof = true; + // rewrite the BUFFER_SIZE, to know that we've reached + // EOF when requested refill + bufferSize = bufferPos; + } + buffer[bufferPos++] = (byte) read; + } + } + + private void assertStreamOpen() { + if (input == null) throw new IllegalStateException("Input Stream already closed!"); + } + + public void close() throws IOException { + if (input != null) { + try { + input.close(); + } finally { + input = null; + } + } } - } } diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java index d0eaddfaacf5..1ffd3d67d384 100644 --- a/src/main/java/com/thealgorithms/maths/ADTFraction.java +++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java @@ -21,11 +21,8 @@ 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); } @@ -64,7 +61,8 @@ public ADTFraction reciprocal() { /** * Calculates the result of the fraction. * - * @return The numerical result of the division between {@code numerator} and {@code denominator} + * @return The numerical result of the division between {@code numerator} and {@code + * denominator} */ public float value() { return (float) this.numerator / this.denominator; diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java index d5b278481aee..a8796ae40324 100644 --- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java +++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java @@ -15,12 +15,9 @@ public static int getMinValue(int... numbers) { throw new IllegalArgumentException("Numbers array cannot be empty"); } - var absMinWrapper = new Object() { - int value = numbers[0]; - }; + var absMinWrapper = new Object() { int value = numbers[0]; }; - Arrays - .stream(numbers) + Arrays.stream(numbers) .skip(1) .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value)) .forEach(number -> absMinWrapper.value = number); diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index 6eb18f260db9..b9c7d3819da2 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -18,28 +18,24 @@ public class AliquotSum { * @return aliquot sum of given {@code number} */ public static int getAliquotValue(int number) { - var sumWrapper = new Object() { - int value = 0; - }; + var sumWrapper = new Object() { int value = 0; }; - IntStream - .iterate(1, i -> ++i) + IntStream.iterate(1, i -> ++i) .limit(number / 2) .filter(i -> number % i == 0) .forEach(i -> sumWrapper.value += i); return sumWrapper.value; } - - /** + + /** * Function to calculate the aliquot sum of an integer number * * @param n a positive integer * @return aliquot sum of given {@code number} */ public static int getAliquotSum(int n) { - if (n <= 0) - return -1; + if (n <= 0) return -1; int sum = 1; double root = Math.sqrt(n); /* @@ -56,9 +52,9 @@ public static int getAliquotSum(int n) { sum += i + n / i; } } - // if n is a perfect square then its root was added twice in above loop, so subtracting root from sum - if (root == (int) root) - sum -= root; + // if n is a perfect square then its root was added twice in above loop, so subtracting root + // from sum + if (root == (int) root) sum -= root; return sum; } } diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java index 3efea0e16f4f..f52470833e65 100644 --- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java +++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java @@ -21,9 +21,8 @@ public class AmicableNumber { public static void main(String[] args) { AmicableNumber.findAllInRange(1, 3000); - /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210) - 3: = ( 2620,2924) So it worked */ - + /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) + 2: = ( 1184,1210) 3: = ( 2620,2924) So it worked */ } /** @@ -32,8 +31,9 @@ public static void main(String[] args) { * @return */ static void findAllInRange(int startValue, int stopValue) { - /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation - * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber + /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) + * is the same calculation also to avoid is to check the number with it self. a number with + * itself is always a AmicableNumber * */ StringBuilder res = new StringBuilder(); int countofRes = 0; @@ -42,22 +42,14 @@ static void findAllInRange(int startValue, int stopValue) { for (int j = i + 1; j <= stopValue; j++) { if (isAmicableNumber(i, j)) { countofRes++; - res.append( - "" + countofRes + ": = ( " + i + "," + j + ")" + "\t" - ); + res.append("" + countofRes + ": = ( " + i + "," + j + ")" + + "\t"); } } } - 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); } @@ -69,12 +61,8 @@ static void findAllInRange(int startValue, int stopValue) { * 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 262669fe8087..b4bae5ae9a13 100644 --- a/src/main/java/com/thealgorithms/maths/Area.java +++ b/src/main/java/com/thealgorithms/maths/Area.java @@ -135,7 +135,8 @@ public static double surfaceAreaParallelogram(final double base, final double he * @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 3ea898cc4a7f..55c4864f0e00 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -20,15 +20,15 @@ public class AutomorphicNumber { * {@code false} */ public static boolean isAutomorphic(long n) { - if (n < 0) - return false; + if (n < 0) return false; long square = n * n; // Calculating square of the number long t = n, numberOfdigits = 0; while (t > 0) { 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; } @@ -40,8 +40,7 @@ public static boolean isAutomorphic(long n) { * {@code false} */ public static boolean isAutomorphic2(long n) { - if (n < 0) - return false; + if (n < 0) return false; long square = n * n; // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } @@ -55,8 +54,7 @@ public static boolean isAutomorphic2(long n) { */ public static boolean isAutomorphic3(String s) { BigInteger n = new BigInteger(s); - if (n.signum() == -1) - return false; //if number is negative, return false + if (n.signum() == -1) return false; // if number is negative, return false BigInteger square = n.multiply(n); // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java index 18f0d12b67f8..5e7271a6137e 100644 --- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java +++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java @@ -17,13 +17,11 @@ public class BinomialCoefficient { * * @param totalObjects Total number of objects * @param numberOfObjects Number of objects to be chosen from total_objects - * @return number of ways in which no_of_objects objects can be chosen from total_objects objects + * @return number of ways in which no_of_objects objects can be chosen from total_objects + * objects */ - public static int binomialCoefficient( - int totalObjects, - int numberOfObjects - ) { + public static int binomialCoefficient(int totalObjects, int numberOfObjects) { // Base Case if (numberOfObjects > totalObjects) { return 0; @@ -35,9 +33,7 @@ public static int 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 693fbbe9b38a..b66499b349b7 100644 --- a/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java @@ -39,14 +39,14 @@ private static void padding(ArrayList<FFT.Complex> x, int newSize) { * @return The convolved signal. */ public static ArrayList<FFT.Complex> fftCircularConvolution( - ArrayList<FFT.Complex> a, - ArrayList<FFT.Complex> b - ) { - int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one + ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) { + int convolvedSize = Math.max( + a.size(), b.size()); // The two signals must have the same size equal to the bigger one padding(a, convolvedSize); // Zero padding the smaller signal padding(b, convolvedSize); - /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT to have the same length with the signal and not bigger */ + /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT + * to have the same length with the signal and not bigger */ FFTBluestein.fftBluestein(a, false); FFTBluestein.fftBluestein(b, false); ArrayList<FFT.Complex> convolved = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/maths/Convolution.java b/src/main/java/com/thealgorithms/maths/Convolution.java index 8a89d31ad3c5..cafb36f7a2b1 100644 --- a/src/main/java/com/thealgorithms/maths/Convolution.java +++ b/src/main/java/com/thealgorithms/maths/Convolution.java @@ -27,8 +27,9 @@ public static double[] convolution(double[] A, double[] B) { C[i] = Σ (A[k]*B[i-k]) k=0 - It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1 - From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below. + It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= + B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get + the conditions below. */ for (int i = 0; i < convolved.length; i++) { convolved[i] = 0; diff --git a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java index c5f48815de46..cacde4b886ba 100644 --- a/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java +++ b/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java @@ -43,14 +43,13 @@ private static void padding(ArrayList<FFT.Complex> x, int newSize) { * @return The convolved signal. */ public static ArrayList<FFT.Complex> convolutionFFT( - ArrayList<FFT.Complex> a, - ArrayList<FFT.Complex> b - ) { + ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) { int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal padding(a, convolvedSize); // Zero padding both signals padding(b, convolvedSize); - /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the convolvedSize because of the extra zero padding in FFT algorithm) */ + /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the + * convolvedSize because of the extra zero padding in FFT algorithm) */ FFT.fft(a, false); FFT.fft(b, false); ArrayList<FFT.Complex> convolved = new ArrayList<>(); @@ -59,7 +58,9 @@ public static ArrayList<FFT.Complex> 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/DeterminantOfMatrix.java b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java index 388bf396975b..c1ef3fc09e1d 100644 --- a/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java +++ b/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java @@ -37,10 +37,10 @@ static int determinant(int[][] a, int n) { return det; } - //Driver Method + // Driver Method public static void main(String[] args) { Scanner in = new Scanner(System.in); - //Input Matrix + // Input Matrix System.out.println("Enter matrix size (Square matrix only)"); int n = in.nextInt(); System.out.println("Enter matrix"); diff --git a/src/main/java/com/thealgorithms/maths/DigitalRoot.java b/src/main/java/com/thealgorithms/maths/DigitalRoot.java index 6a3541f3454d..78066f404739 100644 --- a/src/main/java/com/thealgorithms/maths/DigitalRoot.java +++ b/src/main/java/com/thealgorithms/maths/DigitalRoot.java @@ -1,7 +1,9 @@ -/** Author : Suraj Kumar Modi +/** + * Author : Suraj Kumar Modi * https://github.com/skmodi649 */ -/** You are given a number n. You need to find the digital root of n. +/** + * You are given a number n. You need to find the digital root of n. * DigitalRoot of a number is the recursive sum of its digits until we get a single digit number. * * Test Case 1: @@ -19,7 +21,8 @@ * sum of digit of 45 is 9 which is a single * digit number. */ -/** Algorithm : +/** + * Algorithm : * Step 1 : Define a method digitalRoot(int n) * Step 2 : Define another method single(int n) * Step 3 : digitalRoot(int n) method takes output of single(int n) as input @@ -32,14 +35,16 @@ * return n; * else * return (n%10) + (n/10) - * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and print the result + * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and + * print the result */ package com.thealgorithms.maths; class DigitalRoot { public static int digitalRoot(int n) { - if (single(n) <= 9) { // If n is already single digit than simply call single method and return the value + if (single(n) <= 9) { // If n is already single digit than simply call single method and + // return the value return single(n); } else { return digitalRoot(single(n)); @@ -55,7 +60,6 @@ public static int single(int n) { } } // n / 10 is the number obtainded after removing the digit one by one // Sum of digits is stored in the Stack memory and then finally returned - } /** * Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity : diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index 89f9b4298077..9a2654dbeedb 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -2,23 +2,13 @@ public class DistanceFormula { - public static double euclideanDistance( - double x1, - double y1, - double x2, - double y2 - ) { + public static double euclideanDistance(double x1, double y1, double x2, double y2) { double dX = Math.pow(x2 - x1, 2); double dY = Math.pow(y2 - x1, 2); return Math.sqrt(dX + dY); } - public static double manhattanDistance( - double x1, - double y1, - double x2, - double y2 - ) { + public static double manhattanDistance(double x1, double y1, double x2, double y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } diff --git a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java index ab9fb70b1cf0..72c2065e2121 100644 --- a/src/main/java/com/thealgorithms/maths/DudeneyNumber.java +++ b/src/main/java/com/thealgorithms/maths/DudeneyNumber.java @@ -10,7 +10,7 @@ public class DudeneyNumber { - //returns True if the number is a Dudeney number and False if it is not a Dudeney number. + // returns True if the number is a Dudeney number and False if it is not a Dudeney number. public static boolean isDudeney(int n) { // Calculating Cube Root int cube_root = (int) (Math.round((Math.pow(n, 1.0 / 3.0)))); @@ -19,7 +19,7 @@ public static boolean isDudeney(int n) { return false; } int sum_of_digits = 0; // Stores the sums of the digit of the entered number - int temp = n; //A temporary variable to store the entered number + int temp = n; // A temporary variable to store the entered number // Loop to calculate sum of the digits. while (temp > 0) { // Extracting Last digit of the number @@ -32,7 +32,7 @@ public static boolean isDudeney(int n) { temp /= 10; } - //If the cube root of the number is not equal to the sum of its digits we return false. + // If the cube root of the number is not equal to the sum of its digits we return false. return cube_root == sum_of_digits; } } diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java index eca4007656be..a5c5cf8de20b 100644 --- a/src/main/java/com/thealgorithms/maths/EulerMethod.java +++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java @@ -37,15 +37,8 @@ public static void main(String[] args) { // example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ System.out.println("\n\nexample 3:"); - BiFunction<Double, Double, Double> exampleEquation3 = (x, y) -> - x + y + x * y; - ArrayList<double[]> points3 = eulerFull( - 0, - 0.1, - 0.025, - 1, - exampleEquation3 - ); + BiFunction<Double, Double, Double> exampleEquation3 = (x, y) -> x + y + x * y; + ArrayList<double[]> points3 = eulerFull(0, 0.1, 0.025, 1, exampleEquation3); assert points3.get(points3.size() - 1)[1] == 1.1116729841674804; points3.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1])); } @@ -60,16 +53,10 @@ public static void main(String[] args) { * @param differentialEquation The differential equation to be solved. * @return The next y-value. */ - public static double eulerStep( - double xCurrent, - double stepSize, - double yCurrent, - BiFunction<Double, Double, Double> differentialEquation - ) { + public static double eulerStep(double xCurrent, double stepSize, double yCurrent, + BiFunction<Double, Double, Double> differentialEquation) { if (stepSize <= 0) { - throw new IllegalArgumentException( - "stepSize should be greater than zero" - ); + throw new IllegalArgumentException("stepSize should be greater than zero"); } return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent); } @@ -86,36 +73,26 @@ public static double eulerStep( * @return The points constituting the solution of the differential * equation. */ - public static ArrayList<double[]> eulerFull( - double xStart, - double xEnd, - double stepSize, - double yStart, - BiFunction<Double, Double, Double> differentialEquation - ) { + public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize, + double yStart, BiFunction<Double, Double, Double> differentialEquation) { if (xStart >= xEnd) { - throw new IllegalArgumentException( - "xEnd should be greater than xStart" - ); + throw new IllegalArgumentException("xEnd should be greater than xStart"); } if (stepSize <= 0) { - throw new IllegalArgumentException( - "stepSize should be greater than zero" - ); + throw new IllegalArgumentException("stepSize should be greater than zero"); } ArrayList<double[]> points = new ArrayList<double[]>(); - double[] firstPoint = { xStart, yStart }; + double[] firstPoint = {xStart, yStart}; points.add(firstPoint); double yCurrent = yStart; double xCurrent = xStart; while (xCurrent < xEnd) { // Euler method for next step - yCurrent = - eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); + yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); xCurrent += stepSize; - double[] point = { xCurrent, yCurrent }; + double[] point = {xCurrent, yCurrent}; points.add(point); } diff --git a/src/main/java/com/thealgorithms/maths/FFT.java b/src/main/java/com/thealgorithms/maths/FFT.java index 998d0668f5fe..f50bec52997b 100644 --- a/src/main/java/com/thealgorithms/maths/FFT.java +++ b/src/main/java/com/thealgorithms/maths/FFT.java @@ -180,10 +180,7 @@ public Complex divide(double n) { * @param inverse True if you want to find the inverse FFT. * @return */ - public static ArrayList<Complex> fft( - ArrayList<Complex> x, - boolean inverse - ) { + public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int N = x.size(); @@ -220,11 +217,7 @@ public static int findLog2(int N) { } /* Swap the values of the signal with bit-reversal method */ - public static ArrayList<Complex> fftBitReversal( - int N, - int log2N, - ArrayList<Complex> x - ) { + public static ArrayList<Complex> fftBitReversal(int N, int log2N, ArrayList<Complex> x) { int reverse; for (int i = 0; i < N; i++) { reverse = reverseBits(i, log2N); @@ -236,11 +229,7 @@ public static ArrayList<Complex> fftBitReversal( } /* Divide by N if we want the inverse FFT */ - public static ArrayList<Complex> inverseFFT( - int N, - boolean inverse, - ArrayList<Complex> x - ) { + public static ArrayList<Complex> inverseFFT(int N, boolean inverse, ArrayList<Complex> x) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); diff --git a/src/main/java/com/thealgorithms/maths/FFTBluestein.java b/src/main/java/com/thealgorithms/maths/FFTBluestein.java index ffd42bd57198..cd698b62570a 100644 --- a/src/main/java/com/thealgorithms/maths/FFTBluestein.java +++ b/src/main/java/com/thealgorithms/maths/FFTBluestein.java @@ -30,7 +30,8 @@ public static void fftBluestein(ArrayList<FFT.Complex> x, boolean inverse) { ArrayList<FFT.Complex> an = new ArrayList<>(); ArrayList<FFT.Complex> bn = new ArrayList<>(); - /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols used)*/ + /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols + * used)*/ for (int i = 0; i < bnSize; i++) { bn.add(new FFT.Complex()); } @@ -38,26 +39,16 @@ public static void fftBluestein(ArrayList<FFT.Complex> x, boolean inverse) { for (int i = 0; i < N; i++) { double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction; bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle))); - bn.set( - bnSize - i - 1, - new FFT.Complex(Math.cos(angle), Math.sin(angle)) - ); + bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle))); } /* Initialization of the a(n) sequence */ for (int i = 0; i < N; i++) { double angle = -i * i * Math.PI / N * direction; - an.add( - x - .get(i) - .multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle))) - ); + an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))); } - ArrayList<FFT.Complex> convolution = ConvolutionFFT.convolutionFFT( - an, - bn - ); + ArrayList<FFT.Complex> convolution = ConvolutionFFT.convolutionFFT(an, bn); /* The final multiplication of the convolution with the b*(k) factor */ for (int i = 0; i < N; i++) { diff --git a/src/main/java/com/thealgorithms/maths/Factorial.java b/src/main/java/com/thealgorithms/maths/Factorial.java index 4c31e69d78b3..90fcde543a4d 100644 --- a/src/main/java/com/thealgorithms/maths/Factorial.java +++ b/src/main/java/com/thealgorithms/maths/Factorial.java @@ -21,7 +21,8 @@ public static long factorial(int n) { throw new IllegalArgumentException("number is negative"); } long factorial = 1; - for (int i = 1; i <= n; factorial *= i, ++i); + for (int i = 1; i <= n; factorial *= i, ++i) + ; return factorial; } } diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java index 1e30374e57f0..886337478d01 100644 --- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java +++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -22,7 +23,8 @@ public static boolean inverseSqrt(float number) { /** * Returns the inverse square root of the given number upto 6 - 8 decimal places. - * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false + * calculates the inverse square root of the given number and returns true if calculated answer + * matches with given answer else returns false */ public static boolean inverseSqrt(double number) { @@ -39,17 +41,16 @@ public static boolean inverseSqrt(double number) { } /** * Returns the inverse square root of the given number upto 14 - 16 decimal places. - * calculates the inverse square root of the given number and returns true if calculated answer matches with given answer else returns false + * calculates the inverse square root of the given number and returns true if calculated answer + * matches with given answer else returns false */ } /** * OUTPUT : * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 1st approach Time Complexity : O(1) - * Auxiliary Space Complexity : O(1) - * Input - number = 4522 - * Output: it calculates the inverse squareroot of a number and returns true with it matches the given answer else returns false. - * 2nd approach Time Complexity : O(1) + * Output: it calculates the inverse squareroot of a number and returns true with it matches the + * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity : + * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns + * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1) * Auxiliary Space Complexity : O(1) */ diff --git a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java index b6a39adf0517..72e89f0993be 100644 --- a/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java +++ b/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java @@ -25,31 +25,24 @@ public static Optional<BigDecimal> calculate(final BigDecimal index) { return Optional.of(BigDecimal.ONE); } - final List<BigDecimal> results = Stream - .iterate( - index, - x -> x.compareTo(BigDecimal.ZERO) > 0, - x -> x.subtract(BigDecimal.ONE) - ) - .reduce( - List.of(), - (list, current) -> - list.isEmpty() || list.size() < 2 - ? List.of(BigDecimal.ZERO, BigDecimal.ONE) - : List.of(list.get(1), list.get(0).add(list.get(1))), - (list1, list2) -> list1 - ); + final List<BigDecimal> results + = Stream + .iterate( + index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE)) + .reduce(List.of(), + (list, current) + -> list.isEmpty() || list.size() < 2 + ? List.of(BigDecimal.ZERO, BigDecimal.ONE) + : List.of(list.get(1), list.get(0).add(list.get(1))), + (list1, list2) -> list1); - return results.isEmpty() - ? Optional.empty() - : Optional.of(results.get(results.size() - 1)); + 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) - ); + String.format("expected=%s but was actual=%s", expected, actual)); } } @@ -91,39 +84,28 @@ public static void main(final String[] args) { { final Optional<BigDecimal> result = calculate(new BigDecimal(30)); assertThat(result.isPresent(), true); - result.ifPresent(value -> assertThat(value, new BigDecimal(832040)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(832040))); } { final Optional<BigDecimal> result = calculate(new BigDecimal(40)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal(102334155)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(102334155))); } { final Optional<BigDecimal> result = calculate(new BigDecimal(50)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal(12586269025L)) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal(12586269025L))); } { final Optional<BigDecimal> result = calculate(new BigDecimal(100)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat(value, new BigDecimal("354224848179261915075")) - ); + result.ifPresent(value -> assertThat(value, new BigDecimal("354224848179261915075"))); } { final Optional<BigDecimal> result = calculate(new BigDecimal(200)); assertThat(result.isPresent(), true); - result.ifPresent(value -> - assertThat( - value, - new BigDecimal("280571172992510140037611932413038677189525") - ) - ); + result.ifPresent(value + -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525"))); } } } diff --git a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java index 837cd321e971..c38da196f46e 100644 --- a/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java @@ -17,10 +17,8 @@ public static void main(String[] args) { array[i] = rand.nextInt() % 100; } - assert max(array, array.length) == - Arrays.stream(array).max().getAsInt(); - assert max(array, 0, array.length - 1) == - Arrays.stream(array).max().getAsInt(); + assert max(array, array.length) == Arrays.stream(array).max().getAsInt(); + assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt(); } /** @@ -52,8 +50,6 @@ public static int max(int[] array, int low, int high) { * @return max value of {@code array} */ public static int max(int[] array, int len) { - return len == 1 - ? array[0] - : Math.max(max(array, len - 1), array[len - 1]); + return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java index aeee582de01a..66400d23db3f 100644 --- a/src/main/java/com/thealgorithms/maths/FindMinRecursion.java +++ b/src/main/java/com/thealgorithms/maths/FindMinRecursion.java @@ -20,10 +20,8 @@ public static void main(String[] args) { array[i] = rand.nextInt() % 100; } - assert min(array, 0, array.length - 1) == - Arrays.stream(array).min().getAsInt(); - assert min(array, array.length) == - Arrays.stream(array).min().getAsInt(); + assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt(); + assert min(array, array.length) == Arrays.stream(array).min().getAsInt(); } /** @@ -55,8 +53,6 @@ public static int min(int[] array, int low, int high) { * @return min value of {@code array} */ public static int min(int[] array, int len) { - return len == 1 - ? array[0] - : Math.min(min(array, len - 1), array[len - 1]); + return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]); } } diff --git a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java index 48d4fb3b5a46..3b1ff5fde3b3 100644 --- a/src/main/java/com/thealgorithms/maths/FrizzyNumber.java +++ b/src/main/java/com/thealgorithms/maths/FrizzyNumber.java @@ -1,10 +1,10 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ /** Program description - To find the FrizzyNumber*/ - package com.thealgorithms.maths; public class FrizzyNumber { @@ -16,7 +16,7 @@ public class FrizzyNumber { * Ascending order of sums of powers of 3 = * 3^0 = 1, 3^1 = 3, 3^1 + 3^0 = 4, 3^2 + 3^0 = 9 * Ans = 9 - * + * * @param base The base whose n-th sum of powers is required * @param n Index from ascending order of sum of powers of base * @return n-th sum of powers of base @@ -24,8 +24,7 @@ public class FrizzyNumber { public static double getNthFrizzy(int base, int n) { double final1 = 0.0; int i = 0; - do - { + do { final1 += Math.pow(base, i++) * (n % 2); } while ((n /= 2) > 0); return final1; diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java index 96a2b47dc99d..3a69fcab413f 100644 --- a/src/main/java/com/thealgorithms/maths/GCD.java +++ b/src/main/java/com/thealgorithms/maths/GCD.java @@ -48,14 +48,10 @@ public static int gcd(int[] numbers) { } public static void main(String[] args) { - int[] myIntArray = { 4, 16, 32 }; + int[] myIntArray = {4, 16, 32}; // call gcd function (input array) System.out.println(gcd(myIntArray)); // => 4 - System.out.printf( - "gcd(40,24)=%d gcd(24,40)=%d%n", - gcd(40, 24), - gcd(24, 40) - ); // => 8 + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 } } diff --git a/src/main/java/com/thealgorithms/maths/Gaussian.java b/src/main/java/com/thealgorithms/maths/Gaussian.java index 9bb7c03586c6..fd0f86d89f89 100644 --- a/src/main/java/com/thealgorithms/maths/Gaussian.java +++ b/src/main/java/com/thealgorithms/maths/Gaussian.java @@ -4,10 +4,7 @@ public class Gaussian { - public static ArrayList<Double> gaussian( - int mat_size, - ArrayList<Double> matrix - ) { + public static ArrayList<Double> gaussian(int mat_size, ArrayList<Double> matrix) { ArrayList<Double> answerArray = new ArrayList<Double>(); int i, j = 0; @@ -27,11 +24,7 @@ public static ArrayList<Double> gaussian( } // Perform Gaussian elimination - public static double[][] gaussianElimination( - int mat_size, - int i, - double[][] mat - ) { + public static double[][] gaussianElimination(int mat_size, int i, double[][] mat) { int step = 0; for (step = 0; step < mat_size - 1; step++) { for (i = step; i < mat_size - 1; i++) { @@ -46,11 +39,7 @@ public static double[][] gaussianElimination( } // calculate the x_1, x_2,... values of the gaussian and save it in an arraylist. - public static ArrayList<Double> valueOfGaussian( - int mat_size, - double[][] x, - double[][] mat - ) { + public static ArrayList<Double> valueOfGaussian(int mat_size, double[][] x, double[][] mat) { ArrayList<Double> answerArray = new ArrayList<Double>(); int i, j; diff --git a/src/main/java/com/thealgorithms/maths/GenericRoot.java b/src/main/java/com/thealgorithms/maths/GenericRoot.java index 04e07d14432e..1058da9e72c8 100644 --- a/src/main/java/com/thealgorithms/maths/GenericRoot.java +++ b/src/main/java/com/thealgorithms/maths/GenericRoot.java @@ -1,7 +1,8 @@ package com.thealgorithms.maths; /* - * Algorithm explanation: https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. + * Algorithm explanation: + * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015. */ public class GenericRoot { diff --git a/src/main/java/com/thealgorithms/maths/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java index b30ada488609..854e4d555b40 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -12,8 +12,7 @@ public class HarshadNumber { * {@code false} */ public static boolean isHarshad(long n) { - if (n <= 0) - return false; + if (n <= 0) return false; long t = n; int sumOfDigits = 0; @@ -34,8 +33,7 @@ public static boolean isHarshad(long n) { */ public static boolean isHarshad(String s) { long n = Long.valueOf(s); - if (n <= 0) - return false; + if (n <= 0) return false; int sumOfDigits = 0; for (char ch : s.toCharArray()) { diff --git a/src/main/java/com/thealgorithms/maths/JosephusProblem.java b/src/main/java/com/thealgorithms/maths/JosephusProblem.java index 1e223f0fa860..b878eff2b291 100644 --- a/src/main/java/com/thealgorithms/maths/JosephusProblem.java +++ b/src/main/java/com/thealgorithms/maths/JosephusProblem.java @@ -1,15 +1,21 @@ package com.thealgorithms.maths; -/** There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. +/** + * There are n friends that are playing a game. The friends are sitting in a circle and are + * numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend + * brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings + * you to the 1st friend. */ -/** The rules of the game are as follows: +/** + The rules of the game are as follows: 1.Start at the 1st friend. - 2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. - 3.The last friend you counted leaves the circle and loses the game. - 4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. - 5.Else, the last friend in the circle wins the game. + 2.Count the next k friends in the clockwise direction including the friend you started at. + The counting wraps around the circle and may count some friends more than once. 3.The last friend + you counted leaves the circle and loses the game. 4.If there is still more than one friend in the + circle, go back to step 2 starting from the friend immediately clockwise of the friend who just + lost and repeat. 5.Else, the last friend in the circle wins the game. @author Kunal */ diff --git a/src/main/java/com/thealgorithms/maths/JugglerSequence.java b/src/main/java/com/thealgorithms/maths/JugglerSequence.java index da18dd647479..216098fc926f 100644 --- a/src/main/java/com/thealgorithms/maths/JugglerSequence.java +++ b/src/main/java/com/thealgorithms/maths/JugglerSequence.java @@ -35,10 +35,7 @@ public static void jugglerSequence(int inputNumber) { if (n % 2 == 0) { temp = (int) Math.floor(Math.sqrt(n)); } else { - temp = - (int) Math.floor( - Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n) - ); + temp = (int) Math.floor(Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)); } n = temp; seq.add(n + ""); diff --git a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index a932dc774206..2db05939413d 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -6,12 +6,12 @@ public class KaprekarNumbers { /* This program demonstrates if a given number is Kaprekar Number or not. - Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into two parts where the right part has n - digits and sum of these parts is equal to the original number. */ + Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into + two parts where the right part has n digits and sum of these parts is equal to the original + number. */ // Provides a list of kaprekarNumber in a range - public static List<Long> kaprekarNumberInRange(long start, long end) - throws Exception { + public static List<Long> kaprekarNumberInRange(long start, long end) throws Exception { long n = end - start; if (n < 0) throw new Exception("Invalid range"); ArrayList<Long> list = new ArrayList<>(); @@ -34,32 +34,13 @@ public static boolean isKaprekarNumber(long num) { 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/KeithNumber.java b/src/main/java/com/thealgorithms/maths/KeithNumber.java index a96638b0febb..0ea68d50f7f3 100644 --- a/src/main/java/com/thealgorithms/maths/KeithNumber.java +++ b/src/main/java/com/thealgorithms/maths/KeithNumber.java @@ -4,42 +4,43 @@ class KeithNumber { - //user-defined function that checks if the given number is Keith or not + // user-defined function that checks if the given number is Keith or not static boolean isKeith(int x) { - //List stores all the digits of the X + // List stores all the digits of the X ArrayList<Integer> terms = new ArrayList<Integer>(); - //n denotes the number of digits + // n denotes the number of digits int temp = x, n = 0; - //executes until the condition becomes false + // executes until the condition becomes false while (temp > 0) { - //determines the last digit of the number and add it to the List + // determines the last digit of the number and add it to the List terms.add(temp % 10); - //removes the last digit + // removes the last digit temp = temp / 10; - //increments the number of digits (n) by 1 + // increments the number of digits (n) by 1 n++; } - //reverse the List + // reverse the List Collections.reverse(terms); int next_term = 0, i = n; - //finds next term for the series - //loop executes until the condition returns true + // finds next term for the series + // loop executes until the condition returns true while (next_term < x) { next_term = 0; - //next term is the sum of previous n terms (it depends on number of digits the number has) + // next term is the sum of previous n terms (it depends on number of digits the number + // has) for (int j = 1; j <= n; j++) { next_term = next_term + terms.get(i - j); } terms.add(next_term); i++; } - //when the control comes out of the while loop, there will be two conditions: - //either next_term will be equal to x or greater than x - //if equal, the given number is Keith, else not + // when the control comes out of the while loop, there will be two conditions: + // either next_term will be equal to x or greater than x + // if equal, the given number is Keith, else not return (next_term == x); } - //driver code + // driver code public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); diff --git a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java index 57972cf85b6a..eacc75c23058 100644 --- a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java +++ b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java @@ -1,52 +1,48 @@ package com.thealgorithms.maths; /* This is a program to check if a number is a Krishnamurthy number or not. -A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal to the number itself. -For example, 1, 2 and 145 are Krishnamurthy numbers. -Krishnamurthy number is also referred to as a Strong number. +A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal +to the number itself. For example, 1, 2 and 145 are Krishnamurthy numbers. Krishnamurthy number is +also referred to as a Strong number. */ import java.io.*; public class KrishnamurthyNumber { - //returns True if the number is a Krishnamurthy number and False if it is not. + // returns True if the number is a Krishnamurthy number and False if it is not. public static boolean isKMurthy(int n) { - //initialising the variable s that will store the sum of the factorials of the digits to 0 + // initialising the variable s that will store the sum of the factorials of the digits to 0 int s = 0; - //storing the number n in a temporary variable tmp + // storing the number n in a temporary variable tmp int tmp = n; - //Krishnamurthy numbers are positive + // Krishnamurthy numbers are positive if (n <= 0) { return false; - } //checking if the number is a Krishnamurthy number + } // checking if the number is a Krishnamurthy number else { while (n != 0) { - //initialising the variable fact that will store the factorials of the digits + // initialising the variable fact that will store the factorials of the digits int fact = 1; - //computing factorial of each digit + // computing factorial of each digit for (int i = 1; i <= n % 10; i++) { fact = fact * i; } - //computing the sum of the factorials + // computing the sum of the factorials s = s + fact; - //discarding the digit for which factorial has been calculated + // discarding the digit for which factorial has been calculated n = n / 10; } - //evaluating if sum of the factorials of the digits equals the number itself + // evaluating if sum of the factorials of the digits equals the number itself return tmp == s; } } public static void main(String[] args) throws IOException { - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in) - ); - System.out.println( - "Enter a number to check if it is a Krishnamurthy number: " - ); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter a number to check if it is a Krishnamurthy number: "); int n = Integer.parseInt(br.readLine()); if (isKMurthy(n)) { System.out.println(n + " is a Krishnamurthy number."); diff --git a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java index 6d3657469a62..5c904c2d72f4 100644 --- a/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java +++ b/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java @@ -20,9 +20,7 @@ public static void main(String[] args) { int num1 = input.nextInt(); System.out.println("Please enter second number >> "); int num2 = input.nextInt(); - System.out.println( - "The least common multiple of two numbers is >> " + lcm(num1, num2) - ); + System.out.println("The least common multiple of two numbers is >> " + lcm(num1, num2)); } /* diff --git a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java index 7b9620a46ccb..1ca5c8bd0fa6 100644 --- a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java +++ b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java @@ -1,8 +1,8 @@ package com.thealgorithms.maths; - /** - * https://en.wikipedia.org/wiki/Leonardo_number - */ +/** + * https://en.wikipedia.org/wiki/Leonardo_number + */ public class LeonardoNumber { /** diff --git a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java index d6788ea1f72e..54cda1555a6c 100644 --- a/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java +++ b/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java @@ -28,38 +28,26 @@ public static Solution findAnySolution(final Equation equation) { } private static GcdSolutionWrapper gcd( - final int a, - final int b, - final GcdSolutionWrapper previous - ) { + final int a, final int b, final GcdSolutionWrapper previous) { if (b == 0) { return new GcdSolutionWrapper(a, new Solution(1, 0)); } // stub wrapper becomes the `previous` of the next recursive call final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0)); - final var next = /* recursive call */gcd(b, a % b, stubWrapper); + final var next = /* recursive call */ gcd(b, a % b, stubWrapper); previous.getSolution().setX(next.getSolution().getY()); - previous - .getSolution() - .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; @@ -103,11 +91,14 @@ public int hashCode() { @Override public String toString() { - return "Solution[" + "x=" + x + ", " + "y=" + y + ']'; + return "Solution[" + + "x=" + x + ", " + + "y=" + y + ']'; } } - public record Equation(int a, int b, int c) {} + public record Equation(int a, int b, int c) { + } public static final class GcdSolutionWrapper { @@ -128,10 +119,7 @@ public boolean equals(Object obj) { return false; } var that = (GcdSolutionWrapper) obj; - return ( - this.gcd == that.gcd && - Objects.equals(this.solution, that.solution) - ); + return (this.gcd == that.gcd && Objects.equals(this.solution, that.solution)); } public int getGcd() { @@ -157,15 +145,9 @@ public int hashCode() { @Override public String toString() { - return ( - "GcdSolutionWrapper[" + - "gcd=" + - gcd + - ", " + - "solution=" + - solution + - ']' - ); + return ("GcdSolutionWrapper[" + + "gcd=" + gcd + ", " + + "solution=" + solution + ']'); } } } diff --git a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java index c8e753e4e937..89acbf6a14e7 100644 --- a/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java +++ b/src/main/java/com/thealgorithms/maths/LiouvilleLambdaFunction.java @@ -24,13 +24,11 @@ public class LiouvilleLambdaFunction { */ static int liouvilleLambda(int number) { if (number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException( - "Number must be greater than zero." - ); + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); } - //return 1 if size of prime factor list is even, -1 otherwise + // return 1 if size of prime factor list is even, -1 otherwise return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1; } } diff --git a/src/main/java/com/thealgorithms/maths/LongDivision.java b/src/main/java/com/thealgorithms/maths/LongDivision.java index 2578fe2e8814..b1c7b1901701 100644 --- a/src/main/java/com/thealgorithms/maths/LongDivision.java +++ b/src/main/java/com/thealgorithms/maths/LongDivision.java @@ -1,17 +1,19 @@ -// Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. +// Given two integers dividend and divisor, divide two integers without using multiplication, +// division, and mod operator. // -// The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, -// and -2.7335 would be truncated to -2. -// My method used Long Division, here is the source "https://en.wikipedia.org/wiki/Long_division" +// The integer division should truncate toward zero, which means losing its fractional part. +// For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. My +// method used Long Division, here is the source +// "https://en.wikipedia.org/wiki/Long_division" package com.thealgorithms.maths; public class LongDivision { -public static int divide(int dividend, int divisor) { + public static int divide(int dividend, int divisor) { long new_dividend_1 = dividend; long new_divisor_1 = divisor; - if(divisor == 0){ + if (divisor == 0) { return 0; } if (dividend < 0) { @@ -32,7 +34,6 @@ public static int divide(int dividend, int divisor) { String remainder = ""; - for (int i = 0; i < dividend_string.length(); i++) { String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1); long part_1 = Long.parseLong(part_v1); @@ -57,7 +58,7 @@ public static int divide(int dividend, int divisor) { } if (!(part_1 == 0)) { remainder = String.valueOf(part_1); - }else{ + } else { remainder = ""; } @@ -76,6 +77,5 @@ public static int divide(int dividend, int divisor) { } catch (NumberFormatException e) { return 2147483647; } - } } diff --git a/src/main/java/com/thealgorithms/maths/LucasSeries.java b/src/main/java/com/thealgorithms/maths/LucasSeries.java index 59c9a9f3f2e4..ebeb2715fe2d 100644 --- a/src/main/java/com/thealgorithms/maths/LucasSeries.java +++ b/src/main/java/com/thealgorithms/maths/LucasSeries.java @@ -13,9 +13,7 @@ public class LucasSeries { * @return nth number of Lucas Series */ public static int lucasSeries(int n) { - return n == 1 - ? 2 - : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); + return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2); } /** diff --git a/src/main/java/com/thealgorithms/maths/MagicSquare.java b/src/main/java/com/thealgorithms/maths/MagicSquare.java index 1f9683059575..e48efabe45fd 100644 --- a/src/main/java/com/thealgorithms/maths/MagicSquare.java +++ b/src/main/java/com/thealgorithms/maths/MagicSquare.java @@ -2,8 +2,9 @@ import java.util.*; -/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all -rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/ +/*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n +numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square +contains the integers from 1 to n^2.*/ public class MagicSquare { public static void main(String[] args) { @@ -22,10 +23,7 @@ public static void main(String[] args) { magic_square[row_num][col_num] = 1; for (int i = 2; i <= num * num; i++) { - if ( - magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == - 0 - ) { + if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) { row_num = (row_num - 1 + num) % num; col_num = (col_num + 1) % num; } else { diff --git a/src/main/java/com/thealgorithms/maths/MatrixUtil.java b/src/main/java/com/thealgorithms/maths/MatrixUtil.java index 4f5e048a6244..6fc5252f9d71 100644 --- a/src/main/java/com/thealgorithms/maths/MatrixUtil.java +++ b/src/main/java/com/thealgorithms/maths/MatrixUtil.java @@ -18,33 +18,18 @@ public static boolean isValid(final BigDecimal[][] matrix) { } 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 - ); + 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 boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { + return (isValid(matrix1) && isValid(matrix2) && matrix1[0].length == matrix2.length); } - public static Optional<BigDecimal[][]> operate( - final BigDecimal[][] matrix1, + public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2, - final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation - ) { + final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) { if (!hasEqualSizes(matrix1, matrix2)) { return Optional.empty(); } @@ -54,43 +39,29 @@ public static Optional<BigDecimal[][]> operate( 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]; - - result[rowIndex][columnIndex] = - operation.apply(value1, value2); - }) - ); + 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); + })); return Optional.of(result); } public static Optional<BigDecimal[][]> add( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::add); } public static Optional<BigDecimal[][]> subtract( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { return operate(matrix1, matrix2, BigDecimal::subtract); } public static Optional<BigDecimal[][]> multiply( - final BigDecimal[][] matrix1, - final BigDecimal[][] matrix2 - ) { + final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) { if (!canMultiply(matrix1, matrix2)) { return Optional.empty(); } @@ -102,65 +73,49 @@ public static Optional<BigDecimal[][]> multiply( final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize]; - IntStream - .range(0, matrix1RowSize) - .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]; - - return value1.multiply(value2); - }) - .reduce(BigDecimal.ZERO, BigDecimal::add) - ) - ); + IntStream.range(0, matrix1RowSize) + .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]; + + return value1.multiply(value2); + }) + .reduce(BigDecimal.ZERO, BigDecimal::add))); return Optional.of(result); } - public static void assertThat( - final BigDecimal[][] actual, - final BigDecimal[][] expected - ) { + public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) { if (!Objects.deepEquals(actual, expected)) { - 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))); } } public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - { new BigDecimal(3), new BigDecimal(2) }, - { new BigDecimal(0), new BigDecimal(1) }, + {new BigDecimal(3), new BigDecimal(2)}, + {new BigDecimal(0), new BigDecimal(1)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(1), new BigDecimal(3) }, - { new BigDecimal(2), new BigDecimal(0) }, + {new BigDecimal(1), new BigDecimal(3)}, + {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) }, - { new BigDecimal(2), new BigDecimal(1) }, + {new BigDecimal(4), new BigDecimal(5)}, + {new BigDecimal(2), new BigDecimal(1)}, }; assertThat(actual, expected); @@ -168,23 +123,22 @@ public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - { new BigDecimal(1), new BigDecimal(4) }, - { new BigDecimal(5), new BigDecimal(6) }, + {new BigDecimal(1), new BigDecimal(4)}, + {new BigDecimal(5), new BigDecimal(6)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(2), new BigDecimal(0) }, - { new BigDecimal(-2), new BigDecimal(-3) }, + {new BigDecimal(2), new BigDecimal(0)}, + {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) }, - { new BigDecimal(7), new BigDecimal(9) }, + {new BigDecimal(-1), new BigDecimal(4)}, + {new BigDecimal(7), new BigDecimal(9)}, }; assertThat(actual, expected); @@ -192,26 +146,25 @@ public static void main(final String[] args) { { final BigDecimal[][] matrix1 = { - { new BigDecimal(1), new BigDecimal(2), new BigDecimal(3) }, - { new BigDecimal(4), new BigDecimal(5), new BigDecimal(6) }, - { new BigDecimal(7), new BigDecimal(8), new BigDecimal(9) }, + {new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)}, + {new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)}, + {new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}, }; final BigDecimal[][] matrix2 = { - { new BigDecimal(1), new BigDecimal(2) }, - { new BigDecimal(3), new BigDecimal(4) }, - { new BigDecimal(5), new BigDecimal(6) }, + {new BigDecimal(1), new BigDecimal(2)}, + {new BigDecimal(3), new BigDecimal(4)}, + {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) }, - { new BigDecimal(49), new BigDecimal(64) }, - { new BigDecimal(76), new BigDecimal(100) }, + {new BigDecimal(22), new BigDecimal(28)}, + {new BigDecimal(49), new BigDecimal(64)}, + {new BigDecimal(76), new BigDecimal(100)}, }; assertThat(actual, expected); diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java index 44f94ad6bb9c..994b9b0c9349 100644 --- a/src/main/java/com/thealgorithms/maths/Median.java +++ b/src/main/java/com/thealgorithms/maths/Median.java @@ -15,8 +15,7 @@ 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/MobiusFunction.java b/src/main/java/com/thealgorithms/maths/MobiusFunction.java index 5ed83c7c5833..e9ead992d7a7 100644 --- a/src/main/java/com/thealgorithms/maths/MobiusFunction.java +++ b/src/main/java/com/thealgorithms/maths/MobiusFunction.java @@ -25,29 +25,27 @@ public class MobiusFunction { */ static int mobius(int number) { if (number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException( - "Number must be greater than zero." - ); + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); } if (number == 1) { - //return 1 if number passed is less or is 1 + // return 1 if number passed is less or is 1 return 1; } int primeFactorCount = 0; for (int i = 1; i <= number; i++) { - //find prime factors of number + // find prime factors of number if (number % i == 0 && PrimeCheck.isPrime(i)) { - //check if number is divisible by square of prime factor + // check if number is divisible by square of prime factor if (number % (i * i) == 0) { - //if number is divisible by square of prime factor + // if number is divisible by square of prime factor return 0; } - /*increment primeFactorCount by 1 - if number is not divisible by square of found prime factor*/ + /*increment primeFactorCount by 1 + if number is not divisible by square of found prime factor*/ primeFactorCount++; } } diff --git a/src/main/java/com/thealgorithms/maths/Mode.java b/src/main/java/com/thealgorithms/maths/Mode.java index f90f70626ef5..7333380b0a69 100644 --- a/src/main/java/com/thealgorithms/maths/Mode.java +++ b/src/main/java/com/thealgorithms/maths/Mode.java @@ -16,19 +16,10 @@ public class Mode { public static void main(String[] args) { /* Test array of integers */ assert (mode(new int[] {})) == null; - assert Arrays.equals(mode(new int[] { 5 }), new int[] { 5 }); - assert Arrays.equals( - mode(new int[] { 1, 2, 3, 4, 5 }), - new int[] { 1, 2, 3, 4, 5 } - ); - assert Arrays.equals( - mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 8 }), - new int[] { 7 } - ); - assert Arrays.equals( - mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 9 }), - new int[] { 7, 9 } - ); + assert Arrays.equals(mode(new int[] {5}), new int[] {5}); + assert Arrays.equals(mode(new int[] {1, 2, 3, 4, 5}), new int[] {1, 2, 3, 4, 5}); + assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[] {7}); + assert Arrays.equals(mode(new int[] {7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[] {7, 9}); } /* diff --git a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java index e224c80fff76..e2847bcc0625 100644 --- a/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java +++ b/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java @@ -4,8 +4,8 @@ /* * Find the 2 elements which are non repeating in an array - * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not on - * actual numbers. + * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not + * on actual numbers. */ public class NonRepeatingElement { @@ -15,17 +15,14 @@ public static void main(String[] args) { System.out.println("Enter the number of elements in the array"); int n = sc.nextInt(); if ((n & 1) == 1) { - //Not allowing odd number of elements as we are expecting 2 non repeating numbers + // Not allowing odd number of elements as we are expecting 2 non repeating numbers System.out.println("Array should contain even number of elements"); return; } int[] arr = new int[n]; System.out.println( - "Enter " + - n + - " elements in the array. NOTE: Only 2 elements should not repeat" - ); + "Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat"); for (i = 0; i < n; i++) { arr[i] = sc.nextInt(); } @@ -36,40 +33,38 @@ public static void main(String[] args) { System.out.println("Unable to close scanner" + e); } - //Find XOR of the 2 non repeating elements + // Find XOR of the 2 non repeating elements for (i = 0; i < n; i++) { res ^= arr[i]; } - //Finding the rightmost set bit + // Finding the rightmost set bit res = res & (-res); int num1 = 0, num2 = 0; for (i = 0; i < n; i++) { - if ((res & arr[i]) > 0) { //Case 1 explained below + if ((res & arr[i]) > 0) { // Case 1 explained below num1 ^= arr[i]; } else { - num2 ^= arr[i]; //Case 2 explained below + num2 ^= arr[i]; // Case 2 explained below } } - System.out.println( - "The two non repeating elements are " + num1 + " and " + num2 - ); + System.out.println("The two non repeating elements are " + num1 + " and " + num2); } - /* + /* Explanation of the code: let us assume we have an array [1,2,1,2,3,4] - Property of XOR: num ^ num = 0. - If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 and 2 ^ 2 would give 0. - Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. - We need to find two's complement of 7 and find the rightmost set bit. i.e. (num & (-num)) - Two's complement of 7 is 001 and hence res = 1. - There can be 2 options when we Bitise AND this res with all the elements in our array + Property of XOR: num ^ num = 0. + If we XOR all the elemnets of the array we will be left with 3 ^ 4 as 1 ^ 1 and 2 ^ 2 would give + 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. We need to find two's + complement of 7 and find the rightmost set bit. i.e. (num & (-num)) Two's complement of 7 is 001 + and hence res = 1. There can be 2 options when we Bitise AND this res with all the elements in our + array 1. Result will come non zero number 2. Result will be 0. In the first case we will XOR our element with the first number (which is initially 0) In the second case we will XOR our element with the second number(which is initially 0) - This is how we will get non repeating elements with the help of bitwise operators. + This is how we will get non repeating elements with the help of bitwise operators. */ } diff --git a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java index 6daeb2673cd7..d19b80ab8d4c 100644 --- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java +++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java @@ -1,10 +1,9 @@ package com.thealgorithms.maths; -import java.util.HashMap; +import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Arrays; -import java.lang.IllegalArgumentException; - +import java.util.HashMap; /** * @brief class computing the n-th ugly number (when they are sorted) diff --git a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java index 7c5c540b7ae6..665d8ef5a98c 100644 --- a/src/main/java/com/thealgorithms/maths/NumberOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/NumberOfDigits.java @@ -47,9 +47,7 @@ private static int numberOfDigits(int number) { * @return number of digits of given number */ private static int numberOfDigitsFast(int number) { - return number == 0 - ? 1 - : (int) Math.floor(Math.log10(Math.abs(number)) + 1); + return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); } /** diff --git a/src/main/java/com/thealgorithms/maths/ParseInteger.java b/src/main/java/com/thealgorithms/maths/ParseInteger.java index e2e9e52ac14c..d0cf89b949b7 100644 --- a/src/main/java/com/thealgorithms/maths/ParseInteger.java +++ b/src/main/java/com/thealgorithms/maths/ParseInteger.java @@ -24,11 +24,7 @@ public static int parseInt(String s) { boolean isNegative = s.charAt(0) == '-'; boolean isPositive = s.charAt(0) == '+'; int number = 0; - for ( - int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); - i < length; - ++i - ) { + for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) { if (!Character.isDigit(s.charAt(i))) { throw new NumberFormatException("s=" + s); } diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index fb7468f242aa..beb9a1e4937e 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -3,18 +3,19 @@ public class PascalTriangle { /** - *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that arises - * in probability theory, combinatorics, and algebra. In much of the Western world, it is named after - * the French mathematician Blaise Pascal, although other mathematicians studied it centuries before - * him in India, Persia, China, Germany, and Italy. + *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that + *arises in probability theory, combinatorics, and algebra. In much of the Western world, it is + *named after the French mathematician Blaise Pascal, although other mathematicians studied it + *centuries before him in India, Persia, China, Germany, and Italy. * - * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top (the 0th row). - * The entries in each row are numbered from the left beginning with k=0 and are usually staggered relative - * to the numbers in the adjacent rows. The triangle may be constructed in the following manner: - * In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is - * constructed by adding the number above and to the left with the number above and to the right, treating - * blank entries as 0. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), - * whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row. * + * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top + *(the 0th row). The entries in each row are numbered from the left beginning with k=0 and are + *usually staggered relative to the numbers in the adjacent rows. The triangle may be + *constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero + *entry 1. Each entry of each subsequent row is constructed by adding the number above and to + *the left with the number above and to the right, treating blank entries as 0. For example, the + *initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers + *1 and 3 in the third row are added to produce the number 4 in the fourth row. * * *<p> * link:-https://en.wikipedia.org/wiki/Pascal%27s_triangle @@ -51,7 +52,8 @@ public static int[][] pascal(int n) { // First and last values in every row are 1 if (line == i || i == 0) arr[line][i] = 1; // The rest elements are sum of values just above and left of above - else arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; + else + arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; } } diff --git a/src/main/java/com/thealgorithms/maths/PerfectCube.java b/src/main/java/com/thealgorithms/maths/PerfectCube.java index 0fae7889ce94..f9ed0558b8d5 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectCube.java +++ b/src/main/java/com/thealgorithms/maths/PerfectCube.java @@ -17,7 +17,7 @@ public static boolean isPerfectCube(int number) { int a = (int) Math.pow(number, 1.0 / 3); return a * a * a == number; } - + /** * Check if a number is perfect cube or not by using Math.cbrt function * diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java index 896b8cef8d21..7d6a045166e5 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -17,8 +17,7 @@ public class PerfectNumber { * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber(int number) { - if (number <= 0) - return false; + if (number <= 0) return false; int sum = 0; /* sum of its positive divisors */ for (int i = 1; i < number; ++i) { @@ -28,7 +27,7 @@ public static boolean isPerfectNumber(int number) { } return sum == number; } - + /** * Check if {@code n} is perfect number or not * @@ -36,11 +35,10 @@ public static boolean isPerfectNumber(int number) { * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber2(int n) { - if (n <= 0) - return false; + if (n <= 0) return false; int sum = 1; double root = Math.sqrt(n); - + /* * We can get the factors after the root by dividing number by its factors * before the root. @@ -55,10 +53,10 @@ public static boolean isPerfectNumber2(int n) { sum += i + n / i; } } - - // if n is a perfect square then its root was added twice in above loop, so subtracting root from sum - if (root == (int) root) - sum -= root; + + // if n is a perfect square then its root was added twice in above loop, so subtracting root + // from sum + if (root == (int) root) sum -= root; return sum == n; } diff --git a/src/main/java/com/thealgorithms/maths/Perimeter.java b/src/main/java/com/thealgorithms/maths/Perimeter.java index a941de198eac..15d032b058a1 100644 --- a/src/main/java/com/thealgorithms/maths/Perimeter.java +++ b/src/main/java/com/thealgorithms/maths/Perimeter.java @@ -5,8 +5,9 @@ public class Perimeter { /** * Calculate the Perimeter of regular polygon (equals sides) - * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular Hexagon. - * + * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular + * Hexagon. + * * @param n for number of sides. * @param side for length of each side. * @return Perimeter of given polygon @@ -17,15 +18,17 @@ public static float perimeterRegularPolygon(int n, float side) { /** * Calculate the Perimeter of irregular polygon (unequals sides) - * Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular Pentagon, irregular Hexagon. - * + * Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular + * Pentagon, irregular Hexagon. + * * @param side1 for length of side 1 * @param side2 for length of side 2 * @param side3 for length of side 3 * @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; @@ -35,7 +38,7 @@ public static float perimeterIrregularPolygon(float side1, float side2, float si /** * Calculate the Perimeter of rectangle - * + * * @param length for length of rectangle * @param breadth for breadth of rectangle * @return Perimeter of given rectangle @@ -46,7 +49,7 @@ public static float perimeterRectangle(float length, float breadth) { /** * Calculate the Perimeter or Circumference of circle. - * + * * @param r for radius of circle. * @return circumference of given circle. */ diff --git a/src/main/java/com/thealgorithms/maths/PiNilakantha.java b/src/main/java/com/thealgorithms/maths/PiNilakantha.java index c60b3b5b634a..d00240317997 100644 --- a/src/main/java/com/thealgorithms/maths/PiNilakantha.java +++ b/src/main/java/com/thealgorithms/maths/PiNilakantha.java @@ -22,9 +22,7 @@ public static void main(String[] args) { */ public static double calculatePi(int iterations) { if (iterations < 0 || iterations > 500) { - throw new IllegalArgumentException( - "Please input Integer Number between 0 and 500" - ); + throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); } double pi = 3; @@ -32,15 +30,9 @@ public static double calculatePi(int iterations) { for (int i = 0; i < iterations; i++) { if (i % 2 == 0) { - pi = - pi + - 4.0 / - (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } else { - pi = - pi - - 4.0 / - (divCounter * (divCounter + 1) * (divCounter + 2)); + pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } divCounter += 2; diff --git a/src/main/java/com/thealgorithms/maths/PollardRho.java b/src/main/java/com/thealgorithms/maths/PollardRho.java index 59852c5adea5..8ce62336061e 100644 --- a/src/main/java/com/thealgorithms/maths/PollardRho.java +++ b/src/main/java/com/thealgorithms/maths/PollardRho.java @@ -3,12 +3,12 @@ /* * Java program for pollard rho algorithm * The algorithm is used to factorize a number n = pq, - * where p is a non-trivial factor. + * where p is a non-trivial factor. * Pollard's rho algorithm is an algorithm for integer factorization - * and it takes as its inputs n, the integer to be factored; + * and it takes as its inputs n, the integer to be factored; * and g(x), a polynomial in x computed modulo n. * In the original algorithm, g(x) = ((x ^ 2) − 1) mod n, - * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. + * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. * The output is either a non-trivial factor of n, or failure. * It performs the following steps: * x ← 2 @@ -20,19 +20,20 @@ * y ← g(g(y)) * d ← gcd(|x - y|, n) - * if d = n: + * if d = n: * return failure * else: * return d - * Here x and y corresponds to xi and xj in the previous section. + * Here x and y corresponds to xi and xj in the previous section. * Note that this algorithm may fail to find a nontrivial factor even when n is composite. - * In that case, the method can be tried again, using a starting value other than 2 or a different g(x) - * + * In that case, the method can be tried again, using a starting value other than 2 or a different + g(x) + * * Wikipedia: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class PollardRho { @@ -40,7 +41,8 @@ public class PollardRho { * This method returns a polynomial in x computed modulo n * * @param base Integer base of the polynomial - * @param modulus Integer is value which is to be used to perform modulo operation over the polynomial + * @param modulus Integer is value which is to be used to perform modulo operation over the + * polynomial * @return Integer (((base * base) - 1) % modulus) */ static int g(int base, int modulus) { @@ -57,13 +59,13 @@ static int g(int base, int modulus) { static int pollardRho(int number) { int x = 2, y = 2, d = 1; while (d == 1) { - //tortoise move + // tortoise move x = g(x, number); - //hare move + // hare move y = g(g(y, number), number); - //check GCD of |x-y| and number + // check GCD of |x-y| and number d = GCD.gcd(Math.abs(x - y), number); } if (d == number) { diff --git a/src/main/java/com/thealgorithms/maths/PrimeCheck.java b/src/main/java/com/thealgorithms/maths/PrimeCheck.java index 5eb757acf598..2c9714f1335b 100644 --- a/src/main/java/com/thealgorithms/maths/PrimeCheck.java +++ b/src/main/java/com/thealgorithms/maths/PrimeCheck.java @@ -12,17 +12,13 @@ public static void main(String[] args) { if (isPrime(n)) { System.out.println("algo1 verify that " + n + " is a prime number"); } else { - System.out.println( - "algo1 verify that " + n + " is not a prime number" - ); + System.out.println("algo1 verify that " + n + " is not a prime number"); } if (fermatPrimeChecking(n, 20)) { System.out.println("algo2 verify that " + n + " is a prime number"); } else { - System.out.println( - "algo2 verify that " + n + " is not a prime number" - ); + System.out.println("algo2 verify that " + n + " is not a prime number"); } scanner.close(); } diff --git a/src/main/java/com/thealgorithms/maths/PronicNumber.java b/src/main/java/com/thealgorithms/maths/PronicNumber.java index 15fae23a5b23..312af21ea2ba 100644 --- a/src/main/java/com/thealgorithms/maths/PronicNumber.java +++ b/src/main/java/com/thealgorithms/maths/PronicNumber.java @@ -19,16 +19,17 @@ public class PronicNumber { * @return true if input number is a pronic number, false otherwise */ static boolean isPronic(int input_number) { - //Iterating from 0 to input_number + // Iterating from 0 to input_number for (int i = 0; i <= input_number; i++) { - //Checking if product of i and (i+1) is equals input_number + // Checking if product of i and (i+1) is equals input_number if (i * (i + 1) == input_number && i != input_number) { - //return true if product of i and (i+1) is equals input_number + // return true if product of i and (i+1) is equals input_number return true; } } - //return false if product of i and (i+1) for all values from 0 to input_number is not equals input_number + // return false if product of i and (i+1) for all values from 0 to input_number is not + // equals input_number return false; } } diff --git a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java index ead630a7955e..f14415c35e61 100644 --- a/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java +++ b/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java @@ -12,7 +12,7 @@ public class RomanNumeralUtil { private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 5999; - //1000-5999 + // 1000-5999 private static final String[] RN_M = { "", "M", @@ -21,7 +21,7 @@ public class RomanNumeralUtil { "MMMM", "MMMMM", }; - //100-900 + // 100-900 private static final String[] RN_C = { "", "C", @@ -34,7 +34,7 @@ public class RomanNumeralUtil { "DCCC", "CM", }; - //10-90 + // 10-90 private static final String[] RN_X = { "", "X", @@ -47,7 +47,7 @@ public class RomanNumeralUtil { "LXXX", "XC", }; - //1-9 + // 1-9 private static final String[] RN_I = { "", "I", @@ -64,19 +64,10 @@ 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 - ) - ); + 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/SimpsonIntegration.java b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java index d9efb5e976e6..ef02c5759c03 100644 --- a/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java +++ b/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java @@ -7,9 +7,9 @@ public class SimpsonIntegration { /* * Calculate definite integrals by using Composite Simpson's rule. * Wiki: https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule - * Given f a function and an even number N of intervals that divide the integration interval e.g. [a, b], - * we calculate the step h = (b-a)/N and create a table that contains all the x points of - * the real axis xi = x0 + i*h and the value f(xi) that corresponds to these xi. + * Given f a function and an even number N of intervals that divide the integration interval + * e.g. [a, b], we calculate the step h = (b-a)/N and create a table that contains all the x + * points of the real axis xi = x0 + i*h and the value f(xi) that corresponds to these xi. * * To evaluate the integral i use the formula below: * I = h/3 * {f(x0) + 4*f(x1) + 2*f(x2) + 4*f(x3) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)} @@ -25,9 +25,7 @@ public static void main(String[] args) { // Check so that N is even if (N % 2 != 0) { - System.out.println( - "N must be even number for Simpsons method. Aborted" - ); + System.out.println("N must be even number for Simpsons method. Aborted"); System.exit(1); } diff --git a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java index b5f57a0db4a4..c988bb70808c 100644 --- a/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java +++ b/src/main/java/com/thealgorithms/maths/SquareFreeInteger.java @@ -1,7 +1,7 @@ package com.thealgorithms.maths; /* * Java program for Square free integer - * This class has a function which checks + * This class has a function which checks * if an integer has repeated prime factors * and will return false if the number has repeated prime factors. * true otherwise @@ -23,20 +23,21 @@ public class SquareFreeInteger { * true when number has non repeated prime factors * @throws IllegalArgumentException when number is negative or zero */ - public static boolean isSquareFreeInteger(int number) { - - if(number <= 0) { - //throw exception when number is less than or is zero - throw new IllegalArgumentException("Number must be greater than zero."); - } - - //Store prime factors of number which is passed as argument - //in a list - List<Integer> primeFactorsList = PrimeFactorization.pfactors(number); - - //Create set from list of prime factors of integer number - //if size of list and set is equal then the argument passed to this method is square free - //if size of list and set is not equal then the argument passed to this method is not square free - return primeFactorsList.size() == new HashSet<>(primeFactorsList).size(); - } + public static boolean isSquareFreeInteger(int number) { + + if (number <= 0) { + // throw exception when number is less than or is zero + throw new IllegalArgumentException("Number must be greater than zero."); + } + + // Store prime factors of number which is passed as argument + // in a list + List<Integer> primeFactorsList = PrimeFactorization.pfactors(number); + + // Create set from list of prime factors of integer number + // if size of list and set is equal then the argument passed to this method is square free + // if size of list and set is not equal then the argument passed to this method is not + // square free + return primeFactorsList.size() == new HashSet<>(primeFactorsList).size(); + } } diff --git a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java index 1cfe8b63af62..98a9ac0c4606 100644 --- a/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java +++ b/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java @@ -19,11 +19,13 @@ public class SquareRootWithNewtonRaphsonMethod { public static double squareRoot(int n) { - double x = n; //initially taking a guess that x = n. - double root = 0.5 * (x + n / x); //applying Newton-Raphson Method. + 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. - x = root; //decreasing the value of x to root, i.e. decreasing the guess. + 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/SumOfArithmeticSeries.java b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java index 688756d09373..69be4c3d4cab 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java +++ b/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java @@ -36,13 +36,7 @@ public static void main(String[] args) { * @param numOfTerms the total terms of an arithmetic series * @return sum of given arithmetic series */ - private static double sumOfSeries( - double firstTerm, - double commonDiff, - int numOfTerms - ) { - return ( - numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff) - ); + private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) { + return (numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff)); } } diff --git a/src/main/java/com/thealgorithms/maths/SumOfDigits.java b/src/main/java/com/thealgorithms/maths/SumOfDigits.java index 22d059d92ea6..6ffc20ac0f38 100644 --- a/src/main/java/com/thealgorithms/maths/SumOfDigits.java +++ b/src/main/java/com/thealgorithms/maths/SumOfDigits.java @@ -3,17 +3,13 @@ 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(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; } /** @@ -42,9 +38,7 @@ public static int sumOfDigits(int number) { public static int sumOfDigitsRecursion(int number) { number = number < 0 ? -number : number; /* calculate abs value */ - return number < 10 - ? number - : number % 10 + sumOfDigitsRecursion(number / 10); + return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10); } /** diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java index f45ac4d39686..8bc1afbe8771 100644 --- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java +++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java @@ -3,18 +3,18 @@ public class SumWithoutArithmeticOperators { /** - * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). - * All the integers associated are unsigned 32-bit integers - *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator - *@param a - It is the first number - *@param b - It is the second number - *@return returns an integer which is the sum of the first and second number - */ + * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). + * All the integers associated are unsigned 32-bit integers + *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator + *@param a - It is the first number + *@param b - It is the second number + *@return returns an integer which is the sum of the first and second number + */ - public int getSum(int a, int b){ - if(b==0) return a; - int sum = a^b; - int carry = (a&b)<<1; + public int getSum(int a, int b) { + if (b == 0) return a; + int sum = a ^ b; + int carry = (a & b) << 1; return getSum(sum, carry); } } diff --git a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java index 1c19bea9e630..5bae51d51ffd 100644 --- a/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java +++ b/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java @@ -19,10 +19,7 @@ public static int TrinomialValue(int n, int k) { } return ( - TrinomialValue(n - 1, k - 1) + - TrinomialValue(n - 1, k) + - TrinomialValue(n - 1, k + 1) - ); + TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1)); } public static void printTrinomial(int n) { diff --git a/src/main/java/com/thealgorithms/maths/TwinPrime.java b/src/main/java/com/thealgorithms/maths/TwinPrime.java index ba4310ac0b8c..867a1d23f220 100644 --- a/src/main/java/com/thealgorithms/maths/TwinPrime.java +++ b/src/main/java/com/thealgorithms/maths/TwinPrime.java @@ -1,32 +1,31 @@ package com.thealgorithms.maths; /* * Java program to find 'twin prime' of a prime number - * Twin Prime: Twin prime of a number n is (n+2) + * Twin Prime: Twin prime of a number n is (n+2) * if and only if n & (n+2) are prime. * Wikipedia: https://en.wikipedia.org/wiki/Twin_prime - * + * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) - * + * * */ public class TwinPrime { - - /** + + /** * This method returns twin prime of the integer value passed as argument * * @param input_number Integer value of which twin prime is to be found * @return (number + 2) if number and (number + 2) are prime, -1 otherwise */ - static int getTwinPrime(int inputNumber) { - - //if inputNumber and (inputNumber + 2) are both prime - //then return (inputNumber + 2) as a result - if(PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2) ) { - return inputNumber + 2; - } - //if any one from inputNumber and (inputNumber + 2) or if both of them are not prime - //then return -1 as a result - return -1; - } + static int getTwinPrime(int inputNumber) { + // if inputNumber and (inputNumber + 2) are both prime + // then return (inputNumber + 2) as a result + if (PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2)) { + return inputNumber + 2; + } + // if any one from inputNumber and (inputNumber + 2) or if both of them are not prime + // then return -1 as a result + return -1; + } } diff --git a/src/main/java/com/thealgorithms/maths/VampireNumber.java b/src/main/java/com/thealgorithms/maths/VampireNumber.java index fab745aae20a..d9aa4f203550 100644 --- a/src/main/java/com/thealgorithms/maths/VampireNumber.java +++ b/src/main/java/com/thealgorithms/maths/VampireNumber.java @@ -31,33 +31,17 @@ static void test(int startValue, int stopValue) { // System.out.println(i+ " "+ j); if (isVampireNumber(i, j, true)) { countofRes++; - res.append( - "" + - countofRes + - ": = ( " + - i + - "," + - j + - " = " + - i * - j + - ")" + - "\n" - ); + res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + + "\n"); } } } System.out.println(res); } - static boolean isVampireNumber( - int a, - int b, - boolean noPseudoVamireNumbers - ) { - // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for - // example - // 126 = 6 x 21 + static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) { + // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits + // for example 126 = 6 x 21 if (noPseudoVamireNumbers) { if (a * 10 <= b || b * 10 <= a) { return false; diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java index f9e903b9ff72..8a1bb1488eab 100644 --- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java +++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java @@ -45,7 +45,7 @@ public class VectorCrossProduct { int y; int z; - //Default constructor, initialises all three Direction Ratios to 0 + // Default constructor, initialises all three Direction Ratios to 0 VectorCrossProduct() { x = 0; y = 0; @@ -110,15 +110,15 @@ public static void main(String[] args) { } static void test() { - //Create two vectors + // Create two vectors VectorCrossProduct A = new VectorCrossProduct(1, -2, 3); VectorCrossProduct B = new VectorCrossProduct(2, 0, 3); - //Determine cross product + // Determine cross product VectorCrossProduct crossProd = A.crossProduct(B); crossProd.displayVector(); - //Determine dot product + // Determine dot product int dotProd = A.dotProduct(B); System.out.println("Dot Product of A and B: " + dotProd); } diff --git a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java index 7a370d0fc5b7..78487660fe8c 100644 --- a/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java +++ b/src/main/java/com/thealgorithms/matrixexponentiation/Fibonacci.java @@ -10,10 +10,10 @@ public class Fibonacci { // Exponentiation matrix for Fibonacci sequence - private static final int[][] fibMatrix = { { 1, 1 }, { 1, 0 } }; - private static final int[][] identityMatrix = { { 1, 0 }, { 0, 1 } }; - //First 2 fibonacci numbers - private static final int[][] baseFibNumbers = { { 1 }, { 0 } }; + private static final int[][] fibMatrix = {{1, 1}, {1, 0}}; + private static final int[][] identityMatrix = {{1, 0}, {0, 1}}; + // First 2 fibonacci numbers + private static final int[][] baseFibNumbers = {{1}, {0}}; /** * Performs multiplication of 2 matrices @@ -22,11 +22,8 @@ public class Fibonacci { * @param matrix2 * @return The product of matrix1 and matrix2 */ - private static int[][] matrixMultiplication( - int[][] matrix1, - int[][] matrix2 - ) { - //Check if matrices passed can be multiplied + private static int[][] matrixMultiplication(int[][] matrix1, int[][] matrix2) { + // Check if matrices passed can be multiplied int rowsInMatrix1 = matrix1.length; int columnsInMatrix1 = matrix1[0].length; @@ -38,14 +35,10 @@ private static int[][] matrixMultiplication( 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; } @@ -65,17 +58,11 @@ public static int[][] fib(int n) { return Fibonacci.identityMatrix; } else { int[][] cachedResult = fib(n / 2); - int[][] matrixExpResult = matrixMultiplication( - cachedResult, - cachedResult - ); + int[][] matrixExpResult = matrixMultiplication(cachedResult, cachedResult); if (n % 2 == 0) { return matrixExpResult; } else { - return matrixMultiplication( - Fibonacci.fibMatrix, - matrixExpResult - ); + return matrixMultiplication(Fibonacci.fibMatrix, matrixExpResult); } } } diff --git a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java index 495492ed225f..cfd4ccbdc170 100644 --- a/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java +++ b/src/main/java/com/thealgorithms/minimizinglateness/MinimizingLateness.java @@ -23,9 +23,8 @@ public Schedule(int t, int d) { 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(); @@ -38,13 +37,10 @@ public static void main(String[] args) throws IOException { int i = 0; while ((ch = in.readLine()) != null) { 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()) - ); + // 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())); 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 7db1f636c509..b0da6cba57e3 100644 --- a/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java +++ b/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java @@ -54,9 +54,7 @@ public double getRelativeLuminance(Color color) { */ public double getColor(int color8Bit) { final double sRgb = getColorSRgb(color8Bit); - return (sRgb <= 0.03928) - ? sRgb / 12.92 - : Math.pow((sRgb + 0.055) / 1.055, 2.4); + return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4); } /** @@ -83,38 +81,27 @@ private static void test() { final Color black = Color.BLACK; final double blackLuminance = algImpl.getRelativeLuminance(black); - assert blackLuminance == - 0 : "Test 1 Failed - Incorrect relative luminance."; + assert blackLuminance == 0 : "Test 1 Failed - Incorrect relative luminance."; final Color white = Color.WHITE; final double whiteLuminance = algImpl.getRelativeLuminance(white); - assert whiteLuminance == - 1 : "Test 2 Failed - Incorrect relative luminance."; + assert whiteLuminance == 1 : "Test 2 Failed - Incorrect relative luminance."; final double highestColorRatio = algImpl.getContrastRatio(black, white); - assert highestColorRatio == - 21 : "Test 3 Failed - Incorrect contrast ratio."; + assert highestColorRatio == 21 : "Test 3 Failed - Incorrect contrast ratio."; final Color foreground = new Color(23, 103, 154); - final double foregroundLuminance = algImpl.getRelativeLuminance( - foreground - ); - assert foregroundLuminance == - 0.12215748057375966 : "Test 4 Failed - Incorrect relative luminance."; + final double foregroundLuminance = algImpl.getRelativeLuminance(foreground); + 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."; - - final double contrastRatio = algImpl.getContrastRatio( - foreground, - background - ); - assert contrastRatio == - 4.878363954846178 : "Test 6 Failed - Incorrect contrast ratio."; + final double backgroundLuminance = algImpl.getRelativeLuminance(background); + 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."; } public static void main(String[] args) { diff --git a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java index 105612aed3e3..0fb5b6f17b97 100644 --- a/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java +++ b/src/main/java/com/thealgorithms/misc/InverseOfMatrix.java @@ -6,7 +6,8 @@ * Wikipedia link : https://en.wikipedia.org/wiki/Invertible_matrix * * Here we use gauss elimination method to find the inverse of a given matrix. - * To understand gauss elimination method to find inverse of a matrix: https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination + * To understand gauss elimination method to find inverse of a matrix: + * https://www.sangakoo.com/en/unit/inverse-matrix-method-of-gaussian-elimination * * We can also find the inverse of a matrix */ diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java index d5572a94b33e..84dff89eaa8b 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java @@ -44,7 +44,7 @@ public static void main(String[] args) { */ MedianOfRunningArray p = new MedianOfRunningArray(); - int[] arr = { 10, 7, 4, 9, 2, 3, 11, 17, 14 }; + int[] arr = {10, 7, 4, 9, 2, 3, 11, 17, 14}; for (int i = 0; i < 9; i++) { p.insert(arr[i]); System.out.print(p.median() + " "); diff --git a/src/main/java/com/thealgorithms/misc/PalindromePrime.java b/src/main/java/com/thealgorithms/misc/PalindromePrime.java index ac6d2750afbf..58de938394af 100644 --- a/src/main/java/com/thealgorithms/misc/PalindromePrime.java +++ b/src/main/java/com/thealgorithms/misc/PalindromePrime.java @@ -6,9 +6,7 @@ public class PalindromePrime { public static void main(String[] args) { // Main funtion Scanner in = new Scanner(System.in); - System.out.println( - "Enter the quantity of First Palindromic Primes you want" - ); + System.out.println("Enter the quantity of First Palindromic Primes you want"); int n = in.nextInt(); // Input of how many first palindromic prime we want functioning(n); // calling function - functioning in.close(); diff --git a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java index c8526407a4e3..b9e6fbb78fc5 100644 --- a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java +++ b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java @@ -6,39 +6,24 @@ public class RangeInSortedArray { public static void main(String[] args) { // Testcases - assert Arrays.equals( - sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 3), - new int[] { 2, 4 } - ); - assert Arrays.equals( - sortedRange(new int[] { 1, 2, 3, 3, 3, 4, 5 }, 4), - new int[] { 5, 5 } - ); - assert Arrays.equals( - sortedRange(new int[] { 0, 1, 2 }, 3), - new int[] { -1, -1 } - ); + assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 3), new int[] {2, 4}); + assert Arrays.equals(sortedRange(new int[] {1, 2, 3, 3, 3, 4, 5}, 4), new int[] {5, 5}); + assert Arrays.equals(sortedRange(new int[] {0, 1, 2}, 3), new int[] {-1, -1}); } // Get the 1st and last occurrence index of a number 'key' in a non-decreasing array 'nums' // Gives [-1, -1] in case element doesn't exist in array public static int[] sortedRange(int[] nums, int key) { - int[] range = new int[] { -1, -1 }; + int[] range = new int[] {-1, -1}; alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true); alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false); return range; } - // Recursive altered binary search which searches for leftmost as well as rightmost occurrence of - // 'key' + // 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 - ) { + int[] nums, int key, int left, int right, int[] range, boolean goLeft) { if (left > right) { return; } @@ -64,16 +49,10 @@ public static void alteredBinSearch( } } - // Iterative altered binary search which searches for leftmost as well as rightmost occurrence of - // 'key' + // 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 - ) { + 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/Sort012D.java b/src/main/java/com/thealgorithms/misc/Sort012D.java index 18cb3cb0c4db..1337e5ca97a2 100644 --- a/src/main/java/com/thealgorithms/misc/Sort012D.java +++ b/src/main/java/com/thealgorithms/misc/Sort012D.java @@ -30,26 +30,24 @@ public static void sort012(int[] a) { int temp; while (mid <= h) { switch (a[mid]) { - case 0: - { - temp = a[l]; - a[l] = a[mid]; - a[mid] = temp; - l++; - mid++; - break; - } - case 1: - mid++; - break; - case 2: - { - temp = a[mid]; - a[mid] = a[h]; - a[h] = temp; - h--; - break; - } + case 0: { + temp = a[l]; + a[l] = a[mid]; + a[mid] = temp; + l++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[h]; + a[h] = temp; + h--; + break; + } } } System.out.println("the Sorted array is "); diff --git a/src/main/java/com/thealgorithms/misc/Sparcity.java b/src/main/java/com/thealgorithms/misc/Sparcity.java index 9326416090ec..994f19195e7d 100644 --- a/src/main/java/com/thealgorithms/misc/Sparcity.java +++ b/src/main/java/com/thealgorithms/misc/Sparcity.java @@ -3,8 +3,10 @@ import java.util.*; /* - *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements are 0, it is considered as sparse). - *The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse. + *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements + *are 0, it is considered as sparse). The interest in sparsity arises because its exploitation can + *lead to enormous computational savings and because many large matrix problems that occur in + *practice are sparse. * * @author Ojasva Jain */ @@ -19,7 +21,7 @@ class Sparcity { */ static double sparcity(double[][] mat) { int zero = 0; - //Traversing the matrix to count number of zeroes + // Traversing the matrix to count number of zeroes for (int i = 0; i < mat.length; i++) { for (int j = 0; j < mat[i].length; j++) { if (mat[i][j] == 0) { @@ -27,11 +29,11 @@ static double sparcity(double[][] mat) { } } } - //return sparcity + // return sparcity return ((double) zero / (mat.length * mat[1].length)); } - //Driver method + // Driver method public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter number of rows in matrix: "); diff --git a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java index 5700b94a18d3..fcd7a4320199 100644 --- a/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java +++ b/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java @@ -16,12 +16,8 @@ public static void main(String[] args) { arr[i] = scan.nextInt(); } ThreeSumProblem th = new ThreeSumProblem(); - System.out.println( - "Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n" - ); - System.out.println( - "Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n" - ); + System.out.println("Brute Force Approach\n" + (th.BruteForce(arr, ts)) + "\n"); + System.out.println("Two Pointer Approach\n" + (th.TwoPointer(arr, ts)) + "\n"); System.out.println("Hashmap Approach\n" + (th.Hashmap(arr, ts))); } @@ -42,8 +38,7 @@ public List<List<Integer>> BruteForce(int[] nums, int target) { } } } - arr = - new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(arr)); + arr = new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(arr)); return arr; } diff --git a/src/main/java/com/thealgorithms/misc/WordBoggle.java b/src/main/java/com/thealgorithms/misc/WordBoggle.java index 1257c5363c81..5513bdc5e598 100644 --- a/src/main/java/com/thealgorithms/misc/WordBoggle.java +++ b/src/main/java/com/thealgorithms/misc/WordBoggle.java @@ -27,54 +27,36 @@ public static List<String> boggleBoard(char[][] board, String[] words) { public static void main(String[] args) { // Testcase List<String> ans = new ArrayList<>( - Arrays.asList( - "a", - "boggle", + Arrays.asList("a", "boggle", "this", "NOTRE_PEATED", "is", "simple", "board")); + assert (boggleBoard( + new char[][] { + {'t', 'h', 'i', 's', 'i', 's', 'a'}, + {'s', 'i', 'm', 'p', 'l', 'e', 'x'}, + {'b', 'x', 'x', 'x', 'x', 'e', 'b'}, + {'x', 'o', 'g', 'g', 'l', 'x', 'o'}, + {'x', 'x', 'x', 'D', 'T', 'r', 'a'}, + {'R', 'E', 'P', 'E', 'A', 'd', 'x'}, + {'x', 'x', 'x', 'x', 'x', 'x', 'x'}, + {'N', 'O', 'T', 'R', 'E', '_', 'P'}, + {'x', 'x', 'D', 'E', 'T', 'A', 'E'}, + }, + new String[] { "this", - "NOTRE_PEATED", "is", + "not", + "a", "simple", - "board" - ) - ); - assert ( - boggleBoard( - new char[][] { - { 't', 'h', 'i', 's', 'i', 's', 'a' }, - { 's', 'i', 'm', 'p', 'l', 'e', 'x' }, - { 'b', 'x', 'x', 'x', 'x', 'e', 'b' }, - { 'x', 'o', 'g', 'g', 'l', 'x', 'o' }, - { 'x', 'x', 'x', 'D', 'T', 'r', 'a' }, - { 'R', 'E', 'P', 'E', 'A', 'd', 'x' }, - { 'x', 'x', 'x', 'x', 'x', 'x', 'x' }, - { 'N', 'O', 'T', 'R', 'E', '_', 'P' }, - { 'x', 'x', 'D', 'E', 'T', 'A', 'E' }, - }, - new String[] { - "this", - "is", - "not", - "a", - "simple", - "test", - "boggle", - "board", - "REPEATED", - "NOTRE_PEATED", - } - ) - .equals(ans) - ); + "test", + "boggle", + "board", + "REPEATED", + "NOTRE_PEATED", + }) + .equals(ans)); } - public static void explore( - int i, - int j, - char[][] board, - TrieNode trieNode, - boolean[][] visited, - Set<String> finalWords - ) { + public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, + Set<String> finalWords) { if (visited[i][j]) { return; } @@ -91,14 +73,7 @@ public static void explore( List<Integer[]> neighbors = getNeighbors(i, j, board); for (Integer[] neighbor : neighbors) { - explore( - neighbor[0], - neighbor[1], - board, - trieNode, - visited, - finalWords - ); + explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords); } visited[i][j] = false; @@ -107,35 +82,35 @@ public static void explore( public static List<Integer[]> getNeighbors(int i, int j, char[][] board) { List<Integer[]> neighbors = new ArrayList<>(); if (i > 0 && j > 0) { - neighbors.add(new Integer[] { i - 1, j - 1 }); + neighbors.add(new Integer[] {i - 1, j - 1}); } if (i > 0 && j < board[0].length - 1) { - neighbors.add(new Integer[] { i - 1, j + 1 }); + neighbors.add(new Integer[] {i - 1, j + 1}); } if (i < board.length - 1 && j < board[0].length - 1) { - neighbors.add(new Integer[] { i + 1, j + 1 }); + neighbors.add(new Integer[] {i + 1, j + 1}); } if (i < board.length - 1 && j > 0) { - neighbors.add(new Integer[] { i + 1, j - 1 }); + neighbors.add(new Integer[] {i + 1, j - 1}); } if (i > 0) { - neighbors.add(new Integer[] { i - 1, j }); + neighbors.add(new Integer[] {i - 1, j}); } if (i < board.length - 1) { - neighbors.add(new Integer[] { i + 1, j }); + neighbors.add(new Integer[] {i + 1, j}); } if (j > 0) { - neighbors.add(new Integer[] { i, j - 1 }); + neighbors.add(new Integer[] {i, j - 1}); } if (j < board[0].length - 1) { - neighbors.add(new Integer[] { i, j + 1 }); + neighbors.add(new Integer[] {i, j + 1}); } return neighbors; diff --git a/src/main/java/com/thealgorithms/others/BFPRT.java b/src/main/java/com/thealgorithms/others/BFPRT.java index f296fbda139f..29f47cd68ed6 100644 --- a/src/main/java/com/thealgorithms/others/BFPRT.java +++ b/src/main/java/com/thealgorithms/others/BFPRT.java @@ -66,8 +66,7 @@ public static int medianOfMedians(int[] arr, int begin, int end) { int offset = num % 5 == 0 ? 0 : 1; int[] mArr = new int[num / 5 + offset]; for (int i = 0; i < mArr.length; i++) { - mArr[i] = - getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); + mArr[i] = getMedian(arr, begin + i * 5, Math.min(end, begin + i * 5 + 4)); } return bfprt(mArr, 0, mArr.length - 1, mArr.length / 2); } diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java index 7e6ce9db4417..f6a287299651 100644 --- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java @@ -25,13 +25,8 @@ 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]; @@ -54,23 +49,11 @@ static void calculateNeed( * * @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 - ); + calculateNeed(needArray, maxArray, allocationArray, totalProcess, totalResources); boolean[] finishProcesses = new boolean[totalProcess]; @@ -113,16 +96,12 @@ static boolean checkSafeSystem( // If we could not find a next process in safe sequence. if (!foundSafeSystem) { - System.out.print( - "The system is not in the safe state because lack of resources" - ); + System.out.print("The system is not in the safe state because lack of resources"); return false; } } - System.out.print( - "The system is in safe sequence and the sequence is as follows: " - ); + System.out.print("The system is in safe sequence and the sequence is as follows: "); for (int i = 0; i < totalProcess; i++) { System.out.print("P" + safeSequenceArray[i] + " "); } @@ -163,9 +142,7 @@ public static void main(String[] args) { for (int i = 0; i < numberOfProcesses; i++) { System.out.println("For process " + i + ": "); for (int j = 0; j < numberOfResources; j++) { - System.out.println( - "Enter the maximum instances of resource " + j - ); + System.out.println("Enter the maximum instances of resource " + j); maxArray[i][j] = sc.nextInt(); } } @@ -181,20 +158,14 @@ public static void main(String[] args) { } } - checkSafeSystem( - processes, - availableArray, - maxArray, - allocationArray, - numberOfProcesses, - numberOfResources - ); + checkSafeSystem(processes, availableArray, maxArray, allocationArray, numberOfProcesses, + numberOfResources); sc.close(); } } /* - Example: + Example: n = 5 m = 3 @@ -202,10 +173,10 @@ public static void main(String[] args) { 0 1 2 0 1 2 0 1 2 0 0 1 0 7 5 3 3 3 2 - 1 2 0 0 3 2 2 + 1 2 0 0 3 2 2 2 3 0 2 9 0 2 3 2 1 1 2 2 2 4 0 0 2 4 3 3 - Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2 + Result: The system is in safe sequence and the sequence is as follows: P1, P3, P4, P0, P2 */ diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 2e4edbd9a1f6..f12e2cff8419 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -1,7 +1,8 @@ /* this Code is the illustration of Boyer moore's voting algorithm to find the majority element is an array that appears more than n/2 times in an array where "n" is the length of the array. -For more information on the algorithm refer https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm +For more information on the algorithm refer +https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ package com.thealgorithms.others; diff --git a/src/main/java/com/thealgorithms/others/CRC16.java b/src/main/java/com/thealgorithms/others/CRC16.java index 80dbbcb9a32d..c5c3b1f35a7d 100644 --- a/src/main/java/com/thealgorithms/others/CRC16.java +++ b/src/main/java/com/thealgorithms/others/CRC16.java @@ -1,7 +1,7 @@ package com.thealgorithms.others; /** - * Generates a crc16 checksum for a given string + * Generates a crc16 checksum for a given string */ public class CRC16 { @@ -9,21 +9,20 @@ public static void main(String[] args) { System.out.println(crc16("Hello World!")); } - public static String crc16(String message) { - int crc = 0xFFFF; // initial value - int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) - byte[] bytes = message.getBytes(); + public static String crc16(String message) { + int crc = 0xFFFF; // initial value + int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) + byte[] bytes = message.getBytes(); - for (byte b : bytes) { - for (int i = 0; i < 8; i++) { - boolean bit = ((b >> (7 - i) & 1) == 1); - boolean c15 = ((crc >> 15 & 1) == 1); - crc <<= 1; - if (c15 ^ bit) - crc ^= polynomial; - } - } - crc &= 0xffff; - return Integer.toHexString(crc).toUpperCase(); - } + for (byte b : bytes) { + for (int i = 0; i < 8; i++) { + boolean bit = ((b >> (7 - i) & 1) == 1); + boolean c15 = ((crc >> 15 & 1) == 1); + crc <<= 1; + if (c15 ^ bit) crc ^= polynomial; + } + } + crc &= 0xffff; + return Integer.toHexString(crc).toUpperCase(); + } } diff --git a/src/main/java/com/thealgorithms/others/Conway.java b/src/main/java/com/thealgorithms/others/Conway.java index 7a034d963633..b1d54e61094f 100644 --- a/src/main/java/com/thealgorithms/others/Conway.java +++ b/src/main/java/com/thealgorithms/others/Conway.java @@ -6,27 +6,24 @@ public class Conway { /* * This class will generate the conway sequence also known as the look and say sequence. - * To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. For example: - *1 is read off as "one 1" or 11. - *11 is read off as "two 1s" or 21. - *21 is read off as "one 2, one 1" or 1211. - *1211 is read off as "one 1, one 2, two 1s" or 111221. - *111221 is read off as "three 1s, two 2s, one 1" or 312211. - * https://en.wikipedia.org/wiki/Look-and-say_sequence + * To generate a member of the sequence from the previous member, read off the digits of the + *previous member, counting the number of digits in groups of the same digit. For example: 1 is + *read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, one 1" + *or 1211. 1211 is read off as "one 1, one 2, two 1s" or 111221. 111221 is read off as "three + *1s, two 2s, one 1" or 312211. https://en.wikipedia.org/wiki/Look-and-say_sequence * */ private static final StringBuilder builder = new StringBuilder(); protected static List<String> generateList(String originalString, int maxIteration) { List<String> numbers = new ArrayList<>(); - for(int i=0; i<maxIteration; i++) { + for (int i = 0; i < maxIteration; i++) { originalString = generateNextElement(originalString); numbers.add(originalString); } return numbers; } - public static String generateNextElement(String originalString) { builder.setLength(0); String[] stp = originalString.split("(?<=(.))(?!\\1)"); diff --git a/src/main/java/com/thealgorithms/others/Damm.java b/src/main/java/com/thealgorithms/others/Damm.java index 83550a7f083c..ac480b934fe7 100644 --- a/src/main/java/com/thealgorithms/others/Damm.java +++ b/src/main/java/com/thealgorithms/others/Damm.java @@ -24,16 +24,16 @@ public class Damm { * calculation. */ private static final byte[][] DAMM_TABLE = { - { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 }, - { 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 }, - { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 }, - { 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 }, - { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 }, - { 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 }, - { 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 }, - { 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 }, - { 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 }, - { 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 }, + {0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, + {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, + {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, + {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, + {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, + {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, + {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, + {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, + {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, + {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}, }; /** @@ -99,20 +99,13 @@ private static void checkAndPrint(String input) { private static void generateAndPrint(String input) { String result = addDammChecksum(input); System.out.println( - "Generate and add checksum to initial value '" + - input + - "'. Result: '" + - result + - "'" - ); + "Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { - throw new IllegalArgumentException( - "Input '" + input + "' contains not only digits" - ); + throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java index e2cd2630da51..c2f865d4a699 100644 --- a/src/main/java/com/thealgorithms/others/Dijkstra.java +++ b/src/main/java/com/thealgorithms/others/Dijkstra.java @@ -119,19 +119,14 @@ public boolean equals(Object object) { if (dist != vertex.dist) { return false; } - if ( - name != null ? !name.equals(vertex.name) : vertex.name != null - ) { + if (name != null ? !name.equals(vertex.name) : vertex.name != null) { return false; } - if ( - previous != null - ? !previous.equals(vertex.previous) - : vertex.previous != null - ) { + 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 @@ -140,8 +135,7 @@ public int hashCode() { result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + dist; result = 31 * result + (previous != null ? previous.hashCode() : 0); - result = - 31 * result + (neighbours != null ? neighbours.hashCode() : 0); + result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); return result; } @@ -170,8 +164,8 @@ public Graph(Edge[] edges) { // another pass to set neighbouring vertices for (Edge e : edges) { graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); - // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected - // graph + // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an + // undirected graph } } @@ -180,10 +174,7 @@ public Graph(Edge[] edges) { */ public void dijkstra(String startName) { if (!graph.containsKey(startName)) { - System.err.printf( - "Graph doesn't contain start vertex \"%s\"%n", - startName - ); + System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); return; } final Vertex source = graph.get(startName); @@ -208,7 +199,8 @@ private void dijkstra(final NavigableSet<Vertex> q) { // vertex with shortest distance (first iteration will return source) u = q.pollFirst(); if (u.dist == Integer.MAX_VALUE) { - break; // we can ignore u (and any other remaining vertices) since they are unreachable + break; // we can ignore u (and any other remaining vertices) since they are + // unreachable } // look at distances to each neighbour for (Map.Entry<Vertex, Integer> a : u.neighbours.entrySet()) { @@ -230,10 +222,7 @@ private void dijkstra(final NavigableSet<Vertex> q) { */ public void printPath(String endName) { if (!graph.containsKey(endName)) { - System.err.printf( - "Graph doesn't contain end vertex \"%s\"%n", - endName - ); + System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); return; } diff --git a/src/main/java/com/thealgorithms/others/FloydTriangle.java b/src/main/java/com/thealgorithms/others/FloydTriangle.java index a21ba47917a8..d25ab303e3ed 100644 --- a/src/main/java/com/thealgorithms/others/FloydTriangle.java +++ b/src/main/java/com/thealgorithms/others/FloydTriangle.java @@ -6,9 +6,7 @@ class FloydTriangle { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.println( - "Enter the number of rows which you want in your Floyd Triangle: " - ); + System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); int r = sc.nextInt(), n = 0; sc.close(); for (int i = 0; i < r; i++) { diff --git a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java index 006b165a9e97..8895176596f6 100644 --- a/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java +++ b/src/main/java/com/thealgorithms/others/HappyNumbersSeq.java @@ -7,9 +7,8 @@ public class HappyNumbersSeq { - private static final Set<Integer> CYCLE_NUMS = new HashSet<>( - Arrays.asList(4, 16, 20, 37, 58, 145) - ); + private static final Set<Integer> CYCLE_NUMS + = new HashSet<>(Arrays.asList(4, 16, 20, 37, 58, 145)); public static void main(String[] args) { Scanner in = new Scanner(System.in); diff --git a/src/main/java/com/thealgorithms/others/Huffman.java b/src/main/java/com/thealgorithms/others/Huffman.java index cf36ae22285e..a5af2becc993 100644 --- a/src/main/java/com/thealgorithms/others/Huffman.java +++ b/src/main/java/com/thealgorithms/others/Huffman.java @@ -35,11 +35,7 @@ public static void printCode(HuffmanNode root, String s) { // base case; if the left and right are null // then its a leaf node and we print // the code s generated by traversing the tree. - if ( - root.left == null && - root.right == null && - Character.isLetter(root.c) - ) { + if (root.left == null && root.right == null && Character.isLetter(root.c)) { // c is the character in the node System.out.println(root.c + ":" + s); @@ -60,15 +56,12 @@ public static void main(String[] args) { // number of characters. int n = 6; - char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; - int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'}; + int[] charfreq = {5, 9, 12, 13, 16, 45}; // creating a priority queue q. // makes a min-priority queue(min-heap). - PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>( - n, - new MyComparator() - ); + PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator()); for (int i = 0; i < n; i++) { // creating a Huffman node object diff --git a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java index 3904691a91d8..bb88c7e3ae2f 100644 --- a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java +++ b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java @@ -160,11 +160,11 @@ public static void main(String[] args) { int comp = printAutoSuggestions(root, "hel"); if (comp == -1) { - System.out.println( - "No other strings found " + "with this prefix\n" - ); + System.out.println("No other strings found " + + "with this prefix\n"); } else if (comp == 0) { - System.out.println("No string found with" + " this prefix\n"); + System.out.println("No string found with" + + " this prefix\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java index 81697750e21a..c90cfea1fcb1 100644 --- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java +++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java @@ -18,9 +18,7 @@ public static void main(String[] args) { } // To insert a new element(we are creating a new array) - System.out.println( - "Enter the index at which the element should be inserted" - ); + System.out.println("Enter the index at which the element should be inserted"); int insert_pos = s.nextInt(); System.out.println("Enter the element to be inserted"); int ins = s.nextInt(); diff --git a/src/main/java/com/thealgorithms/others/KochSnowflake.java b/src/main/java/com/thealgorithms/others/KochSnowflake.java index f82a812509e2..9107092057eb 100644 --- a/src/main/java/com/thealgorithms/others/KochSnowflake.java +++ b/src/main/java/com/thealgorithms/others/KochSnowflake.java @@ -56,8 +56,7 @@ public static void main(String[] args) { assert image.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // The snowflake is drawn in black and this is the position of the first vector - assert image.getRGB((int) offsetX, (int) offsetY) == - new Color(0, 0, 0).getRGB(); + assert image.getRGB((int) offsetX, (int) offsetY) == new Color(0, 0, 0).getRGB(); // Save image try { @@ -77,10 +76,7 @@ public static void main(String[] args) { * @param steps The number of iterations. * @return The transformed vectors after the iteration-steps. */ - public static ArrayList<Vector2> Iterate( - ArrayList<Vector2> initialVectors, - int steps - ) { + public static ArrayList<Vector2> Iterate(ArrayList<Vector2> initialVectors, int steps) { ArrayList<Vector2> vectors = initialVectors; for (int i = 0; i < steps; i++) { vectors = IterationStep(vectors); @@ -98,18 +94,14 @@ public static ArrayList<Vector2> Iterate( */ public static BufferedImage GetKochSnowflake(int imageWidth, int steps) { if (imageWidth <= 0) { - throw new IllegalArgumentException( - "imageWidth should be greater than zero" - ); + throw new IllegalArgumentException("imageWidth should be greater than zero"); } double offsetX = imageWidth / 10.; double offsetY = imageWidth / 3.7; Vector2 vector1 = new Vector2(offsetX, offsetY); - Vector2 vector2 = new Vector2( - imageWidth / 2, - Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY - ); + Vector2 vector2 + = new Vector2(imageWidth / 2, Math.sin(Math.PI / 3) * imageWidth * 0.8 + offsetY); Vector2 vector3 = new Vector2(imageWidth - offsetX, offsetY); ArrayList<Vector2> initialVectors = new ArrayList<Vector2>(); initialVectors.add(vector1); @@ -130,23 +122,15 @@ public static BufferedImage GetKochSnowflake(int imageWidth, int steps) { * applied. * @return The transformed vectors after the iteration-step. */ - private static ArrayList<Vector2> IterationStep( - ArrayList<Vector2> vectors - ) { + private static ArrayList<Vector2> IterationStep(ArrayList<Vector2> vectors) { ArrayList<Vector2> newVectors = new ArrayList<Vector2>(); for (int i = 0; i < vectors.size() - 1; i++) { Vector2 startVector = vectors.get(i); Vector2 endVector = vectors.get(i + 1); newVectors.add(startVector); - Vector2 differenceVector = endVector - .subtract(startVector) - .multiply(1. / 3); + Vector2 differenceVector = endVector.subtract(startVector).multiply(1. / 3); newVectors.add(startVector.add(differenceVector)); - newVectors.add( - startVector - .add(differenceVector) - .add(differenceVector.rotate(60)) - ); + newVectors.add(startVector.add(differenceVector).add(differenceVector.rotate(60))); newVectors.add(startVector.add(differenceVector.multiply(2))); } @@ -163,15 +147,9 @@ private static ArrayList<Vector2> IterationStep( * @return The image of the rendered edges. */ private static BufferedImage GetImage( - ArrayList<Vector2> vectors, - int imageWidth, - int imageHeight - ) { - BufferedImage image = new BufferedImage( - imageWidth, - imageHeight, - BufferedImage.TYPE_INT_RGB - ); + ArrayList<Vector2> vectors, int imageWidth, int imageHeight) { + BufferedImage image + = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); // Set the background white diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java index f9db1f742fe5..9aa0f6faa8e6 100644 --- a/src/main/java/com/thealgorithms/others/LineSweep.java +++ b/src/main/java/com/thealgorithms/others/LineSweep.java @@ -13,31 +13,33 @@ */ public class LineSweep { - /** Find Maximum end point + /** + * Find Maximum end point * param = ranges : Array of range[start,end] * return Maximum Endpoint */ - public static int FindMaximumEndPoint (int[][]ranges){ - Arrays.sort(ranges, Comparator.comparingInt(a->a[1])); - return ranges[ranges.length-1][1]; - } + public static int FindMaximumEndPoint(int[][] ranges) { + Arrays.sort(ranges, Comparator.comparingInt(a -> a[1])); + return ranges[ranges.length - 1][1]; + } - /** Find if any ranges overlap + /** + * Find if any ranges overlap * param = ranges : Array of range[start,end] * return true if overlap exists false otherwise. */ public static boolean isOverlap(int[][] ranges) { int maximumEndPoint = FindMaximumEndPoint(ranges); - Arrays.sort(ranges, Comparator.comparingInt(a->a[0])); - int[] numberLine = new int[maximumEndPoint+2]; + Arrays.sort(ranges, Comparator.comparingInt(a -> a[0])); + int[] numberLine = new int[maximumEndPoint + 2]; for (int[] range : ranges) { int start = range[0]; int end = range[1]; numberLine[start] += 1; - numberLine[end+1] -= 1; + numberLine[end + 1] -= 1; } int current = 0; @@ -46,6 +48,6 @@ public static boolean isOverlap(int[][] ranges) { current += num; overlaps = Math.max(overlaps, current); } - return overlaps >1 ; + return overlaps > 1; } } diff --git a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java index c96da433c007..f16946dc7860 100644 --- a/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java +++ b/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java @@ -21,11 +21,7 @@ public class LinearCongruentialGenerator { * @param modulo The maximum number that can be generated (exclusive). A * common value is 2^32. */ - public LinearCongruentialGenerator( - double multiplier, - double increment, - double modulo - ) { + public LinearCongruentialGenerator(double multiplier, double increment, double modulo) { this(System.currentTimeMillis(), multiplier, increment, modulo); } @@ -40,11 +36,7 @@ public LinearCongruentialGenerator( * common value is 2^32. */ public LinearCongruentialGenerator( - double seed, - double multiplier, - double increment, - double modulo - ) { + double seed, double multiplier, double increment, double modulo) { this.previousValue = seed; this.a = multiplier; this.c = increment; @@ -66,11 +58,8 @@ public static void main(String[] args) { // 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/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java index addf82554470..9bc02535a306 100644 --- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java +++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java @@ -27,7 +27,8 @@ private static void checkNumber(int number) { * @param number the input number * @param base the given base * @exception IllegalArgumentException number is negative or base is less than 2 - * @return the list containing the digits of the input number in the given base, the most significant digit is at the end of the array + * @return the list containing the digits of the input number in the given base, the most + * significant digit is at the end of the array */ public static ArrayList<Integer> computeDigitsInBase(int number, int base) { checkNumber(number); @@ -46,8 +47,8 @@ public static ArrayList<Integer> computeDigitsInBase(int number, int base) { * @return true, if the input array is a palindrome, false otherwise */ public static boolean isPalindromic(ArrayList<Integer> list) { - for (int pos = 0; pos < list.size()/2; ++pos) { - if(list.get(pos) != list.get(list.size()-1-pos)) { + for (int pos = 0; pos < list.size() / 2; ++pos) { + if (list.get(pos) != list.get(list.size() - 1 - pos)) { return false; } } @@ -59,7 +60,8 @@ public static boolean isPalindromic(ArrayList<Integer> list) { * @param number the input number * @param base the given base * @exception IllegalArgumentException number is negative or base is less than 2 - * @return true, if the input number represented in the given base is a palindrome, false otherwise + * @return true, if the input number represented in the given base is a palindrome, false + * otherwise */ public static boolean isPalindromicInBase(int number, int base) { checkNumber(number); @@ -78,14 +80,15 @@ public static boolean isPalindromicInBase(int number, int base) { } /** - * @brief finds the smallest base for which the representation of the input number is a palindrome + * @brief finds the smallest base for which the representation of the input number is a + * palindrome * @param number the input number * @exception IllegalArgumentException number is negative * @return the smallest base for which the representation of the input number is a palindrome */ public static int lowestBasePalindrome(int number) { int base = 2; - while(!isPalindromicInBase(number, base)) { + while (!isPalindromicInBase(number, base)) { ++base; } return base; diff --git a/src/main/java/com/thealgorithms/others/Luhn.java b/src/main/java/com/thealgorithms/others/Luhn.java index 319955e7fdeb..269250ba0fe5 100644 --- a/src/main/java/com/thealgorithms/others/Luhn.java +++ b/src/main/java/com/thealgorithms/others/Luhn.java @@ -67,8 +67,9 @@ public static boolean luhnCheck(int[] digits) { public static void main(String[] args) { System.out.println("Luhn algorithm usage examples:"); - int[] validInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7 }; - int[] invalidInput = { 4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4 }; //typo in last symbol + int[] validInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 7}; + int[] invalidInput = {4, 5, 6, 1, 2, 6, 1, 2, 1, 2, 3, 4, 5, 4, 6, 4}; // typo in last + // symbol checkAndPrint(validInput); checkAndPrint(invalidInput); @@ -83,9 +84,7 @@ public static void main(String[] args) { private static void checkAndPrint(int[] input) { String validationResult = Luhn.luhnCheck(input) ? "valid" : "not valid"; - System.out.println( - "Input " + Arrays.toString(input) + " is " + validationResult - ); + System.out.println("Input " + Arrays.toString(input) + " is " + validationResult); } /* @@ -109,21 +108,15 @@ private record CreditCard(int[] digits) { public static CreditCard fromString(String cardNumber) { Objects.requireNonNull(cardNumber); String trimmedCardNumber = cardNumber.replaceAll(" ", ""); - if ( - trimmedCardNumber.length() != DIGITS_COUNT || - !trimmedCardNumber.matches("\\d+") - ) { - throw new IllegalArgumentException( - "{" + cardNumber + "} - is not a card number" - ); + if (trimmedCardNumber.length() != DIGITS_COUNT || !trimmedCardNumber.matches("\\d+")) { + throw new IllegalArgumentException("{" + cardNumber + "} - is not a card number"); } int[] cardNumbers = toIntArray(trimmedCardNumber); boolean isValid = luhnCheck(cardNumbers); if (!isValid) { throw new IllegalArgumentException( - "Credit card number {" + cardNumber + "} - have a typo" - ); + "Credit card number {" + cardNumber + "} - have a typo"); } return new CreditCard(cardNumbers); @@ -146,11 +139,7 @@ public String number() { @Override public String toString() { - return String.format( - "%s {%s}", - CreditCard.class.getSimpleName(), - number() - ); + return String.format("%s {%s}", CreditCard.class.getSimpleName(), number()); } private static int[] toIntArray(String string) { @@ -161,19 +150,11 @@ private static int[] toIntArray(String string) { private static void businessExample(String cardNumber) { try { System.out.println( - "Trying to create CreditCard object from valid card number: " + - cardNumber - ); + "Trying to create CreditCard object from valid card number: " + cardNumber); CreditCard creditCard = CreditCard.fromString(cardNumber); - System.out.println( - "And business object is successfully created: " + - creditCard + - "\n" - ); + System.out.println("And business object is successfully created: " + creditCard + "\n"); } catch (IllegalArgumentException e) { - System.out.println( - "And fail with exception message: " + e.getMessage() + "\n" - ); + System.out.println("And fail with exception message: " + e.getMessage() + "\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/Mandelbrot.java b/src/main/java/com/thealgorithms/others/Mandelbrot.java index 6ffcc8556d8a..8dcaed2bfe05 100644 --- a/src/main/java/com/thealgorithms/others/Mandelbrot.java +++ b/src/main/java/com/thealgorithms/others/Mandelbrot.java @@ -27,23 +27,13 @@ public class Mandelbrot { public static void main(String[] args) { // Test black and white - BufferedImage blackAndWhiteImage = getImage( - 800, - 600, - -0.6, - 0, - 3.2, - 50, - false - ); + BufferedImage blackAndWhiteImage = getImage(800, 600, -0.6, 0, 3.2, 50, false); // Pixel outside the Mandelbrot set should be white. - assert blackAndWhiteImage.getRGB(0, 0) == - new Color(255, 255, 255).getRGB(); + assert blackAndWhiteImage.getRGB(0, 0) == new Color(255, 255, 255).getRGB(); // Pixel inside the Mandelbrot set should be black. - assert blackAndWhiteImage.getRGB(400, 300) == - new Color(0, 0, 0).getRGB(); + assert blackAndWhiteImage.getRGB(400, 300) == new Color(0, 0, 0).getRGB(); // Test color-coding BufferedImage coloredImage = getImage(800, 600, -0.6, 0, 3.2, 50, true); @@ -80,63 +70,38 @@ public static void main(String[] args) { * @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" - ); + throw new IllegalArgumentException("imageWidth should be greater than zero"); } if (imageHeight <= 0) { - throw new IllegalArgumentException( - "imageHeight should be greater than zero" - ); + throw new IllegalArgumentException("imageHeight should be greater than zero"); } if (maxStep <= 0) { - throw new IllegalArgumentException( - "maxStep should be greater than zero" - ); + 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 for (int imageX = 0; imageX < imageWidth; imageX++) { 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 figureX = figureCenterX + ((double) imageX / imageWidth - 0.5) * figureWidth; + 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()); } } @@ -179,18 +144,18 @@ private static Color colorCodedColorMap(double distance) { int t = (int) (val * (1 - (1 - f) * saturation)); switch (hi) { - case 0: - return new Color(v, t, p); - case 1: - return new Color(q, v, p); - case 2: - return new Color(p, v, t); - case 3: - return new Color(p, q, v); - case 4: - return new Color(t, p, v); - default: - return new Color(v, p, q); + case 0: + return new Color(v, t, p); + case 1: + return new Color(q, v, p); + case 2: + return new Color(p, v, t); + case 3: + return new Color(p, q, v); + case 4: + return new Color(t, p, v); + default: + return new Color(v, p, q); } } } @@ -205,11 +170,7 @@ private static Color colorCodedColorMap(double distance) { * @param maxStep Maximum number of steps to check for divergent behavior. * @return The relative distance as the ratio of steps taken to maxStep. */ - private static double getDistance( - double figureX, - double figureY, - int maxStep - ) { + private static double getDistance(double figureX, double figureY, int maxStep) { double a = figureX; double b = figureY; int currentStep = 0; diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java index 576d83a9789f..a74d4cc87745 100644 --- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java +++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java @@ -21,18 +21,16 @@ public abstract class MemoryManagementAlgorithms { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public abstract ArrayList<Integer> fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ); + public abstract ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses); /** - * A constant value used to indicate that an allocation has not been made. - * This value is used as a sentinel value to represent that no allocation has been made - * when allocating space in an array or other data structure. + * A constant value used to indicate that an allocation has not been made. + * This value is used as a sentinel value to represent that no allocation has been made + * when allocating space in an array or other data structure. * The value is -255 and is marked as protected and final to ensure that it cannot be modified - * from outside the class and that its value remains consistent throughout the program execution. - * + * from outside the class and that its value remains consistent throughout the program + * execution. + * * @author: Ishan Makadia (github.com/intrepid-ishan) * @version: April 06, 2023 */ @@ -44,7 +42,6 @@ public abstract ArrayList<Integer> fitProcess( */ class BestFitCPU extends MemoryManagementAlgorithms { - /** * Method to find the maximum valued element of an array filled with * positive integers. @@ -75,13 +72,12 @@ private static int findBestFit(int[] blockSizes, int processSize) { // Initialize minDiff with an unreachable value by a difference between a blockSize and the // processSize. int minDiff = findMaxElement(blockSizes); - int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the + 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. - if ( - blockSizes[i] - processSize < minDiff && - blockSizes[i] - processSize >= 0 - ) { + 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; } @@ -101,18 +97,19 @@ private static int findBestFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList<Integer> fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the best-fit algorithm + public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the best-fit + // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findBestFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] + -= processSize; // resize the block based on the process size } } return memAlloc; @@ -136,7 +133,8 @@ 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; @@ -161,18 +159,19 @@ private static int findWorstFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList<Integer> fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the worst-fit algorithm + public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the worst-fit + // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findWorstFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] + -= processSize; // resize the block based on the process size } } return memAlloc; @@ -184,7 +183,6 @@ public ArrayList<Integer> fitProcess( */ class FirstFitCPU extends MemoryManagementAlgorithms { - /** * Method to find the index of the memory block that is going to fit the * given process based on the first fit algorithm. @@ -216,18 +214,19 @@ private static int findFirstFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList<Integer> fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the first-fit algorithm + public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the first-fit + // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findFirstFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] + -= processSize; // resize the block based on the process size } } return memAlloc; @@ -239,12 +238,14 @@ public ArrayList<Integer> fitProcess( */ 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 * given process based on the next fit algorithm. In the case of next fit, - * if the search is interrupted in between, the new search is carried out from the last location. + * if the search is interrupted in between, the new search is carried out from the last + * location. * * @param blocks: the array with the available memory blocks. * @param process: the size of the process. @@ -278,18 +279,19 @@ private int findNextFit(int[] blockSizes, int processSize) { * @return the ArrayList filled with Integers repressenting the memory * allocation that took place. */ - public ArrayList<Integer> fitProcess( - int[] sizeOfBlocks, - int[] sizeOfProcesses - ) { - // The array list responsible for saving the memory allocations done by the first-fit algorithm + public ArrayList<Integer> fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses) { + // The array list responsible for saving the memory allocations done by the first-fit + // algorithm ArrayList<Integer> memAlloc = new ArrayList<>(); // Do this for every process for (int processSize : sizeOfProcesses) { - int chosenBlockIdx = findNextFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used + int chosenBlockIdx = findNextFit( + sizeOfBlocks, processSize); // Find the index of the memory block going to be used memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list - if (chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, - sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size + if (chosenBlockIdx + != NO_ALLOCATION) { // Only if a block was chosen to store the process in it, + sizeOfBlocks[chosenBlockIdx] + -= processSize; // resize the block based on the process size } } return memAlloc; diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java index f05d19389fad..539b9dd2ec94 100644 --- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java +++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java @@ -43,11 +43,7 @@ public static void main(String[] args) { System.out.println(Arrays.toString(miniMaxAlgorith.getScores())); System.out.println( - "The best score for " + - (isMaximizer ? "Maximizer" : "Minimizer") + - " is " + - bestScore - ); + "The best score for " + (isMaximizer ? "Maximizer" : "Minimizer") + " is " + bestScore); } /** @@ -59,12 +55,7 @@ public static void main(String[] args) { * @param verbose True to show each players choices. * @return The optimal score for the player that made the first move. */ - public int miniMax( - int depth, - boolean isMaximizer, - int index, - boolean verbose - ) { + public int miniMax(int depth, boolean isMaximizer, int index, boolean verbose) { int bestScore, score1, score2; if (depth == height) { // Leaf node reached. @@ -88,13 +79,8 @@ public int miniMax( // (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 b5a7422aece4..6cd5a08d1274 100644 --- a/src/main/java/com/thealgorithms/others/PageRank.java +++ b/src/main/java/com/thealgorithms/others/PageRank.java @@ -11,8 +11,7 @@ public static void main(String[] args) { nodes = in.nextInt(); PageRank p = new PageRank(); System.out.println( - "Enter the Adjacency Matrix with 1->PATH & 0->NO PATH Between two WebPages: " - ); + "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(); @@ -37,13 +36,8 @@ public void calc(double totalNodes) { 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++) { @@ -52,9 +46,7 @@ public void calc(double totalNodes) { System.out.print("\n Initial PageRank Values , 0th Step \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } while (ITERATION_STEP <= 2) { // Iterations @@ -64,21 +56,13 @@ public void calc(double totalNodes) { this.pagerank[k] = 0; } - for ( - InternalNodeNumber = 1; - InternalNodeNumber <= totalNodes; - InternalNodeNumber++ - ) { - for ( - ExternalNodeNumber = 1; - ExternalNodeNumber <= totalNodes; - ExternalNodeNumber++ - ) { - if ( - this.path[ExternalNodeNumber][InternalNodeNumber] == 1 - ) { + for (InternalNodeNumber = 1; InternalNodeNumber <= totalNodes; InternalNodeNumber++) { + 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 @@ -86,21 +70,14 @@ public void calc(double totalNodes) { 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"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + - k + - " is :\t" + - this.pagerank[k] + - "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } ITERATION_STEP = ITERATION_STEP + 1; @@ -108,16 +85,13 @@ public void calc(double totalNodes) { // Add the Damping Factor to PageRank for (k = 1; k <= totalNodes; k++) { - this.pagerank[k] = - (1 - DampingFactor) + DampingFactor * this.pagerank[k]; + this.pagerank[k] = (1 - DampingFactor) + DampingFactor * this.pagerank[k]; } // Display PageRank System.out.print("\n Final Page Rank : \n"); for (k = 1; k <= totalNodes; k++) { - System.out.printf( - " Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n" - ); + System.out.printf(" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"); } } } diff --git a/src/main/java/com/thealgorithms/others/PasswordGen.java b/src/main/java/com/thealgorithms/others/PasswordGen.java index 38a20841ab74..c079d1cbebd2 100644 --- a/src/main/java/com/thealgorithms/others/PasswordGen.java +++ b/src/main/java/com/thealgorithms/others/PasswordGen.java @@ -38,11 +38,7 @@ static String generatePassword(int min_length, int max_length) { StringBuilder password = new StringBuilder(); // Note that size of the password is also random - for ( - int i = random.nextInt(max_length - min_length) + min_length; - i > 0; - --i - ) { + for (int i = random.nextInt(max_length - min_length) + min_length; i > 0; --i) { password.append(letters.get(random.nextInt(letters.size()))); } diff --git a/src/main/java/com/thealgorithms/others/PerlinNoise.java b/src/main/java/com/thealgorithms/others/PerlinNoise.java index c3591cf0aaf8..a979c514313f 100644 --- a/src/main/java/com/thealgorithms/others/PerlinNoise.java +++ b/src/main/java/com/thealgorithms/others/PerlinNoise.java @@ -18,12 +18,7 @@ public class PerlinNoise { * @return float array containing calculated "Perlin-Noise" values */ static float[][] generatePerlinNoise( - int width, - int height, - int octaveCount, - float persistence, - long seed - ) { + 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][][]; @@ -38,8 +33,7 @@ static float[][] generatePerlinNoise( // calculate octaves with different roughness for (int octave = 0; octave < octaveCount; octave++) { - noiseLayers[octave] = - generatePerlinNoiseLayer(base, width, height, octave); + noiseLayers[octave] = generatePerlinNoiseLayer(base, width, height, octave); } float amplitude = 1f; @@ -76,12 +70,7 @@ static float[][] generatePerlinNoise( * @param octave current layer * @return float array containing calculated "Perlin-Noise-Layer" values */ - static float[][] generatePerlinNoiseLayer( - float[][] base, - int width, - int height, - int octave - ) { + static float[][] generatePerlinNoiseLayer(float[][] base, int width, int height, int octave) { float[][] perlinNoiseLayer = new float[width][height]; // calculate period (wavelength) for different shapes @@ -101,22 +90,13 @@ static float[][] generatePerlinNoiseLayer( float verticalBlend = (y - y0) * frequency; // blend top corners - float top = interpolate( - base[x0][y0], - base[x1][y0], - horizintalBlend - ); + float top = interpolate(base[x0][y0], base[x1][y0], horizintalBlend); // blend bottom corners - float bottom = interpolate( - base[x0][y1], - base[x1][y1], - horizintalBlend - ); + float bottom = interpolate(base[x0][y1], base[x1][y1], horizintalBlend); // blend top and bottom interpolation to get the final blend value for this cell - perlinNoiseLayer[x][y] = - interpolate(top, bottom, verticalBlend); + perlinNoiseLayer[x][y] = interpolate(top, bottom, verticalBlend); } } @@ -163,8 +143,7 @@ public static void main(String[] args) { System.out.println("Charset (String): "); charset = in.next(); - perlinNoise = - generatePerlinNoise(width, height, octaveCount, persistence, seed); + perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); final char[] chars = charset.toCharArray(); final int length = chars.length; final float step = 1f / length; diff --git a/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java b/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java index d2065085d8c6..ddc37a916cbf 100644 --- a/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java +++ b/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java @@ -47,7 +47,6 @@ public List<Integer> print(int[][] matrix, int row, int col) { } row--; - } // print columns from first except printed elements @@ -57,9 +56,7 @@ public List<Integer> print(int[][] matrix, int row, int col) { } c++; } - } return result; } - } diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java index 4bd3fa69cf6e..6c5a0b7bee10 100644 --- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java +++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java @@ -142,8 +142,7 @@ public static void main(String[] args) { System.out.println(myQueue.remove()); // Will print 1 System.out.println( - (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack() - ); // Will print NULL + (myQueue.isInStackEmpty()) ? "null" : myQueue.peekBack()); // Will print NULL // instack: [] // outStack: [(top) 2, 3, 4] diff --git a/src/main/java/com/thealgorithms/others/RabinKarp.java b/src/main/java/com/thealgorithms/others/RabinKarp.java index 3c123ace3e89..8757f03bab4b 100644 --- a/src/main/java/com/thealgorithms/others/RabinKarp.java +++ b/src/main/java/com/thealgorithms/others/RabinKarp.java @@ -35,21 +35,19 @@ private static void searchPat(String text, String pattern, int q) { h = (int) Math.pow(d, m - 1) % q; for (i = 0; i < m; i++) { - // hash value is calculated for each character and then added with the hash value of the next - // character for pattern - // as well as the text for length equal to the length of pattern + // hash value is calculated for each character and then added with the hash value of the + // next character for pattern as well as the text for length equal to the length of + // pattern p = (d * p + pattern.charAt(i)) % q; t = (d * t + text.charAt(i)) % q; } for (i = 0; i <= n - m; i++) { // if the calculated hash value of the pattern and text matches then - // all the characters of the pattern is matched with the text of length equal to length of the - // pattern - // if all matches then pattern exist in string - // if not then the hash value of the first character of the text is subtracted and hash value - // of the next character after the end - // of the evaluated characters is added + // all the characters of the pattern is matched with the text of length equal to length + // of the pattern if all matches then pattern exist in string if not then the hash value + // of the first character of the text is subtracted and hash value of the next character + // after the end of the evaluated characters is added if (p == t) { // if hash value matches then the individual characters are matched for (j = 0; j < m; j++) { @@ -65,10 +63,9 @@ private static void searchPat(String text, String pattern, int q) { } } - // if i<n-m then hash value of the first character of the text is subtracted and hash value of - // the next character after the end - // of the evaluated characters is added to get the hash value of the next window of characters - // in the text + // if i<n-m then hash value of the first character of the text is subtracted and hash + // value of the next character after the end of the evaluated characters is added to get + // the hash value of the next window of characters in the text if (i < n - m) { t = (d * (t - text.charAt(i) * h) + text.charAt(i + m)) % q; diff --git a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java index 0b410a9d5947..5e4662b0b052 100644 --- a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java +++ b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java @@ -9,15 +9,11 @@ public class RemoveDuplicateFromString { public static void main(String[] args) throws Exception { - BufferedReader br = new BufferedReader( - new InputStreamReader(System.in) - ); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String inpStr = br.readLine(); System.out.println("Actual string is: " + inpStr); - System.out.println( - "String after removing duplicates: " + removeDuplicate(inpStr) - ); + System.out.println("String after removing duplicates: " + removeDuplicate(inpStr)); br.close(); } diff --git a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java index 19f875938a92..9c26dffa0768 100644 --- a/src/main/java/com/thealgorithms/others/ReturnSubsequence.java +++ b/src/main/java/com/thealgorithms/others/ReturnSubsequence.java @@ -8,7 +8,8 @@ public static void main(String[] args) { 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++) { @@ -22,23 +23,26 @@ public static void main(String[] args) { * @return subsequence */ private static String[] returnSubsequence(String givenString) { - if ( - givenString.length() == 0 - ) { // in it // If string is empty we will create an array of size=1 and insert "" (Empty string) + if (givenString.length() == 0) { // in it // If string is empty we will create an array of + // size=1 and insert "" (Empty string) String[] ans = new String[1]; 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 3ffc38062339..39669373fe85 100644 --- a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java +++ b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java @@ -30,10 +30,8 @@ public static int[] findPrimesTill(int n) { } } - 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 015e6a2650c4..3314f6d9c7bb 100644 --- a/src/main/java/com/thealgorithms/others/SkylineProblem.java +++ b/src/main/java/com/thealgorithms/others/SkylineProblem.java @@ -19,10 +19,7 @@ public void run() { String input = sc.next(); String[] data = input.split(","); this.add( - Integer.parseInt(data[0]), - Integer.parseInt(data[1]), - Integer.parseInt(data[2]) - ); + Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); } this.print(this.findSkyline(0, num - 1)); @@ -62,10 +59,7 @@ public ArrayList<Skyline> findSkyline(int start, int end) { return this.mergeSkyline(sky1, sky2); } - public ArrayList<Skyline> mergeSkyline( - ArrayList<Skyline> sky1, - ArrayList<Skyline> sky2 - ) { + public ArrayList<Skyline> mergeSkyline(ArrayList<Skyline> sky1, ArrayList<Skyline> sky2) { int currentH1 = 0, currentH2 = 0; ArrayList<Skyline> skyline = new ArrayList<>(); int maxH = 0; diff --git a/src/main/java/com/thealgorithms/others/Sudoku.java b/src/main/java/com/thealgorithms/others/Sudoku.java index 574ca98370a7..d2bc1d5c7add 100644 --- a/src/main/java/com/thealgorithms/others/Sudoku.java +++ b/src/main/java/com/thealgorithms/others/Sudoku.java @@ -102,15 +102,15 @@ public static void print(int[][] board, int N) { // Driver Code public static void main(String[] args) { int[][] board = new int[][] { - { 3, 0, 6, 5, 0, 8, 4, 0, 0 }, - { 5, 2, 0, 0, 0, 0, 0, 0, 0 }, - { 0, 8, 7, 0, 0, 0, 0, 3, 1 }, - { 0, 0, 3, 0, 1, 0, 0, 8, 0 }, - { 9, 0, 0, 8, 6, 3, 0, 0, 5 }, - { 0, 5, 0, 0, 9, 0, 6, 0, 0 }, - { 1, 3, 0, 0, 0, 0, 2, 5, 0 }, - { 0, 0, 0, 0, 0, 0, 0, 7, 4 }, - { 0, 0, 5, 2, 0, 6, 3, 0, 0 }, + {3, 0, 6, 5, 0, 8, 4, 0, 0}, + {5, 2, 0, 0, 0, 0, 0, 0, 0}, + {0, 8, 7, 0, 0, 0, 0, 3, 1}, + {0, 0, 3, 0, 1, 0, 0, 8, 0}, + {9, 0, 0, 8, 6, 3, 0, 0, 5}, + {0, 5, 0, 0, 9, 0, 6, 0, 0}, + {1, 3, 0, 0, 0, 0, 2, 5, 0}, + {0, 0, 0, 0, 0, 0, 0, 7, 4}, + {0, 0, 5, 2, 0, 6, 3, 0, 0}, }; int N = board.length; diff --git a/src/main/java/com/thealgorithms/others/TopKWords.java b/src/main/java/com/thealgorithms/others/TopKWords.java index 71fd4f9173c5..6473c1739e68 100644 --- a/src/main/java/com/thealgorithms/others/TopKWords.java +++ b/src/main/java/com/thealgorithms/others/TopKWords.java @@ -64,12 +64,11 @@ public Map<String, Integer> getDictionary() { public static void main(String[] args) { // you can replace the filePath with yours CountWords cw = new CountWords("/Users/lisanaaa/Desktop/words.txt"); - Map<String, Integer> dictionary = cw.getDictionary(); // get the words dictionary: {word: frequency} + Map<String, Integer> dictionary + = cw.getDictionary(); // get the words dictionary: {word: frequency} // we change the map to list for convenient sort - List<Map.Entry<String, Integer>> list = new ArrayList<>( - dictionary.entrySet() - ); + List<Map.Entry<String, Integer>> list = new ArrayList<>(dictionary.entrySet()); // sort by lambda valueComparator list.sort(Comparator.comparing(m -> m.getValue())); diff --git a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java index 0c1889af8222..c0fb4d75f84d 100644 --- a/src/main/java/com/thealgorithms/others/TowerOfHanoi.java +++ b/src/main/java/com/thealgorithms/others/TowerOfHanoi.java @@ -4,20 +4,15 @@ class TowerOfHanoi { - public static void shift( - int n, - String startPole, - String intermediatePole, - String endPole - ) { + public static void shift(int n, String startPole, String intermediatePole, String endPole) { // if n becomes zero the program returns thus ending the loop. if (n != 0) { - // Shift function is called in recursion for swapping the n-1 disc from the startPole to the - // intermediatePole + // Shift function is called in recursion for swapping the n-1 disc from the startPole to + // the intermediatePole shift(n - 1, startPole, endPole, intermediatePole); System.out.format("Move %d from %s to %s\n", n, startPole, endPole); // Result Printing - // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole - // to the endPole + // Shift function is called in recursion for swapping the n-1 disc from the + // intermediatePole to the endPole shift(n - 1, intermediatePole, startPole, endPole); } } diff --git a/src/main/java/com/thealgorithms/others/Verhoeff.java b/src/main/java/com/thealgorithms/others/Verhoeff.java index e60881089214..a783aceb0fd2 100644 --- a/src/main/java/com/thealgorithms/others/Verhoeff.java +++ b/src/main/java/com/thealgorithms/others/Verhoeff.java @@ -35,16 +35,16 @@ public class Verhoeff { * Dihedral group</a> */ private static final byte[][] MULTIPLICATION_TABLE = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - { 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, - { 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 }, - { 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 }, - { 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 }, - { 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 }, - { 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 }, - { 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 }, - { 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, - { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, + {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, + {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, + {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, + {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, + {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, + {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, + {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, + {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}, }; /** @@ -71,14 +71,14 @@ public class Verhoeff { * {@code p(i+j,n) = p(i, p(j,n))}. */ private static final byte[][] PERMUTATION_TABLE = { - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, - { 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, - { 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 }, - { 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 }, - { 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 }, - { 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 }, - { 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, - { 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, + {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, + {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, + {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, + {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, + {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, + {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}, }; /** @@ -147,29 +147,20 @@ public static void main(String[] args) { } private static void checkAndPrint(String input) { - String validationResult = Verhoeff.verhoeffCheck(input) - ? "valid" - : "not valid"; + String validationResult = Verhoeff.verhoeffCheck(input) ? "valid" : "not valid"; System.out.println("Input '" + input + "' is " + validationResult); } private static void generateAndPrint(String input) { String result = addVerhoeffChecksum(input); System.out.println( - "Generate and add checksum to initial value '" + - input + - "'. Result: '" + - result + - "'" - ); + "Generate and add checksum to initial value '" + input + "'. Result: '" + result + "'"); } private static void checkInput(String input) { Objects.requireNonNull(input); if (!input.matches("\\d+")) { - throw new IllegalArgumentException( - "Input '" + input + "' contains not only digits" - ); + throw new IllegalArgumentException("Input '" + input + "' contains not only digits"); } } diff --git a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java index 418c1c70a440..8a73e5ace57c 100644 --- a/src/main/java/com/thealgorithms/others/cn/HammingDistance.java +++ b/src/main/java/com/thealgorithms/others/cn/HammingDistance.java @@ -5,14 +5,9 @@ public class HammingDistance { - public int getHammingDistanceBetweenBits( - String senderBits, - String receiverBits - ) { + public int getHammingDistanceBetweenBits(String senderBits, String receiverBits) { if (senderBits.length() != receiverBits.length()) { - throw new IllegalArgumentException( - "Sender and Receiver bits should be same" - ); + throw new IllegalArgumentException("Sender and Receiver bits should be same"); } List<byte[]> byteArray = new ArrayList<>(); diff --git a/src/main/java/com/thealgorithms/others/countSetBits.java b/src/main/java/com/thealgorithms/others/countSetBits.java index fe71e1d7426b..04e0d6f62e6e 100644 --- a/src/main/java/com/thealgorithms/others/countSetBits.java +++ b/src/main/java/com/thealgorithms/others/countSetBits.java @@ -2,37 +2,41 @@ public class countSetBits { - /** - * The below algorithm is called as Brian Kernighan's algorithm - * We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. The idea is to only consider the set bits of an integer by turning off its rightmost set bit (after counting it), so the next iteration of the loop considers the next rightmost bit. + /** + * The below algorithm is called as Brian Kernighan's algorithm + * We can use Brian Kernighan’s algorithm to improve the above naive algorithm’s performance. + The idea is to only consider the set bits of an integer by turning off its rightmost set bit + (after counting it), so the next iteration of the loop considers the next rightmost bit. - The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This works as the expression n-1 flips all the bits after the rightmost set bit of n, including the rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. + The expression n & (n-1) can be used to turn off the rightmost set bit of a number n. This + works as the expression n-1 flips all the bits after the rightmost set bit of n, including the + rightmost set bit itself. Therefore, n & (n-1) results in the last bit flipped of n. For example, consider number 52, which is 00110100 in binary, and has a total 3 bits set. 1st iteration of the loop: n = 52 - + 00110100 & (n) 00110011 (n-1) ~~~~~~~~ 00110000 - - + + 2nd iteration of the loop: n = 48 - + 00110000 & (n) 00101111 (n-1) ~~~~~~~~ 00100000 - - + + 3rd iteration of the loop: n = 32 - + 00100000 & (n) 00011111 (n-1) ~~~~~~~~ 00000000 (n = 0) - + * @param num takes Long number whose number of set bit is to be found * @return the count of set bits in the binary equivalent */ diff --git a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java index b1c3411b7b07..f57ee5c67b83 100644 --- a/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java @@ -1,11 +1,11 @@ package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; - import java.util.List; /** - * Non-pre-emptive First Come First Serve scheduling. This can be understood here - https://www.scaler.com/topics/first-come-first-serve/ + * Non-pre-emptive First Come First Serve scheduling. This can be understood here - + * https://www.scaler.com/topics/first-come-first-serve/ */ public class FCFSScheduling { @@ -23,25 +23,27 @@ public void scheduleProcesses() { private void evaluateWaitingTime() { int processesNumber = processes.size(); - if(processesNumber == 0) { + if (processesNumber == 0) { return; } 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); - waitingTime = processes.get(i).getWaitingTime(); - burstTime = processes.get(i).getBurstTime(); + for (int i = 1; i < processesNumber; i++) { + processes.get(i).setWaitingTime(waitingTime + burstTime); + waitingTime = processes.get(i).getWaitingTime(); + burstTime = processes.get(i).getBurstTime(); } } private void evaluateTurnAroundTime() { - for(int i=0; i<processes.size(); i++) { - processes.get(i).setTurnAroundTimeTime(processes.get(i).getBurstTime() + processes.get(i).getWaitingTime()); + for (int i = 0; i < processes.size(); i++) { + 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 6d26bfd7f34b..e34cb7879ebd 100644 --- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java @@ -5,15 +5,15 @@ package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; - import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** - * The Round-robin scheduling algorithm is a kind of preemptive First come, First Serve CPU Scheduling algorithm. - * This can be understood here - https://www.scaler.com/topics/round-robin-scheduling-in-os/ + * The Round-robin scheduling algorithm is a kind of preemptive First come, First Serve CPU + * Scheduling algorithm. This can be understood here - + * https://www.scaler.com/topics/round-robin-scheduling-in-os/ */ public class RRScheduling { @@ -33,7 +33,7 @@ public void scheduleProcesses() { private void evaluateTurnAroundTime() { int processesNumber = processes.size(); - if(processesNumber == 0) { + if (processesNumber == 0) { return; } @@ -51,38 +51,42 @@ private void evaluateTurnAroundTime() { remainingBurstTime[i] = processes.get(i).getBurstTime(); } - while (completed != processesNumber){ + while (completed != processesNumber) { int index = queue.poll(); - if(remainingBurstTime[index] == processes.get(index).getBurstTime()){ + if (remainingBurstTime[index] == processes.get(index).getBurstTime()) { currentTime = Math.max(currentTime, processes.get(index).getArrivalTime()); } - if(remainingBurstTime[index] - quantumTime > 0){ + if (remainingBurstTime[index] - quantumTime > 0) { remainingBurstTime[index] -= quantumTime; 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; + remainingBurstTime[index] = 0; } - // 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){ - mark[i]=1; + // 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) { + mark[i] = 1; queue.add(i); } } - // If the current process has burst time remaining, push the process into the queue again. - if(remainingBurstTime[index] > 0) queue.add(index); + // If the current process has burst time remaining, push the process into the queue + // again. + if (remainingBurstTime[index] > 0) queue.add(index); // If the queue is empty, pick the first process from the list that is not completed. - if(queue.isEmpty()){ - for (int i=1; i<processesNumber; i++){ - if (remainingBurstTime[i] > 0){ + if (queue.isEmpty()) { + for (int i = 1; i < processesNumber; i++) { + if (remainingBurstTime[i] > 0) { mark[i] = 1; queue.add(i); break; @@ -94,6 +98,7 @@ private void evaluateTurnAroundTime() { private void evaluateWaitingTime() { for (int i = 0; i < processes.size(); i++) - processes.get(i).setWaitingTime(processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime()); + 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 bf3a9f00fae0..5eb8879abd3f 100644 --- a/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java @@ -1,17 +1,17 @@ package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; - import java.util.ArrayList; /** - * Implementation of Shortest Job First Algorithm: The algorithm allows the waiting process with the minimal burst time to be executed first. - * see more here: https://www.guru99.com/shortest-job-first-sjf-scheduling.html + * Implementation of Shortest Job First Algorithm: The algorithm allows the waiting process with the + * minimal burst time to be executed first. see more here: + * https://www.guru99.com/shortest-job-first-sjf-scheduling.html */ public class SJFScheduling { protected ArrayList<ProcessDetails> processes; - protected ArrayList<String>schedule ; + protected ArrayList<String> schedule; /** * a simple constructor @@ -20,85 +20,79 @@ public class SJFScheduling { */ SJFScheduling(final ArrayList<ProcessDetails> processes) { this.processes = processes; - schedule=new ArrayList<>(); + schedule = new ArrayList<>(); sortByArrivalTime(); } -protected void sortByArrivalTime() { - int size=processes.size(),i,j; + protected void sortByArrivalTime() { + int size = processes.size(), i, j; ProcessDetails temp; - for(i=0;i<size;i++) - { - for(j=i+1;j<size-1;j++) - { - if(processes.get(j).getArrivalTime()>processes.get(j+1).getArrivalTime()) - { - temp=processes.get(j); - processes.set(j,processes.get(j+1)); - processes.set(j+1,temp); + for (i = 0; i < size; i++) { + for (j = i + 1; j < size - 1; j++) { + if (processes.get(j).getArrivalTime() > processes.get(j + 1).getArrivalTime()) { + temp = processes.get(j); + processes.set(j, processes.get(j + 1)); + processes.set(j + 1, temp); } } } - -} + } /** * this functions returns the order of the executions */ public void scheduleProcesses() { - ArrayList<ProcessDetails> ready=new ArrayList<>(); + ArrayList<ProcessDetails> ready = new ArrayList<>(); - int size = processes.size(),runtime,time=0; - int executed=0,j,k=0; + int size = processes.size(), runtime, time = 0; + int executed = 0, j, k = 0; ProcessDetails running; if (size == 0) { return; } - - while(executed<size) - { - while(k<size && processes.get(k).getArrivalTime()<=time)//here we find the processes that have arrived. + while (executed < size) { + while (k < size + && processes.get(k).getArrivalTime() + <= time) // here we find the processes that have arrived. { ready.add(processes.get(k)); k++; } - running=findShortestJob(ready); - if(running==null) - { - time++; + running = findShortestJob(ready); + if (running == null) { + time++; + } else { + runtime = running.getBurstTime(); + for (j = 0; j < runtime; j++) { + time++; + } + schedule.add(running.getProcessId()); + ready.remove(running); + executed++; } - else { - runtime = running.getBurstTime(); - for (j = 0; j < runtime; j++) { - time++;} - schedule.add(running.getProcessId()); - ready.remove(running); - executed++; - } } - - } /** - * this function evaluates the shortest job of all the ready processes (based on a process burst time) + * this function evaluates the shortest job of all the ready processes (based on a process + * burst time) * @param ReadyProcesses an array list of ready processes - * @return returns the process' with the shortest burst time OR NULL if there are no ready processes + * @return returns the process' with the shortest burst time OR NULL if there are no ready + * processes */ private ProcessDetails findShortestJob(ArrayList<ProcessDetails> ReadyProcesses) { - if (ReadyProcesses.isEmpty()){ + if (ReadyProcesses.isEmpty()) { return null; } - int i,size = ReadyProcesses.size(); + int i, size = ReadyProcesses.size(); int minBurstTime = ReadyProcesses.get(0).getBurstTime(), temp, positionOfShortestJob = 0; - for (i = 1; i < size; i++) { temp = ReadyProcesses.get(i).getBurstTime(); - if (minBurstTime > temp ) { + if (minBurstTime > temp) { minBurstTime = temp; positionOfShortestJob = i; } @@ -106,10 +100,4 @@ private ProcessDetails findShortestJob(ArrayList<ProcessDetails> ReadyProcesses) return ReadyProcesses.get(positionOfShortestJob); } - - - - - - } - +} diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java index 1373748e0a54..42502c36ff92 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java @@ -41,12 +41,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private <T extends Comparable<T>> int search( - T[] array, - T key, - int left, - int right - ) { + private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right < left) { return -1; // this means that the key not found } @@ -71,12 +66,11 @@ public static void main(String[] args) { 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)]; @@ -84,15 +78,11 @@ public static void main(String[] args) { 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 aae8f58e438a..e2995747c9e8 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -1,11 +1,12 @@ package com.thealgorithms.searches; /* -To apply this method, the provided array must be strictly sorted. In this method, two pointers, one at 0th row -& the other at the last row are taken & the searching is done on the basis of the middle element of the middle column. -If that element is equal to target, its coordinates are returned, else if it is smaller than the target, the rows above -that element are ignored (because the elements above it will also be smaller than the target), else that element is -greater than the target, then the rows below it are ignored. +To apply this method, the provided array must be strictly sorted. In this method, two pointers, one +at 0th row & the other at the last row are taken & the searching is done on the basis of the middle +element of the middle column. If that element is equal to target, its coordinates are returned, else +if it is smaller than the target, the rows above that element are ignored (because the elements +above it will also be smaller than the target), else that element is greater than the target, then +the rows below it are ignored. */ public class BinarySearch2dArray { @@ -19,69 +20,55 @@ static int[] BinarySearch(int[][] arr, int target) { int startRow = 0, endRow = rowCount - 1, midCol = colCount / 2; while (startRow < endRow - 1) { - int midRow = startRow + (endRow - startRow) / 2; //getting the index of middle row + int midRow = startRow + (endRow - startRow) / 2; // getting the index of middle row if (arr[midRow][midCol] == target) { - return new int[] { midRow, midCol }; - } else if (arr[midRow][midCol] < target) startRow = - midRow; else endRow = midRow; + return new int[] {midRow, midCol}; + } else if (arr[midRow][midCol] < target) + startRow = midRow; + else + endRow = midRow; } /* - if the above search fails to find the target element, these conditions will be used to find the target - element, which further uses the binary search algorithm in the places which were left unexplored. + if the above search fails to find the target element, these conditions will be used to + find the target element, which further uses the binary search algorithm in the places + which were left unexplored. */ - if (arr[startRow][midCol] == target) return new int[] { - startRow, - midCol, - }; + if (arr[startRow][midCol] == target) + return new int[] { + startRow, + midCol, + }; - if (arr[endRow][midCol] == target) return new int[] { endRow, midCol }; + 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 - ); else return binarySearch( - arr, - target, - endRow, - midCol + 1, - colCount - 1 - ); + if (target <= arr[endRow][midCol - 1]) + return binarySearch(arr, target, endRow, 0, midCol - 1); + else + return binarySearch(arr, target, endRow, midCol + 1, colCount - 1); } - static int[] binarySearch( - int[][] arr, - int target, - int row, - int colStart, - int colEnd - ) { + static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) { while (colStart <= colEnd) { int midIndex = colStart + (colEnd - colStart) / 2; - if (arr[row][midIndex] == target) return new int[] { - row, - midIndex, - }; else if (arr[row][midIndex] < target) colStart = - midIndex + 1; else colEnd = midIndex - 1; + if (arr[row][midIndex] == target) + return new int[] { + row, + midIndex, + }; + else if (arr[row][midIndex] < target) + colStart = midIndex + 1; + else + colEnd = midIndex - 1; } - return new int[] { -1, -1 }; + return new int[] {-1, -1}; } } diff --git a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java index 94a3d55ffcd0..feb7cf295069 100644 --- a/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java +++ b/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java @@ -40,8 +40,7 @@ public static Optional<Node> search(final Node node, final String name) { return Optional.of(node); } - return node - .getSubNodes() + return node.getSubNodes() .stream() .map(value -> search(value, name)) .flatMap(Optional::stream) @@ -51,32 +50,22 @@ public static Optional<Node> search(final Node node, final String name) { 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) - ); + String.format("expected=%s but was actual=%s", expected, actual)); } } public static void main(final String[] args) { - final Node rootNode = new Node( - "A", + 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") - ) - ); + 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!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -85,7 +74,7 @@ public static void main(final String[] args) { final String expected = "G"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .orElseThrow(() -> new AssertionError("Node not found!")); assertThat(result.getName(), expected); } @@ -94,7 +83,7 @@ public static void main(final String[] args) { final String expected = "E"; final Node result = search(rootNode, expected) - .orElseThrow(() -> new AssertionError("Node not found!")); + .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 1b9accdca308..f3b868493978 100644 --- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java +++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java @@ -14,12 +14,11 @@ public static void main(String[] args) { 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)]; @@ -27,16 +26,12 @@ public static void main(String[] args) { 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 @@ -54,11 +49,6 @@ public <T extends Comparable<T>> int find(T[] array, T key) { range = range * 2; } - return Arrays.binarySearch( - array, - range / 2, - Math.min(range, array.length), - key - ); + return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key); } } diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java index bd4af6e528a8..041802cf40fc 100644 --- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java +++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java @@ -59,22 +59,14 @@ public <T extends Comparable<T>> int find(T[] array, T key) { // Driver Program public static void main(String[] args) { - Integer[] integers = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 }; + Integer[] integers = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; int size = integers.length; Integer shouldBeFound = 128; 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/HowManyTimesRotated.java b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java index df2d2e42bfd7..dea0db37b3e5 100644 --- a/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java +++ b/src/main/java/com/thealgorithms/searches/HowManyTimesRotated.java @@ -3,8 +3,8 @@ import java.util.*; /* - Problem Statement: - Given an array, find out how many times it has to been rotated + Problem Statement: + Given an array, find out how many times it has to been rotated from its initial sorted position. Input-Output: Eg. [11,12,15,18,2,5,6,8] @@ -12,14 +12,16 @@ (One rotation means putting the first element to the end) Note: The array cannot contain duplicates - Logic: + Logic: The position of the minimum element will give the number of times the array has been rotated from its initial sorted position. - Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations [6,8,11,12,15,18,2,5] and so on. - Finding the minimum element will take O(N) time but, we can use Binary Search to find the mimimum element, we can reduce the complexity to O(log N). - If we look at the rotated array, to identify the minimum element (say a[i]), we observe that a[i-1]>a[i]<a[i+1]. + Eg. For [2,5,6,8,11,12,15,18], 1 rotation gives [5,6,8,11,12,15,18,2], 2 rotations + [6,8,11,12,15,18,2,5] and so on. Finding the minimum element will take O(N) time but, we can use + Binary Search to find the mimimum element, we can reduce the complexity to O(log N). If we look + at the rotated array, to identify the minimum element (say a[i]), we observe that + a[i-1]>a[i]<a[i+1]. - Some other test cases: + Some other test cases: 1. [1,2,3,4] Number of rotations: 0 or 4(Both valid) 2. [15,17,2,3,5] Number of rotations: 3 */ @@ -33,9 +35,7 @@ public static void main(String[] args) { a[i] = sc.nextInt(); } - System.out.println( - "The array has been rotated " + rotated(a) + " times" - ); + System.out.println("The array has been rotated " + rotated(a) + " times"); sc.close(); } diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java index f982598da875..282e73095d86 100644 --- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java +++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java @@ -30,12 +30,8 @@ public int find(int[] array, int key) { 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) { @@ -58,11 +54,8 @@ public static void main(String[] args) { 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)]; @@ -70,15 +63,11 @@ public static void main(String[] args) { 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 cec8703bed1f..7fa6a37c87bb 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java @@ -58,11 +58,10 @@ public static void main(String[] args) { 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)]; @@ -70,15 +69,11 @@ public static void main(String[] args) { 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 933056987b4e..efff17c9d8df 100644 --- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java @@ -56,11 +56,10 @@ public static void main(String[] args) { 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)]; @@ -68,15 +67,11 @@ public static void main(String[] args) { 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/JumpSearch.java b/src/main/java/com/thealgorithms/searches/JumpSearch.java index 36bbb39370d0..f499cf8079cc 100644 --- a/src/main/java/com/thealgorithms/searches/JumpSearch.java +++ b/src/main/java/com/thealgorithms/searches/JumpSearch.java @@ -6,7 +6,7 @@ public class JumpSearch implements SearchAlgorithm { public static void main(String[] args) { JumpSearch jumpSearch = new JumpSearch(); - Integer[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + Integer[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < array.length; i++) { assert jumpSearch.find(array, i) == i; } diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java index c9b647fd3ed7..dd728d81bd23 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -22,7 +22,8 @@ int KMPSearch(String pat, String txt) { i++; } if (j == M) { - System.out.println("Found pattern " + "at index " + (i - j)); + System.out.println("Found pattern " + + "at index " + (i - j)); int index = (i - j); j = lps[j - 1]; return index; @@ -31,7 +32,10 @@ int KMPSearch(String pat, String txt) { else if (i < N && pat.charAt(j) != txt.charAt(i)) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway - if (j != 0) j = lps[j - 1]; else i = i + 1; + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; } } System.out.println("No pattern found"); diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java index 350cfc6e8861..94939518b68a 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearch.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java @@ -42,10 +42,8 @@ public static void main(String[] args) { 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)]; @@ -53,12 +51,7 @@ public static void main(String[] args) { 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/LinearSearchThread.java b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java index 98638ef4cbe1..c277b68f859b 100644 --- a/src/main/java/com/thealgorithms/searches/LinearSearchThread.java +++ b/src/main/java/com/thealgorithms/searches/LinearSearchThread.java @@ -29,9 +29,9 @@ public static void main(String[] args) { t1.join(); t2.join(); t3.join(); - } catch (InterruptedException e) {} - boolean found = - t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); + } catch (InterruptedException e) { + } + boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); System.out.println("Found = " + found); } } diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java index d800a6cc1db6..be0f1131ef6b 100644 --- a/src/main/java/com/thealgorithms/searches/LowerBound.java +++ b/src/main/java/com/thealgorithms/searches/LowerBound.java @@ -33,12 +33,11 @@ public static void main(String[] args) { 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; @@ -46,16 +45,12 @@ public static void main(String[] args) { 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); } /** @@ -78,12 +73,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private <T extends Comparable<T>> int search( - T[] array, - T key, - int left, - int right - ) { + private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java index 88c097b039ad..4ba8110c8452 100644 --- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java +++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java @@ -23,7 +23,8 @@ public class Node { int score; int visitCount; - public Node() {} + public Node() { + } public Node(Node parent, boolean isPlayersTurn) { this.parent = parent; @@ -78,9 +79,7 @@ public Node monteCarloTreeSearch(Node rootNode) { winnerNode = getWinnerNode(rootNode); printScores(rootNode); System.out.format( - "\nThe optimal node is: %02d\n", - rootNode.childNodes.indexOf(winnerNode) + 1 - ); + "\nThe optimal node is: %02d\n", rootNode.childNodes.indexOf(winnerNode) + 1); return winnerNode; } @@ -120,13 +119,10 @@ public Node getPromisingNode(Node rootNode) { 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; @@ -165,10 +161,8 @@ public void simulateRandomPlay(Node promisingNode) { 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; } @@ -177,22 +171,15 @@ public void simulateRandomPlay(Node promisingNode) { } public Node getWinnerNode(Node rootNode) { - return Collections.max( - rootNode.childNodes, - Comparator.comparing(c -> c.score) - ); + return Collections.max(rootNode.childNodes, Comparator.comparing(c -> c.score)); } public void printScores(Node rootNode) { 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/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java index 1ff560049e23..8ae304f6103f 100644 --- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java @@ -1,6 +1,6 @@ package com.thealgorithms.searches; -//URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/ +// URL: https://www.geeksforgeeks.org/order-agnostic-binary-search/ /* Order Agnostic Binary Search is an algorithm where we do not know whether the given sorted array is ascending or descending order. @@ -11,37 +11,36 @@ In the while loop, we use the two pointer method (start and end) to get the midd Depending upon the condition, respective statements will be executed and we will get our answer. */ - public class OrderAgnosticBinarySearch { - - static int BinSearchAlgo(int[] arr, int start, int end, int target) { - - // Checking whether the given array is ascending order - boolean AscOrd = arr[start] < arr[end]; - - while (start <= end) { - int middle = start + (end - start) / 2; - - // Check if the desired element is present at the middle position - if (arr[middle] == target) - return middle; // returns the index of the middle element - - // Ascending order - if (AscOrd) { - if (arr[middle] < target) - start = middle + 1; - else - end = middle - 1; - } - - // Descending order - else { - if (arr[middle] > target) - start = middle + 1; - else - end = middle - 1; - } - } - // Element is not present - return -1; - } - } +public class OrderAgnosticBinarySearch { + + static int BinSearchAlgo(int[] arr, int start, int end, int target) { + + // Checking whether the given array is ascending order + boolean AscOrd = arr[start] < arr[end]; + + while (start <= end) { + int middle = start + (end - start) / 2; + + // Check if the desired element is present at the middle position + if (arr[middle] == target) return middle; // returns the index of the middle element + + // Ascending order + if (AscOrd) { + if (arr[middle] < target) + start = middle + 1; + else + end = middle - 1; + } + + // Descending order + else { + if (arr[middle] > target) + start = middle + 1; + else + end = middle - 1; + } + } + // Element is not present + return -1; + } +} diff --git a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java index 416ddf6e1182..8ce01575b67d 100644 --- a/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/PerfectBinarySearch.java @@ -22,7 +22,7 @@ static int binarySearch(int[] arr, int target) { public static void main(String[] args) { PerfectBinarySearch BinarySearch = new PerfectBinarySearch(); - int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; assert BinarySearch.binarySearch(array, -1) == -1; assert BinarySearch.binarySearch(array, 11) == -1; } diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java index 9747a8179343..db8223e323ed 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -45,19 +45,12 @@ public static <T extends Comparable<T>> T select(List<T> list, int n) { return list.get(index); } - private static <T extends Comparable<T>> int selectIndex( - List<T> list, - int n - ) { + private static <T extends Comparable<T>> int selectIndex(List<T> list, int n) { return selectIndex(list, 0, list.size() - 1, n); } private static <T extends Comparable<T>> int selectIndex( - List<T> list, - int left, - int right, - int n - ) { + List<T> list, int left, int right, int n) { while (true) { if (left == right) return left; int pivotIndex = pivot(list, left, right); @@ -73,12 +66,7 @@ private static <T extends Comparable<T>> int selectIndex( } private static <T extends Comparable<T>> int partition( - List<T> list, - int left, - int right, - int pivotIndex, - int n - ) { + List<T> list, int left, int right, int pivotIndex, int n) { T pivotValue = list.get(pivotIndex); Collections.swap(list, pivotIndex, right); int storeIndex = left; @@ -104,11 +92,7 @@ private static <T extends Comparable<T>> int partition( return (n < storeIndex) ? storeIndex : Math.min(n, storeIndexEq); } - private static <T extends Comparable<T>> int pivot( - List<T> list, - int left, - int right - ) { + private static <T extends Comparable<T>> int pivot(List<T> list, int left, int right) { if (right - left < 5) { return partition5(list, left, right); } @@ -128,11 +112,7 @@ private static <T extends Comparable<T>> int pivot( return selectIndex(list, left, rightIndex, mid); } - private static <T extends Comparable<T>> int partition5( - List<T> list, - int left, - int right - ) { + private static <T extends Comparable<T>> int partition5(List<T> list, int left, int right) { List<T> ts = list.subList(left, right); ts.sort(Comparator.naturalOrder()); return (left + right) >>> 1; diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index cda1bfec051f..8343310d18bf 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -13,7 +13,7 @@ public class RabinKarpAlgorithm { q -> A prime number */ public int search(String pat, String txt, int q) { - int index = -1; //note: -1 here represent not found, it is not an index + int index = -1; // note: -1 here represent not found, it is not an index int M = pat.length(); int N = txt.length(); int i, j; diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index 3a672d7cd181..3b4b0b08377f 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -10,37 +10,38 @@ * {21, 31, 41, 51}} * * This array is sorted in both row and column manner. - * In this two pointers are taken, the first points to the 0th row and the second one points to end column, and then the - * element corresponding to the pointers placed in the array is compared with the target that either its equal, greater or - * smaller than the target. If the element is equal to the target, the co-ordinates of that element is returned i.e. an - * array of the two pointers will be returned, else if the target is greater than corresponding element then the pointer - * pointing to the 0th row will be incremented by 1, else if the target is lesser than the corresponding element then the - * pointer pointing to the end column will be decremented by 1. And if the element doesn't exist in the array, an array + * In this two pointers are taken, the first points to the 0th row and the second one points to end + * column, and then the element corresponding to the pointers placed in the array is compared with + * the target that either its equal, greater or smaller than the target. If the element is equal to + * the target, the co-ordinates of that element is returned i.e. an array of the two pointers will + * be returned, else if the target is greater than corresponding element then the pointer pointing + * to the 0th row will be incremented by 1, else if the target is lesser than the corresponding + * element then the pointer pointing to the end column will be decremented by 1. And if the element + * doesn't exist in the array, an array * {-1, -1} will be returned. */ -public class RowColumnWiseSorted2dArrayBinarySearch - implements MatrixSearchAlgorithm { +public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { - @Override - public <T extends Comparable<T>> int[] find(T[][] matrix, T key) { - return search(matrix, key); - } + @Override + public <T extends Comparable<T>> int[] find(T[][] matrix, T key) { + return search(matrix, key); + } - public static <T extends Comparable<T>> int[] search(T[][] matrix, T target) { - int rowPointer = 0; //The pointer at 0th row - int colPointer = matrix.length - 1; //The pointer at end column + public static <T extends Comparable<T>> int[] search(T[][] matrix, T target) { + int rowPointer = 0; // The pointer at 0th row + int colPointer = matrix.length - 1; // The pointer at end column - while (rowPointer < matrix.length && colPointer >= 0) { - int comp = target.compareTo(matrix[rowPointer][colPointer]); + while (rowPointer < matrix.length && colPointer >= 0) { + int comp = target.compareTo(matrix[rowPointer][colPointer]); - if (comp == 0) { - return new int[] { rowPointer, colPointer }; - } else if (comp > 0) { - rowPointer++; //Incrementing the row pointer if the target is greater - } else { - colPointer--; //Decrementing the column pointer if the target is lesser - } + if (comp == 0) { + return new int[] {rowPointer, colPointer}; + } else if (comp > 0) { + rowPointer++; // Incrementing the row pointer if the target is greater + } else { + colPointer--; // Decrementing the column pointer if the target is lesser + } + } + return new int[] {-1, -1}; // The not found condition } - return new int[] { -1, -1 }; //The not found condition - } } diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 44d38a480dd6..4e5939d6b2b8 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -30,7 +30,7 @@ public class SaddlebackSearch { */ private static int[] find(int[][] arr, int row, int col, int key) { // array to store the answer row and column - int[] ans = { -1, -1 }; + int[] ans = {-1, -1}; if (row < 0 || col >= arr[row].length) { return ans; } diff --git a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java index c92569cf1086..b173f66598fb 100644 --- a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java +++ b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java @@ -17,7 +17,7 @@ public int[] search(int[][] matrix, int value) { int i = 0; // This variable iterates over columns int j = n - 1; - int[] result = { -1, -1 }; + int[] result = {-1, -1}; while (i < n && j >= 0) { if (matrix[i][j] == value) { @@ -30,7 +30,6 @@ public int[] search(int[][] matrix, int value) { } else { j--; } - } return result; } diff --git a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java index 5b305831bdfa..b8ee476bfcd9 100644 --- a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java @@ -23,9 +23,7 @@ public class SquareRootBinarySearch { */ public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.print( - "Enter a number you want to calculate square root of : " - ); + System.out.print("Enter a number you want to calculate square root of : "); int num = sc.nextInt(); long ans = squareRoot(num); System.out.println("The square root is : " + ans); diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java index 5b447fa4912f..e79f0e666a83 100644 --- a/src/main/java/com/thealgorithms/searches/TernarySearch.java +++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java @@ -39,12 +39,7 @@ public <T extends Comparable<T>> int find(T[] arr, T value) { * @param end The ending index till which we will Search. * @return Returns the index of the Element if found. Else returns -1. */ - private <T extends Comparable<T>> int ternarySearch( - T[] arr, - T key, - int start, - int end - ) { + private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) { if (start > end) { return -1; } @@ -57,15 +52,11 @@ private <T extends Comparable<T>> int ternarySearch( return mid1; } else if (key.compareTo(arr[mid2]) == 0) { return mid2; - } /* Search the first (1/3) rd part of the array.*/else if ( - key.compareTo(arr[mid1]) < 0 - ) { + } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) { return ternarySearch(arr, key, start, --mid1); - } /* Search 3rd (1/3)rd part of the array */else if ( - key.compareTo(arr[mid2]) > 0 - ) { + } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) { return ternarySearch(arr, key, ++mid2, end); - } /* Search middle (1/3)rd part of the array */else { + } /* Search middle (1/3)rd part of the array */ else { return ternarySearch(arr, key, mid1, mid2); } } @@ -75,11 +66,10 @@ public static void main(String[] args) { 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)]; @@ -87,15 +77,11 @@ public static void main(String[] args) { 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/UnionFind.java b/src/main/java/com/thealgorithms/searches/UnionFind.java index ec0a694bb282..d32e4fd3ec1f 100644 --- a/src/main/java/com/thealgorithms/searches/UnionFind.java +++ b/src/main/java/com/thealgorithms/searches/UnionFind.java @@ -61,27 +61,19 @@ public String toString() { // Tests public static void main(String[] args) { UnionFind uf = new UnionFind(5); - System.out.println( - "init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):" - ); + System.out.println("init /w 5 (should print 'p [0, 1, 2, 3, 4] r [0, 0, 0, 0, 0]'):"); System.out.println(uf); uf.union(1, 2); - System.out.println( - "union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):" - ); + System.out.println("union 1 2 (should print 'p [0, 1, 1, 3, 4] r [0, 1, 0, 0, 0]'):"); System.out.println(uf); uf.union(3, 4); - System.out.println( - "union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" - ); + System.out.println("union 3 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); System.out.println(uf); uf.find(4); - System.out.println( - "find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):" - ); + System.out.println("find 4 (should print 'p [0, 1, 1, 3, 3] r [0, 1, 0, 1, 0]'):"); System.out.println(uf); System.out.println("count (should print '3'):"); diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java index 1c842fbccb0a..cddd3cb8bf8c 100644 --- a/src/main/java/com/thealgorithms/searches/UpperBound.java +++ b/src/main/java/com/thealgorithms/searches/UpperBound.java @@ -33,12 +33,11 @@ public static void main(String[] args) { 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; @@ -46,16 +45,12 @@ public static void main(String[] args) { 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); } /** @@ -78,12 +73,7 @@ public <T extends Comparable<T>> int find(T[] array, T key) { * @param right The upper bound * @return the location of the key */ - private <T extends Comparable<T>> int search( - T[] array, - T key, - int left, - int right - ) { + private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) { if (right <= left) { return left; } diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java index eb62555f5497..c21e307cfb40 100644 --- a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java @@ -1,31 +1,29 @@ package com.thealgorithms.searches; import java.util.*; public class sortOrderAgnosticBinarySearch { - public static int find(int[] arr, int key){ + 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. - while(start<=end){ - int mid = end-start/2; - if (arr[mid]==key){ + int end = arr.length - 1; + 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) { return mid; } - if(arrDescending){ // boolean is true then our array is in descending order - if(key<arr[mid]){ - start=mid+1; + if (arrDescending) { // boolean is true then our array is in descending order + if (key < arr[mid]) { + start = mid + 1; + } else { + end = mid - 1; } - else{ - end=mid-1; + } else { // otherwise our array is in ascending order + if (key > arr[mid]) { + start = mid + 1; + } else { + end = mid - 1; } } - else { // otherwise our array is in ascending order - if(key>arr[mid]){ - start=mid+1; - } - else{ - end=mid-1; - } - } } return -1; } diff --git a/src/main/java/com/thealgorithms/sorts/BeadSort.java b/src/main/java/com/thealgorithms/sorts/BeadSort.java index cd60ab0b585f..101a5c50af6d 100644 --- a/src/main/java/com/thealgorithms/sorts/BeadSort.java +++ b/src/main/java/com/thealgorithms/sorts/BeadSort.java @@ -1,41 +1,40 @@ package com.thealgorithms.sorts; - -//BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort -//BeadSort can't sort negative number, Character, String. It can sort positive number only +// BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort +// BeadSort can't sort negative number, Character, String. It can sort positive number only public class BeadSort { public int[] sort(int[] unsorted) { - int[] sorted = new int[unsorted.length]; - int max = 0; - for(int i = 0; i < unsorted.length; i++) { - max = Math.max(max, unsorted[i]); - } + int[] sorted = new int[unsorted.length]; + int max = 0; + for (int i = 0; i < unsorted.length; i++) { + max = Math.max(max, unsorted[i]); + } - char[][] grid = new char[unsorted.length][max]; - int[] count = new int[max]; + char[][] grid = new char[unsorted.length][max]; + int[] count = new int[max]; - for(int i = 0; i < unsorted.length; i++) { - for(int j = 0; j < max; j++) { - grid[i][j] = '-'; - } - } + for (int i = 0; i < unsorted.length; i++) { + for (int j = 0; j < max; j++) { + grid[i][j] = '-'; + } + } - for(int i = 0; i < max; i++) { - count[i] = 0; - } + for (int i = 0; i < max; i++) { + count[i] = 0; + } - for(int i = 0; i < unsorted.length; i++) { + for (int i = 0; i < unsorted.length; i++) { int k = 0; - for(int j = 0; j < unsorted[i]; j++) { + for (int j = 0; j < unsorted[i]; j++) { grid[count[max - k - 1]++][k] = '*'; k++; - } + } } - for(int i = 0; i < unsorted.length; i++) { + for (int i = 0; i < unsorted.length; i++) { int k = 0; - for(int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) { + for (int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) { k++; } sorted[i] = k; diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java index 414aa647eb50..346d860508ca 100644 --- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java +++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java @@ -69,7 +69,7 @@ static void printArray(int[] arr) { } public static void main(String[] args) { - int[] a = { 3, 7, 4, 8, 6, 2, 1, 5 }; + int[] a = {3, 7, 4, 8, 6, 2, 1, 5}; int up = 1; BitonicSort ob = new BitonicSort(); ob.sort(a, a.length, up); diff --git a/src/main/java/com/thealgorithms/sorts/BogoSort.java b/src/main/java/com/thealgorithms/sorts/BogoSort.java index 26a2a3a16463..75f1e84367c3 100644 --- a/src/main/java/com/thealgorithms/sorts/BogoSort.java +++ b/src/main/java/com/thealgorithms/sorts/BogoSort.java @@ -39,7 +39,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; BogoSort bogoSort = new BogoSort(); @@ -47,7 +47,7 @@ public static void main(String[] args) { SortUtils.print(bogoSort.sort(integers)); // String Input - String[] strings = { "c", "a", "e", "b", "d" }; + String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(bogoSort.sort(strings)); } diff --git a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java index c95f549a180f..10197969e853 100644 --- a/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java +++ b/src/main/java/com/thealgorithms/sorts/BubbleSortRecursion.java @@ -41,10 +41,7 @@ public <T extends Comparable<T>> T[] sort(T[] unsorted) { * @param unsorted array contains elements * @param len length of given array */ - private static <T extends Comparable<T>> void bubbleSort( - T[] unsorted, - int len - ) { + private static <T extends Comparable<T>> void bubbleSort(T[] unsorted, int len) { boolean swapped = false; /* flag to check if array is sorted or not */ for (int i = 0; i < len - 1; ++i) { diff --git a/src/main/java/com/thealgorithms/sorts/BucketSort.java b/src/main/java/com/thealgorithms/sorts/BucketSort.java index f2288479e8b5..184e36f04db6 100644 --- a/src/main/java/com/thealgorithms/sorts/BucketSort.java +++ b/src/main/java/com/thealgorithms/sorts/BucketSort.java @@ -67,7 +67,7 @@ public static int[] bucketSort(int[] arr) { arr[index++] = value; } } - + return arr; } diff --git a/src/main/java/com/thealgorithms/sorts/CircleSort.java b/src/main/java/com/thealgorithms/sorts/CircleSort.java index 3d013c88e1b7..74b3fc62125d 100644 --- a/src/main/java/com/thealgorithms/sorts/CircleSort.java +++ b/src/main/java/com/thealgorithms/sorts/CircleSort.java @@ -10,7 +10,8 @@ public class CircleSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] array) { int n = array.length; - while (doSort(array, 0, n - 1)); + while (doSort(array, 0, n - 1)) + ; return array; } @@ -19,11 +20,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { * @param the left boundary of the part currently being sorted * @param the right boundary of the part currently being sorted */ - private <T extends Comparable<T>> Boolean doSort( - T[] array, - int left, - int right - ) { + private <T extends Comparable<T>> Boolean doSort(T[] array, int left, int right) { boolean swapped = false; if (left == right) { @@ -58,13 +55,13 @@ private <T extends Comparable<T>> Boolean doSort( public static void main(String[] args) { CircleSort CSort = new CircleSort(); - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; CSort.sort(arr); for (int i = 0; i < arr.length - 1; ++i) { assert arr[i] <= arr[i + 1]; } - String[] stringArray = { "c", "a", "e", "b", "d" }; + String[] stringArray = {"c", "a", "e", "b", "d"}; CSort.sort(stringArray); for (int i = 0; i < stringArray.length - 1; ++i) { assert arr[i].compareTo(arr[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java index 474fa3d79cd3..dc3a9a100fa0 100644 --- a/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java +++ b/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java @@ -43,14 +43,14 @@ public <T extends Comparable<T>> T[] sort(T[] array) { // Driver Program public static void main(String[] args) { // Integer Input - Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; CocktailShakerSort shakerSort = new CocktailShakerSort(); // Output => 1 4 6 9 12 23 54 78 231 SortUtils.print(shakerSort.sort(integers)); // String Input - String[] strings = { "c", "a", "e", "b", "d" }; + String[] strings = {"c", "a", "e", "b", "d"}; SortUtils.print(shakerSort.sort(strings)); } } diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java index 570fd3e83b94..11c2ce183e17 100644 --- a/src/main/java/com/thealgorithms/sorts/CountingSort.java +++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java @@ -53,25 +53,20 @@ public <T extends Comparable<T>> List<T> sort(List<T> list) { * @param list The list to be sorted */ private static <T extends Comparable<T>> List<T> streamSort(List<T> list) { - return list - .stream() + 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()) - ) + .flatMap( + entry -> IntStream.rangeClosed(1, entry.getValue()).mapToObj(t -> entry.getKey())) .collect(toList()); } // Driver Program public static void main(String[] args) { // Integer Input - List<Integer> unsortedInts = Stream - .of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12) - .collect(toList()); + List<Integer> 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:"); @@ -86,9 +81,8 @@ public static void main(String[] args) { System.out.println("\n------------------------------\n"); // String Input - List<String> unsortedStrings = Stream - .of("c", "a", "e", "b", "d", "a", "f", "g", "c") - .collect(toList()); + List<String> 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/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java index 4c4520c63cab..7e18b657973f 100644 --- a/src/main/java/com/thealgorithms/sorts/DNFSort.java +++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java @@ -10,26 +10,24 @@ static void sort012(int[] a, int arr_size) { int mid = 0, temp = 0; while (mid <= high) { switch (a[mid]) { - case 0: - { - temp = a[low]; - a[low] = a[mid]; - a[mid] = temp; - low++; - mid++; - break; - } - case 1: - mid++; - break; - case 2: - { - temp = a[mid]; - a[mid] = a[high]; - a[high] = temp; - high--; - break; - } + case 0: { + temp = a[low]; + a[low] = a[mid]; + a[mid] = temp; + low++; + mid++; + break; + } + case 1: + mid++; + break; + case 2: { + temp = a[mid]; + a[mid] = a[high]; + a[high] = temp; + high--; + break; + } } } } @@ -44,7 +42,7 @@ static void printArray(int[] arr, int arr_size) { /*Driver function to check for above functions*/ public static void main(String[] args) { - int[] arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; + int[] arr = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java index 69a09e67532d..6fabddcb42eb 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -2,7 +2,7 @@ /** * Dual Pivot Quick Sort Algorithm - * + * * @author Debasish Biswas (https://github.com/debasishbsws) * * @see SortAlgorithm */ @@ -26,7 +26,8 @@ public <T extends Comparable<T>> T[] sort(T[] array) { * @param right The last index of an array * @param array The array to be sorted */ - private static <T extends Comparable<T>> void dualPivotQuicksort(T[] array, int left, int right) { + private static <T extends Comparable<T>> void dualPivotQuicksort( + T[] array, int left, int right) { if (left < right) { int[] pivots = partition(array, left, right); @@ -44,8 +45,7 @@ private static <T extends Comparable<T>> void dualPivotQuicksort(T[] array, int * @param right The last index of an array Finds the partition index of an array */ private static <T extends Comparable<T>> int[] partition(T[] array, int left, int right) { - if (array[left].compareTo(array[right]) > 0) - swap(array, left, right); + if (array[left].compareTo(array[right]) > 0) swap(array, left, right); T pivot1 = array[left]; T pivot2 = array[right]; @@ -62,14 +62,11 @@ private static <T extends Comparable<T>> int[] partition(T[] array, int left, in // If element is greater or equal to pivot2 else if (array[less].compareTo(pivot2) >= 0) { - while (less < great && array[great].compareTo(pivot2) > 0) - great--; + while (less < great && array[great].compareTo(pivot2) > 0) great--; swap(array, less, great--); - if (array[less].compareTo(pivot1) < 0) - swap(array, less, left++); - + if (array[less].compareTo(pivot1) < 0) swap(array, less, left++); } less++; @@ -81,7 +78,7 @@ else if (array[less].compareTo(pivot2) >= 0) { swap(array, right, great); // return the pivots' indices - return new int[] { less, great }; + return new int[] {less, great}; } private static <T extends Comparable<T>> void swap(T[] array, int left, int right) { @@ -96,7 +93,7 @@ private static <T extends Comparable<T>> void swap(T[] array, int left, int righ * @param args the command line arguments */ public static void main(String[] args) { - Integer[] array = { 24, 8, -42, 75, -29, -77, 38, 57 }; + Integer[] array = {24, 8, -42, 75, -29, -77, 38, 57}; DualPivotQuickSort dualPivotQuickSort = new DualPivotQuickSort(); dualPivotQuickSort.sort(array); for (int i = 0; i < array.length; i++) { @@ -107,5 +104,4 @@ public static void main(String[] args) { /* * References: https://www.geeksforgeeks.org/dual-pivot-quicksort/ */ - } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java index 5a2c8a01d09f..123f22d82393 100644 --- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java +++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java @@ -1,34 +1,27 @@ package com.thealgorithms.sorts; /** - * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined by a value given - * as the indented middle. - * First permutation: values less than middle. - * Second permutation: values equal middle. - * Third permutation: values greater than middle. - * If no indented middle is given, this implementation will use a value from the given Array. - * This value is the one positioned in the arrays' middle if the arrays' length is odd. - * If the arrays' length is even, the value left to the middle will be used. - * More information and Pseudocode: https://en.wikipedia.org/wiki/Dutch_national_flag_problem + * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined + * by a value given as the indented middle. First permutation: values less than middle. Second + * permutation: values equal middle. Third permutation: values greater than middle. If no indented + * middle is given, this implementation will use a value from the given Array. This value is the one + * positioned in the arrays' middle if the arrays' length is odd. If the arrays' length is even, the + * value left to the middle will be used. More information and Pseudocode: + * https://en.wikipedia.org/wiki/Dutch_national_flag_problem */ public class DutchNationalFlagSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] unsorted) { return dutch_national_flag_sort( - unsorted, - unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1] - ); + unsorted, unsorted[(int) Math.ceil((unsorted.length) / 2.0) - 1]); } public <T extends Comparable<T>> T[] sort(T[] unsorted, T intendedMiddle) { return dutch_national_flag_sort(unsorted, intendedMiddle); } - private <T extends Comparable<T>> T[] dutch_national_flag_sort( - T[] arr, - T intendedMiddle - ) { + private <T extends Comparable<T>> T[] dutch_national_flag_sort(T[] arr, T intendedMiddle) { int i = 0; int j = 0; int k = arr.length - 1; diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index e9031cb96d64..c74ff316bca9 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -1,9 +1,9 @@ package com.thealgorithms.sorts; -import java.util.function.Function; - import static com.thealgorithms.sorts.SortUtils.*; +import java.util.function.Function; + class InsertionSort implements SortAlgorithm { /** @@ -40,14 +40,12 @@ public <T extends Comparable<T>> T[] sort(T[] array, int lo, int hi) { public <T extends Comparable<T>> T[] sentinelSort(T[] array) { int minElemIndex = 0; int n = array.length; - if (n < 1) - return array; + if (n < 1) return array; // put the smallest element to the 0 position as a sentinel, which will allow us to avoid // redundant comparisons like `j > 0` further for (int i = 1; i < n; i++) - if (less(array[i], array[minElemIndex])) - minElemIndex = i; + if (less(array[i], array[minElemIndex])) minElemIndex = i; swap(array, 0, minElemIndex); for (int i = 2; i < n; i++) { @@ -77,15 +75,17 @@ public static void main(String[] args) { 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); + insertionTime / insertionSentinelTime); } - private static double measureApproxExecTime(Function<Double[], Double[]> sortAlgorithm, Double[] randomArray) { + private static double measureApproxExecTime( + Function<Double[], Double[]> sortAlgorithm, Double[] randomArray) { long start = System.currentTimeMillis(); sortAlgorithm.apply(randomArray); long end = System.currentTimeMillis(); diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java index 07f03cca072d..e679fa9f03e7 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -1,4 +1,5 @@ -/** Author : Siddhant Swarup Mallick +/** + * Author : Siddhant Swarup Mallick * Github : https://github.com/siddhant2002 */ @@ -21,86 +22,86 @@ public static boolean isSorted(int[] p, int option) { // Choice is choosed as any number from 1 to 3 (So the linked list will be // sorted by Merge sort technique/Insertion sort technique/Heap sort technique) switch (ch) { - case 1: - Task nm = new Task(); - Node start = null, prev = null, fresh, ptr; - for (int i = 0; i < a.length; i++) { - // New nodes are created and values are added - fresh = new Node(); // Node class is called - fresh.val = a[i]; // Node val is stored - if (start == null) - start = fresh; - else - prev.next = fresh; - prev = fresh; - } - start = nm.sortByMergeSort(start); - // method is being called - int i = 0; - for (ptr = start; ptr != null; ptr = ptr.next) { - a[i++] = ptr.val; - // storing the sorted values in the array - } - Arrays.sort(b); - // array b is sorted and it will return true when checked with sorted list - LinkListSort uu = new LinkListSort(); - return uu.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - case 2: - Node start1 = null, prev1 = null, fresh1, ptr1; - for (int i1 = 0; i1 < a.length; i1++) { - // New nodes are created and values are added - fresh1 = new Node(); // New node is created - fresh1.val = a[i1]; // Value is stored in the value part of the node - if (start1 == null) - start1 = fresh1; - else - prev1.next = fresh1; - prev1 = fresh1; - } - Task1 kk = new Task1(); - start1 = kk.sortByInsertionSort(start1); - // method is being called - int i1 = 0; - for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { - a[i1++] = ptr1.val; - // storing the sorted values in the array - } - LinkListSort uu1 = new LinkListSort(); - // array b is not sorted and it will return false when checked with sorted list - return uu1.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - case 3: - Task2 mm = new Task2(); - Node start2 = null, prev2 = null, fresh2, ptr2; - for (int i2 = 0; i2 < a.length; i2++) { - // New nodes are created and values are added - fresh2 = new Node(); // Node class is created - fresh2.val = a[i2]; // Value is stored in the value part of the Node - if (start2 == null) - start2 = fresh2; - else - prev2.next = fresh2; - prev2 = fresh2; - } - start2 = mm.sortByHeapSort(start2); - // method is being called - int i3 = 0; - for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { - a[i3++] = ptr2.val; - // storing the sorted values in the array - } - Arrays.sort(b); - // array b is sorted and it will return true when checked with sorted list - LinkListSort uu2 = new LinkListSort(); - return uu2.compare(a, b); - // The given array and the expected array is checked if both are same then true - // is displayed else false is displayed - default: - // default is used incase user puts a unauthorized value - System.out.println("Wrong choice"); + case 1: + Task nm = new Task(); + Node start = null, prev = null, fresh, ptr; + for (int i = 0; i < a.length; i++) { + // New nodes are created and values are added + fresh = new Node(); // Node class is called + fresh.val = a[i]; // Node val is stored + if (start == null) + start = fresh; + else + prev.next = fresh; + prev = fresh; + } + start = nm.sortByMergeSort(start); + // method is being called + int i = 0; + for (ptr = start; ptr != null; ptr = ptr.next) { + a[i++] = ptr.val; + // storing the sorted values in the array + } + Arrays.sort(b); + // array b is sorted and it will return true when checked with sorted list + LinkListSort uu = new LinkListSort(); + return uu.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + case 2: + Node start1 = null, prev1 = null, fresh1, ptr1; + for (int i1 = 0; i1 < a.length; i1++) { + // New nodes are created and values are added + fresh1 = new Node(); // New node is created + fresh1.val = a[i1]; // Value is stored in the value part of the node + if (start1 == null) + start1 = fresh1; + else + prev1.next = fresh1; + prev1 = fresh1; + } + Task1 kk = new Task1(); + start1 = kk.sortByInsertionSort(start1); + // method is being called + int i1 = 0; + for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) { + a[i1++] = ptr1.val; + // storing the sorted values in the array + } + LinkListSort uu1 = new LinkListSort(); + // array b is not sorted and it will return false when checked with sorted list + return uu1.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + case 3: + Task2 mm = new Task2(); + Node start2 = null, prev2 = null, fresh2, ptr2; + for (int i2 = 0; i2 < a.length; i2++) { + // New nodes are created and values are added + fresh2 = new Node(); // Node class is created + fresh2.val = a[i2]; // Value is stored in the value part of the Node + if (start2 == null) + start2 = fresh2; + else + prev2.next = fresh2; + prev2 = fresh2; + } + start2 = mm.sortByHeapSort(start2); + // method is being called + int i3 = 0; + for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) { + a[i3++] = ptr2.val; + // storing the sorted values in the array + } + Arrays.sort(b); + // array b is sorted and it will return true when checked with sorted list + LinkListSort uu2 = new LinkListSort(); + return uu2.compare(a, b); + // The given array and the expected array is checked if both are same then true + // is displayed else false is displayed + default: + // default is used incase user puts a unauthorized value + System.out.println("Wrong choice"); } // Switch case is used to call the classes as per the user requirement return false; @@ -108,8 +109,7 @@ public static boolean isSorted(int[] p, int option) { boolean compare(int[] a, int[] b) { for (int i = 0; i < a.length; i++) { - if (a[i] != b[i]) - return false; + if (a[i] != b[i]) return false; } return true; // Both the arrays are checked for equalness. If both are equal then true is @@ -140,8 +140,7 @@ class Task { static int[] a; public Node sortByMergeSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); a = new int[c]; // Array of size c is created @@ -207,8 +206,7 @@ void task1(int[] n, int s, int m, int e) { class Task1 { public Node sortByInsertionSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); int[] a = new int[c]; // Array of size c is created @@ -250,8 +248,7 @@ class Task2 { static int[] a; public Node sortByHeapSort(Node head) { - if (head == null || head.next == null) - return head; + if (head == null || head.next == null) return head; int c = count(head); a = new int[c]; // Array of size c is created @@ -298,10 +295,8 @@ void task1(int[] n, int k, int i) { int p = i; int l = 2 * i + 1; int r = 2 * i + 2; - if (l < k && n[l] > n[p]) - p = l; - if (r < k && n[r] > n[p]) - p = r; + if (l < k && n[l] > n[p]) p = l; + if (r < k && n[r] > n[p]) p = r; if (p != i) { int d = n[p]; n[p] = n[i]; diff --git a/src/main/java/com/thealgorithms/sorts/MergeSort.java b/src/main/java/com/thealgorithms/sorts/MergeSort.java index 7c9bf9eb59d2..0950b46891ce 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSort.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSort.java @@ -9,8 +9,7 @@ */ class MergeSort implements SortAlgorithm { - @SuppressWarnings("rawtypes") - private static Comparable[] aux; + @SuppressWarnings("rawtypes") private static Comparable[] aux; /** * Generic merge sort algorithm implements. diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java index c06528608278..92405d3dd9dc 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java @@ -13,7 +13,8 @@ public static void call_merge_sort(int[] a, int n) { 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); @@ -22,13 +23,8 @@ public static void merge_sort(int[] a, int start, int end, int maxele) { //this } } - public static void implement_merge_sort( - int[] a, - int start, - int mid, - int end, - int maxele - ) { //implementation of mergesort + public static void implement_merge_sort(int[] a, int start, int mid, int end, + int maxele) { // implementation of mergesort int i = start; int j = mid + 1; int k = start; diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java index 902507abc419..9d4a5871dc87 100644 --- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java +++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java @@ -34,10 +34,7 @@ private static List<Integer> merge(List<Integer> arr) { return sort(arrA, arrB); } - private static List<Integer> sort( - List<Integer> unsortedA, - List<Integer> unsortedB - ) { + private static List<Integer> sort(List<Integer> unsortedA, List<Integer> unsortedB) { if (unsortedA.size() <= 0 && unsortedB.size() <= 0) { return new ArrayList<>(); } @@ -49,23 +46,15 @@ private static List<Integer> sort( } if (unsortedA.get(0) <= unsortedB.get(0)) { List<Integer> newAl = new ArrayList<Integer>() { - { - add(unsortedA.get(0)); - } + { add(unsortedA.get(0)); } }; - newAl.addAll( - sort(unsortedA.subList(1, unsortedA.size()), unsortedB) - ); + newAl.addAll(sort(unsortedA.subList(1, unsortedA.size()), unsortedB)); return newAl; } else { List<Integer> newAl = new ArrayList<Integer>() { - { - add(unsortedB.get(0)); - } + { add(unsortedB.get(0)); } }; - newAl.addAll( - sort(unsortedA, unsortedB.subList(1, unsortedB.size())) - ); + newAl.addAll(sort(unsortedA, unsortedB.subList(1, unsortedB.size()))); return newAl; } } @@ -75,8 +64,7 @@ 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)) - ); + 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/OddEvenSort.java b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java index e6fe5e6cade5..b5213792d12d 100644 --- a/src/main/java/com/thealgorithms/sorts/OddEvenSort.java +++ b/src/main/java/com/thealgorithms/sorts/OddEvenSort.java @@ -19,7 +19,7 @@ public static void main(String[] args) { oddEvenSort(arr); - //Print Sorted elements + // Print Sorted elements for (int i = 0; i < arr.length - 1; ++i) { System.out.println(arr[i]); assert arr[i] <= arr[i + 1]; diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java index ce1aa7746b02..cd399fb701cb 100644 --- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -39,7 +39,7 @@ void sort(Integer[] array) { public static void main(String[] args) { PigeonholeSort pigeonholeSort = new PigeonholeSort(); - Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 }; + Integer[] arr = {8, 3, 2, 7, 4, 6, 8}; System.out.print("Unsorted order is : "); print(arr); diff --git a/src/main/java/com/thealgorithms/sorts/QuickSort.java b/src/main/java/com/thealgorithms/sorts/QuickSort.java index c0fe66e24565..2842b08a975c 100644 --- a/src/main/java/com/thealgorithms/sorts/QuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/QuickSort.java @@ -27,11 +27,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { * @param right The last index of an array * @param array The array to be sorted */ - private static <T extends Comparable<T>> void doSort( - T[] array, - int left, - int right - ) { + private static <T extends Comparable<T>> void doSort(T[] array, int left, int right) { if (left < right) { int pivot = randomPartition(array, left, right); doSort(array, left, pivot - 1); @@ -47,11 +43,7 @@ private static <T extends Comparable<T>> void doSort( * @param right The last index of an array * @return the partition index of the array */ - private static <T extends Comparable<T>> int randomPartition( - T[] array, - int left, - int right - ) { + private static <T extends Comparable<T>> int randomPartition(T[] array, int left, int right) { int randomIndex = left + (int) (Math.random() * (right - left + 1)); swap(array, randomIndex, right); return partition(array, left, right); @@ -65,11 +57,7 @@ private static <T extends Comparable<T>> int randomPartition( * @param right The last index of an array Finds the partition index of an * array */ - private static <T extends Comparable<T>> int partition( - T[] array, - int left, - int right - ) { + private static <T extends Comparable<T>> int partition(T[] array, int left, int right) { int mid = (left + right) >>> 1; T pivot = array[mid]; diff --git a/src/main/java/com/thealgorithms/sorts/RadixSort.java b/src/main/java/com/thealgorithms/sorts/RadixSort.java index 93d579142501..d2090bf86646 100644 --- a/src/main/java/com/thealgorithms/sorts/RadixSort.java +++ b/src/main/java/com/thealgorithms/sorts/RadixSort.java @@ -53,7 +53,7 @@ static void print(int[] arr, int n) { } public static void main(String[] args) { - int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; + int[] arr = {170, 45, 75, 90, 802, 24, 2, 66}; int n = arr.length; radixsort(arr, n); print(arr, n); diff --git a/src/main/java/com/thealgorithms/sorts/SelectionSort.java b/src/main/java/com/thealgorithms/sorts/SelectionSort.java index 3c4dfe250ebb..555b4b6037dc 100644 --- a/src/main/java/com/thealgorithms/sorts/SelectionSort.java +++ b/src/main/java/com/thealgorithms/sorts/SelectionSort.java @@ -32,14 +32,14 @@ public <T extends Comparable<T>> T[] sort(T[] arr) { * Driver Code */ public static void main(String[] args) { - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; SelectionSort selectionSort = new SelectionSort(); Integer[] sorted = selectionSort.sort(arr); for (int i = 0; i < sorted.length - 1; ++i) { assert sorted[i] <= sorted[i + 1]; } - String[] strings = { "c", "a", "e", "b", "d" }; + String[] strings = {"c", "a", "e", "b", "d"}; String[] sortedStrings = selectionSort.sort(strings); for (int i = 0; i < sortedStrings.length - 1; ++i) { assert strings[i].compareTo(strings[i + 1]) <= 0; diff --git a/src/main/java/com/thealgorithms/sorts/ShellSort.java b/src/main/java/com/thealgorithms/sorts/ShellSort.java index fe2c387fc8c1..5f41a5440388 100644 --- a/src/main/java/com/thealgorithms/sorts/ShellSort.java +++ b/src/main/java/com/thealgorithms/sorts/ShellSort.java @@ -36,7 +36,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { /* Driver Code */ public static void main(String[] args) { - Integer[] toSort = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; ShellSort sort = new ShellSort(); sort.sort(toSort); diff --git a/src/main/java/com/thealgorithms/sorts/SimpleSort.java b/src/main/java/com/thealgorithms/sorts/SimpleSort.java index 1255f3929300..138ebb62937d 100644 --- a/src/main/java/com/thealgorithms/sorts/SimpleSort.java +++ b/src/main/java/com/thealgorithms/sorts/SimpleSort.java @@ -23,7 +23,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { public static void main(String[] args) { // ==== Int ======= - Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; + Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; System.out.print("unsorted: "); print(a); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java index 85886b743973..7a3ded37bf3f 100644 --- a/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java +++ b/src/main/java/com/thealgorithms/sorts/SortAlgorithm.java @@ -24,9 +24,7 @@ public interface SortAlgorithm { * @return a sorted list */ @SuppressWarnings("unchecked") - default <T extends Comparable<T>> List<T> sort(List<T> unsorted) { - return Arrays.asList( - sort(unsorted.toArray((T[]) new Comparable[unsorted.size()])) - ); + default<T extends Comparable<T>> List<T> sort(List<T> unsorted) { + return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); } } diff --git a/src/main/java/com/thealgorithms/sorts/SortUtils.java b/src/main/java/com/thealgorithms/sorts/SortUtils.java index 5f3563fbeb57..9e114b2084fc 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtils.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtils.java @@ -59,9 +59,7 @@ static <T extends Comparable<T>> boolean greaterOrEqual(T firstElement, T second * @param listToPrint the list to print */ static void print(List<?> listToPrint) { - String result = listToPrint.stream() - .map(Object::toString) - .collect(Collectors.joining(" ")); + String result = listToPrint.stream().map(Object::toString).collect(Collectors.joining(" ")); System.out.println(result); } diff --git a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java index 2e2561e81a44..e75b8e1e6f04 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java @@ -12,7 +12,6 @@ public class SortUtilsRandomGenerator { random = new Random(seed); } - /** * Function to generate array of double values, with predefined size. * @@ -21,8 +20,7 @@ public class SortUtilsRandomGenerator { */ public static Double[] generateArray(int size) { Double[] arr = new Double[size]; - for (int i = 0; i < size; i++) - arr[i] = generateDouble(); + for (int i = 0; i < size; i++) arr[i] = generateDouble(); return arr; } @@ -43,5 +41,4 @@ public static Double generateDouble() { public static int generateInt(int n) { return random.nextInt(n); } - } diff --git a/src/main/java/com/thealgorithms/sorts/StoogeSort.java b/src/main/java/com/thealgorithms/sorts/StoogeSort.java index 0089eaede161..330f9752d1e4 100644 --- a/src/main/java/com/thealgorithms/sorts/StoogeSort.java +++ b/src/main/java/com/thealgorithms/sorts/StoogeSort.java @@ -12,11 +12,7 @@ public <T extends Comparable<T>> T[] sort(T[] unsortedArray) { return unsortedArray; } - public <T extends Comparable<T>> T[] sort( - T[] unsortedArray, - int start, - int end - ) { + public <T extends Comparable<T>> T[] sort(T[] unsortedArray, int start, int end) { if (SortUtils.less(unsortedArray[end - 1], unsortedArray[start])) { T temp = unsortedArray[start]; unsortedArray[start] = unsortedArray[end - 1]; @@ -36,7 +32,7 @@ public <T extends Comparable<T>> T[] sort( public static void main(String[] args) { StoogeSort stoogeSort = new StoogeSort(); - Integer[] integerArray = { 8, 84, 53, 953, 64, 2, 202 }; + Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202}; // Print integerArray unsorted SortUtils.print(integerArray); @@ -44,7 +40,7 @@ public static void main(String[] args) { // Print integerArray sorted SortUtils.print(integerArray); - String[] stringArray = { "g", "d", "a", "b", "f", "c", "e" }; + String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; // Print stringArray unsorted SortUtils.print(stringArray); diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 3e7b02f2c896..87489b8d08af 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -6,19 +6,17 @@ public class StrandSort { // note: the input list is destroyed - public static <E extends Comparable<? super E>> LinkedList<E> strandSort( - LinkedList<E> list - ) { + public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list) { if (list.size() <= 1) return list; LinkedList<E> result = new LinkedList<E>(); while (list.size() > 0) { LinkedList<E> sorted = new LinkedList<E>(); - sorted.add(list.removeFirst()); //same as remove() or remove(0) + sorted.add(list.removeFirst()); // same as remove() or remove(0) for (Iterator<E> it = list.iterator(); it.hasNext();) { E elem = it.next(); if (sorted.peekLast().compareTo(elem) <= 0) { - sorted.addLast(elem); //same as add(elem) or add(0, elem) + sorted.addLast(elem); // same as add(elem) or add(0, elem) it.remove(); } } @@ -28,15 +26,14 @@ public static <E extends Comparable<? super E>> LinkedList<E> strandSort( } private static <E extends Comparable<? super E>> LinkedList<E> merge( - LinkedList<E> left, - LinkedList<E> right - ) { + LinkedList<E> left, LinkedList<E> right) { LinkedList<E> result = new LinkedList<E>(); while (!left.isEmpty() && !right.isEmpty()) { - //change the direction of this comparison to change the direction of the sort - if (left.peek().compareTo(right.peek()) <= 0) result.add( - left.remove() - ); else result.add(right.remove()); + // change the direction of this comparison to change the direction of the sort + if (left.peek().compareTo(right.peek()) <= 0) + result.add(left.remove()); + else + result.add(right.remove()); } result.addAll(left); result.addAll(right); diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java index 718de04eeb8b..a626e511bb10 100644 --- a/src/main/java/com/thealgorithms/sorts/SwapSort.java +++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java @@ -17,8 +17,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { int index = 0; while (index < LENGTH - 1) { - int amountSmallerElements = - this.getSmallerElementCount(array, index); + int amountSmallerElements = this.getSmallerElementCount(array, index); if (amountSmallerElements > 0 && index != amountSmallerElements) { T element = array[index]; @@ -32,10 +31,7 @@ public <T extends Comparable<T>> T[] sort(T[] array) { return array; } - private <T extends Comparable<T>> int getSmallerElementCount( - T[] array, - int index - ) { + private <T extends Comparable<T>> int getSmallerElementCount(T[] array, int index) { int counter = 0; for (int i = 0; i < array.length; i++) { if (less(array[i], array[index])) { @@ -48,7 +44,7 @@ private <T extends Comparable<T>> int getSmallerElementCount( public static void main(String[] args) { // ==== Int ======= - Integer[] a = { 3, 7, 45, 1, 33, 5, 2, 9 }; + Integer[] a = {3, 7, 45, 1, 33, 5, 2, 9}; System.out.print("unsorted: "); print(a); System.out.println(); diff --git a/src/main/java/com/thealgorithms/sorts/TimSort.java b/src/main/java/com/thealgorithms/sorts/TimSort.java index 41337bc5a0a8..be7eaa275c91 100644 --- a/src/main/java/com/thealgorithms/sorts/TimSort.java +++ b/src/main/java/com/thealgorithms/sorts/TimSort.java @@ -9,8 +9,7 @@ */ class TimSort implements SortAlgorithm { private static final int SUB_ARRAY_SIZE = 32; - @SuppressWarnings("rawtypes") - private static Comparable[] aux; + @SuppressWarnings("rawtypes") private static Comparable[] aux; @Override public <T extends Comparable<T>> T[] sort(T[] a) { @@ -48,5 +47,4 @@ private static <T extends Comparable<T>> void merge(T[] a, int lo, int mid, int } } } - } diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index b72a3d77766f..947e158a2a61 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -79,20 +79,14 @@ static class Graph { * */ public void addEdge(String label, String... next) { adj.put(label, new Vertex(label)); - if (!next[0].isEmpty()) Collections.addAll( - adj.get(label).next, - next - ); + if (!next[0].isEmpty()) Collections.addAll(adj.get(label).next, next); } } static class BackEdgeException extends RuntimeException { public BackEdgeException(String backEdge) { - super( - "This graph contains a cycle. No linear ordering is possible. " + - backEdge - ); + super("This graph contains a cycle. No linear ordering is possible. " + backEdge); } } @@ -144,24 +138,20 @@ private static String sort(Graph graph, Vertex u, LinkedList<String> list) { time++; u.weight = time; u.color = Color.GRAY; - graph.adj - .get(u.label) - .next.forEach(label -> { - if (graph.adj.get(label).color == Color.WHITE) { - graph.adj.get(label).predecessor = u; - list.addFirst(sort(graph, graph.adj.get(label), list)); - } else if (graph.adj.get(label).color == Color.GRAY) { - /* - * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v - * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f - * - * In many cases, we will not know u.f, but v.color denotes the type of edge - * */ - throw new BackEdgeException( - "Back edge: " + u.label + " -> " + label - ); - } - }); + graph.adj.get(u.label).next.forEach(label -> { + if (graph.adj.get(label).color == Color.WHITE) { + graph.adj.get(label).predecessor = u; + list.addFirst(sort(graph, graph.adj.get(label), list)); + } else if (graph.adj.get(label).color == Color.GRAY) { + /* + * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v + * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f + * + * In many cases, we will not know u.f, but v.color denotes the type of edge + * */ + throw new BackEdgeException("Back edge: " + u.label + " -> " + label); + } + }); u.color = Color.BLACK; time++; u.finished = time; diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java index 78f233783ff0..be95d64361d5 100644 --- a/src/main/java/com/thealgorithms/sorts/TreeSort.java +++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java @@ -51,9 +51,7 @@ private <T extends Comparable<T>> T[] doTreeSortArray(T[] unsortedArray) { return unsortedArray; } - private <T extends Comparable<T>> List<T> doTreeSortList( - List<T> unsortedList - ) { + private <T extends Comparable<T>> List<T> doTreeSortList(List<T> unsortedList) { // create a generic BST tree BSTRecursiveGeneric<T> tree = new BSTRecursiveGeneric<T>(); @@ -71,7 +69,7 @@ public static void main(String[] args) { // ==== Integer Array ======= System.out.println("Testing for Integer Array...."); - Integer[] a = { 3, -7, 45, 1, 343, -5, 2, 9 }; + Integer[] a = {3, -7, 45, 1, 343, -5, 2, 9}; System.out.printf("%-10s", "unsorted: "); print(a); a = treeSort.sort(a); @@ -111,15 +109,7 @@ public static void main(String[] args) { // ==== String List ======= System.out.println("Testing for String List...."); List<String> stringList = List.of( - "banana", - "berry", - "orange", - "grape", - "peach", - "cherry", - "apple", - "pineapple" - ); + "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 dc05de43cbdd..e6f7f10adb79 100644 --- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java +++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java @@ -9,9 +9,11 @@ /** * A wiggle sort implementation based on John L.s' answer in * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity - * Also have a look at: https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 - * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable arrays and throw an error, - * but there are some exceptions that won't be caught, for example [1, 2, 2]. + * Also have a look at: + * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1 + * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable + * arrays and throw an error, but there are some exceptions that won't be caught, for example [1, 2, + * 2]. */ public class WiggleSort implements SortAlgorithm { @@ -31,10 +33,7 @@ private int mapIndex(int index, int n) { * @param median defines the groups * @param <T> extends interface Comparable */ - private <T extends Comparable<T>> void triColorSort( - T[] sortThis, - T median - ) { + private <T extends Comparable<T>> void triColorSort(T[] sortThis, T median) { int n = sortThis.length; int i = 0; int j = 0; @@ -54,14 +53,11 @@ private <T extends Comparable<T>> void triColorSort( } private <T extends Comparable<T>> T[] wiggleSort(T[] sortThis) { - // find the median using quickSelect (if the result isn't in the array, use the next greater value) + // find the median using quickSelect (if the result isn't in the array, use the next greater + // value) T median; - median = - select( - Arrays.asList(sortThis), - (int) floor(sortThis.length / 2.0) - ); + median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0)); int numMedians = 0; @@ -72,22 +68,17 @@ private <T extends Comparable<T>> T[] wiggleSort(T[] sortThis) { } // added condition preventing off-by-one errors for odd arrays. // https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1 - if ( - sortThis.length % 2 == 1 && - numMedians == ceil(sortThis.length / 2.0) - ) { + 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, " + - "the median has to be the smallest values in the array." - ); + "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." - ); + "No more than half the number of values may be the same."); } triColorSort(sortThis, median); diff --git a/src/main/java/com/thealgorithms/strings/Alphabetical.java b/src/main/java/com/thealgorithms/strings/Alphabetical.java index 09d533eaad1a..fde17c883917 100644 --- a/src/main/java/com/thealgorithms/strings/Alphabetical.java +++ b/src/main/java/com/thealgorithms/strings/Alphabetical.java @@ -25,10 +25,7 @@ public static void main(String[] args) { public static boolean isAlphabetical(String s) { s = s.toLowerCase(); for (int i = 0; i < s.length() - 1; ++i) { - if ( - !Character.isLetter(s.charAt(i)) || - !(s.charAt(i) <= s.charAt(i + 1)) - ) { + if (!Character.isLetter(s.charAt(i)) || !(s.charAt(i) <= s.charAt(i + 1))) { return false; } } diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 33ea900e3d06..dcfc2f851122 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -12,24 +12,21 @@ */ public class Anagrams { - // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time. + // 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but + // differ in running time. public static void main(String[] args) { String first = "deal"; 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*/ + nm.approach2(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach1(first, second) - );/* To activate methods for different approaches*/ + nm.approach1(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach3(first, second) - );/* To activate methods for different approaches*/ + nm.approach3(first, second)); /* To activate methods for different approaches*/ System.out.println( - nm.approach4(first, second) - );/* To activate methods for different approaches*/ + nm.approach4(first, second)); /* To activate methods for different approaches*/ /** * OUTPUT : * first string ="deal" second string ="lead" @@ -55,9 +52,9 @@ boolean approach1(String s, String t) { char[] c = s.toCharArray(); char[] d = t.toCharArray(); Arrays.sort(c); - Arrays.sort( - d - );/* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */ + Arrays.sort(d); /* In this approach the strings are stored in the character arrays and + both the arrays are sorted. After that both the arrays are compared + for checking anangram */ return Arrays.equals(c, d); } @@ -72,8 +69,10 @@ boolean approach2(String a, String b) { for (char c : a.toCharArray()) { m[c - 'a']++; } - // In this approach the frequency of both the strings are stored and after that the frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match then anagram message is displayed in the form of boolean format - // Running time and space complexity of this algo is less as compared to others + // In this approach the frequency of both the strings are stored and after that the + // frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match + // then anagram message is displayed in the form of boolean format Running time and + // space complexity of this algo is less as compared to others for (char c : b.toCharArray()) { n[c - 'a']++; } @@ -90,7 +89,8 @@ boolean approach3(String s, String t) { if (s.length() != t.length()) { return false; } - // this is similar to approach number 2 but here the string is not converted to character array + // this is similar to approach number 2 but here the string is not converted to character + // array else { int[] a = new int[26]; int[] b = new int[26]; @@ -110,7 +110,9 @@ boolean approach4(String s, String t) { if (s.length() != t.length()) { return false; } - // This approach is done using hashmap where frequencies are stored and checked iteratively and if all the frequencies of first string match with the second string then anagram message is displayed in boolean format + // This approach is done using hashmap where frequencies are stored and checked iteratively + // and if all the frequencies of first string match with the second string then anagram + // message is displayed in boolean format else { HashMap<Character, Integer> nm = new HashMap<>(); HashMap<Character, Integer> kk = new HashMap<>(); @@ -126,22 +128,25 @@ boolean approach4(String s, String t) { } boolean approach5(String s, String t) { - if(s.length() != t.length()){ + if (s.length() != t.length()) { return false; } - // Approach is different from above 4 aproaches. - // Here we initialize an array of size 26 where each element corresponds to the frequency of a character. + // Approach is different from above 4 aproaches. + // Here we initialize an array of size 26 where each element corresponds to the frequency of + // a character. int[] freq = new int[26]; - // iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string. - for(int i=0; i<s.length(); i++){ + // iterate through both strings, incrementing the frequency of each character in the first + // string and decrementing the frequency of each character in the second string. + for (int i = 0; i < s.length(); i++) { int pos1 = s.charAt(i) - 'a'; - int pos2 = s.charAt(i) - 'a'; + int pos2 = s.charAt(i) - 'a'; freq[pos1]++; freq[pos2]--; } - // iterate through the frequency array and check if all the elements are zero, if so return true else false - for(int i=0; i<26; i++){ - if(freq[i] != 0){ + // iterate through the frequency array and check if all the elements are zero, if so return + // true else false + for (int i = 0; i < 26; i++) { + if (freq[i] != 0) { return false; } } diff --git a/src/main/java/com/thealgorithms/strings/CheckVowels.java b/src/main/java/com/thealgorithms/strings/CheckVowels.java index bd6861785fdd..821bca69d22d 100644 --- a/src/main/java/com/thealgorithms/strings/CheckVowels.java +++ b/src/main/java/com/thealgorithms/strings/CheckVowels.java @@ -11,9 +11,8 @@ */ public class CheckVowels { - private static final Set<Character> VOWELS = new HashSet<>( - Arrays.asList('a', 'e', 'i', 'o', 'u') - ); + private static final Set<Character> 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/HammingDistance.java b/src/main/java/com/thealgorithms/strings/HammingDistance.java index a6f6db19475c..bfa3114b1c03 100644 --- a/src/main/java/com/thealgorithms/strings/HammingDistance.java +++ b/src/main/java/com/thealgorithms/strings/HammingDistance.java @@ -1,7 +1,7 @@ package com.thealgorithms.strings; -/* In information theory, the Hamming distance between two strings of equal length -is the number of positions at which the corresponding symbols are different. +/* In information theory, the Hamming distance between two strings of equal length +is the number of positions at which the corresponding symbols are different. https://en.wikipedia.org/wiki/Hamming_distance */ public class HammingDistance { @@ -14,8 +14,7 @@ public class HammingDistance { * @return {@code int} hamming distance * @throws Exception */ - public static int calculateHammingDistance(String s1, String s2) - throws Exception { + public static int calculateHammingDistance(String s1, String s2) throws Exception { if (s1.length() != s2.length()) { throw new Exception("String lengths must be equal"); } diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java index 9ac0d50ca8fe..aa318d873482 100644 --- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java +++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java @@ -92,11 +92,7 @@ public static Integer getLastComparisons() { * @param text text String * @return index of first occurrence of the pattern in the text */ - private static int firstOccurrence( - String pattern, - String text, - boolean caseSensitive - ) { + private static int firstOccurrence(String pattern, String text, boolean caseSensitive) { shiftValues = calcShiftValues(pattern); // build the bad symbol table comparisons = 0; // reset comparisons @@ -104,7 +100,8 @@ private static int firstOccurrence( 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()) { @@ -113,10 +110,9 @@ private static int firstOccurrence( while (i >= 0) { comparisons++; char patternChar = pattern.charAt(i); - char textChar = text.charAt( - (textIndex + i) - (pattern.length() - 1) - ); - if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern + char textChar = text.charAt((textIndex + i) - (pattern.length() - 1)); + if (!charEquals( + patternChar, textChar, caseSensitive)) { // bad character, shift pattern textIndex += getShiftValue(text.charAt(textIndex)); break; } @@ -163,7 +159,8 @@ private static HashMap<Character, Integer> calcShiftValues(String pattern) { patternLength = pattern.length(); HashMap<Character, Integer> 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/LetterCombinationsOfPhoneNumber.java b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java index fcdc310d4a61..7ad9971eb56b 100644 --- a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java +++ b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java @@ -15,8 +15,7 @@ protected static List<String> printWords(int[] numbers, int len, int numIndex, S for (int i = 0; i < numberToCharMap[numbers[numIndex]].length; i++) { String sCopy = String.copyValueOf(s.toCharArray()); - sCopy = - sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString()); + sCopy = sCopy.concat(numberToCharMap[numbers[numIndex]][i].toString()); stringList.addAll(printWords(numbers, len, numIndex + 1, sCopy)); } return stringList; @@ -30,21 +29,21 @@ private static void printWords(int[] numbers) { protected static void generateNumberToCharMap() { numberToCharMap = new Character[10][5]; - numberToCharMap[0] = new Character[] { '\0' }; - numberToCharMap[1] = new Character[] { '\0' }; - numberToCharMap[2] = new Character[] { 'a', 'b', 'c' }; - numberToCharMap[3] = new Character[] { 'd', 'e', 'f' }; - numberToCharMap[4] = new Character[] { 'g', 'h', 'i' }; - numberToCharMap[5] = new Character[] { 'j', 'k', 'l' }; - numberToCharMap[6] = new Character[] { 'm', 'n', 'o' }; - numberToCharMap[7] = new Character[] { 'p', 'q', 'r', 's' }; - numberToCharMap[8] = new Character[] { 't', 'u', 'v' }; - numberToCharMap[9] = new Character[] { 'w', 'x', 'y', 'z' }; + numberToCharMap[0] = new Character[] {'\0'}; + numberToCharMap[1] = new Character[] {'\0'}; + numberToCharMap[2] = new Character[] {'a', 'b', 'c'}; + numberToCharMap[3] = new Character[] {'d', 'e', 'f'}; + numberToCharMap[4] = new Character[] {'g', 'h', 'i'}; + numberToCharMap[5] = new Character[] {'j', 'k', 'l'}; + numberToCharMap[6] = new Character[] {'m', 'n', 'o'}; + numberToCharMap[7] = new Character[] {'p', 'q', 'r', 's'}; + numberToCharMap[8] = new Character[] {'t', 'u', 'v'}; + numberToCharMap[9] = new Character[] {'w', 'x', 'y', 'z'}; } // Driver code public static void main(String[] args) { - int[] number = { 2, 3, 4 }; + int[] number = {2, 3, 4}; printWords(number); } } diff --git a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java index 8ebff8576630..6efdabcec7f3 100644 --- a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java @@ -11,9 +11,7 @@ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the string: "); str = sc.nextLine(); - System.out.println( - "Longest substring is : " + s.longestPalindrome(str) - ); + System.out.println("Longest substring is : " + s.longestPalindrome(str)); } } diff --git a/src/main/java/com/thealgorithms/strings/Lower.java b/src/main/java/com/thealgorithms/strings/Lower.java index c5288d1a0a2b..ef3902b15df3 100644 --- a/src/main/java/com/thealgorithms/strings/Lower.java +++ b/src/main/java/com/thealgorithms/strings/Lower.java @@ -6,7 +6,7 @@ public class Lower { * Driver Code */ public static void main(String[] args) { - String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toLowerCase(s).equals(s.toLowerCase()); } @@ -21,10 +21,7 @@ public static void main(String[] args) { public static String toLowerCase(String s) { char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { - if ( - Character.isLetter(values[i]) && - Character.isUpperCase(values[i]) - ) { + if (Character.isLetter(values[i]) && Character.isUpperCase(values[i])) { values[i] = Character.toLowerCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java index 327cc4c19897..a8669273a3cd 100644 --- a/src/main/java/com/thealgorithms/strings/MyAtoi.java +++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java @@ -1,9 +1,10 @@ -// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function). Here is my implementation +// Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer +// (similar to C/C++'s atoi function). Here is my implementation package com.thealgorithms.strings; public class MyAtoi { -public static int myAtoi(String s) { + public static int myAtoi(String s) { s = s.trim(); char[] char_1 = s.toCharArray(); String number = ""; @@ -22,8 +23,7 @@ public static int myAtoi(String s) { number = "0"; break; } - if(ch >= '0' && ch <= '9') - number += ch; + if (ch >= '0' && ch <= '9') number += ch; } else if (ch == '-' && !isDigit) { number += "0"; negative = true; @@ -40,15 +40,14 @@ public static int myAtoi(String s) { break; } } - - if (!isDigit) { + + if (!isDigit) { return 0; } - - number = number.replaceFirst("^0+(?!$)", ""); - - - if (number.length() > 10 && negative) { + + number = number.replaceFirst("^0+(?!$)", ""); + + if (number.length() > 10 && negative) { return -2147483648; } else if (number.length() > 10) { return 2147483647; @@ -64,9 +63,9 @@ public static int myAtoi(String s) { } } - if(negative){ - return Integer.parseInt(number)*-1; - } + if (negative) { + return Integer.parseInt(number) * -1; + } return Integer.parseInt(number); } diff --git a/src/main/java/com/thealgorithms/strings/Palindrome.java b/src/main/java/com/thealgorithms/strings/Palindrome.java index 0046e5450e69..cfc4efd1bb2d 100644 --- a/src/main/java/com/thealgorithms/strings/Palindrome.java +++ b/src/main/java/com/thealgorithms/strings/Palindrome.java @@ -14,9 +14,7 @@ class Palindrome { */ public static boolean isPalindrome(String s) { return ( - (s == null || s.length() <= 1) || - s.equals(new StringBuilder(s).reverse().toString()) - ); + (s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString())); } /** diff --git a/src/main/java/com/thealgorithms/strings/Pangram.java b/src/main/java/com/thealgorithms/strings/Pangram.java index 71924e0bbb81..4772ac826b5e 100644 --- a/src/main/java/com/thealgorithms/strings/Pangram.java +++ b/src/main/java/com/thealgorithms/strings/Pangram.java @@ -36,7 +36,7 @@ public static boolean isPangram(String s) { } return true; } - + /** * Checks if a String is Pangram or not by checking if each alhpabet is present or not * diff --git a/src/main/java/com/thealgorithms/strings/PermuteString.java b/src/main/java/com/thealgorithms/strings/PermuteString.java index b7705c9bc77e..d4abb67440b4 100644 --- a/src/main/java/com/thealgorithms/strings/PermuteString.java +++ b/src/main/java/com/thealgorithms/strings/PermuteString.java @@ -7,13 +7,13 @@ Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with A, B and C respectively. >>Repeat step 1 for the rest of the characters like fixing second character B and so on. ->>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again, - and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB. +>>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B +again, and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB. >>Repeat these steps for BAC and CBA, to get all the permutations. */ public class PermuteString { - //Function for swapping the characters at position I with character at position j + // Function for swapping the characters at position I with character at position j public static String swapString(String a, int i, int j) { char[] b = a.toCharArray(); char ch; @@ -30,18 +30,18 @@ public static void main(String[] args) { generatePermutation(str, 0, len); } - //Function for generating different permutations of the string + // Function for generating different permutations of the string public static void generatePermutation(String str, int start, int end) { - //Prints the permutations + // Prints the permutations if (start == end - 1) { System.out.println(str); } else { for (int i = start; i < end; i++) { - //Swapping the string by fixing a character + // Swapping the string by fixing a character str = swapString(str, start, i); - //Recursively calling function generatePermutation() for rest of the characters + // Recursively calling function generatePermutation() for rest of the characters generatePermutation(str, start + 1, end); - //Backtracking and swapping the characters again. + // Backtracking and swapping the characters again. str = swapString(str, start, i); } } diff --git a/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java b/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java index 95833220df1a..0cd2a971b225 100644 --- a/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java +++ b/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java @@ -9,12 +9,11 @@ public class ReverseStringRecursive { * @param str string to be reversed * @return reversed string */ - public static String reverse(String str) - { - if(str.isEmpty()){ + public static String reverse(String str) { + if (str.isEmpty()) { return str; } else { - return reverse(str.substring(1))+str.charAt(0); + return reverse(str.substring(1)) + str.charAt(0); } } } diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java index 0d209f885f94..9e8f31d26594 100644 --- a/src/main/java/com/thealgorithms/strings/StringCompression.java +++ b/src/main/java/com/thealgorithms/strings/StringCompression.java @@ -1,60 +1,62 @@ package com.thealgorithms.strings; /* References : https://en.wikipedia.org/wiki/Run-length_encoding - * String compression algorithm deals with encoding the string, that is, shortening the size of the string + * String compression algorithm deals with encoding the string, that is, shortening the size of the + * string * @author Swarga-codes (https://github.com/Swarga-codes) -*/ + */ public class StringCompression { - /** - * Returns the compressed or encoded string - * - * @param ch character array that contains the group of characters to be encoded - * @return the compressed character array as string - */ - public static String compress(String input) { - // Keeping the count as 1 since every element present will have atleast a count - // of 1 - int count = 1; - String compressedString = ""; - // Base condition to check whether the array is of size 1, if it is then we - // return the array - if (input.length() == 1) { - return "" + input.charAt(0); + /** + * Returns the compressed or encoded string + * + * @param ch character array that contains the group of characters to be encoded + * @return the compressed character array as string + */ + public static String compress(String input) { + // Keeping the count as 1 since every element present will have atleast a count + // of 1 + int count = 1; + String compressedString = ""; + // Base condition to check whether the array is of size 1, if it is then we + // return the array + if (input.length() == 1) { + return "" + input.charAt(0); + } + // If the array has a length greater than 1 we move into this loop + for (int i = 0; i < input.length() - 1; i++) { + // here we check for similarity of the adjacent elements and change the count + // accordingly + if (input.charAt(i) == input.charAt(i + 1)) { + count = count + 1; + } + if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { + compressedString = appendCount(compressedString, count, input.charAt(i)); + 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); + break; + } else { + compressedString = appendCount(compressedString, count, input.charAt(i)); + count = 1; + } + } + } + return compressedString; } - // If the array has a length greater than 1 we move into this loop - for (int i = 0; i < input.length() - 1; i++) { - // here we check for similarity of the adjacent elements and change the count - // accordingly - if (input.charAt(i) == input.charAt(i + 1)) { - count = count + 1; - } - if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { - compressedString = appendCount(compressedString, count, input.charAt(i)); - 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); - break; + /** + * @param res the resulting string + * @param count current count + * @param ch the character at a particular index + * @return the res string appended with the count + */ + public static String appendCount(String res, int count, char ch) { + if (count > 1) { + res += ch + "" + count; + count = 1; } else { - compressedString = appendCount(compressedString, count, input.charAt(i)); - count = 1; + res += ch + ""; } - } - } - return compressedString; - } - /** - * @param res the resulting string - * @param count current count - * @param ch the character at a particular index - * @return the res string appended with the count - */ - public static String appendCount(String res, int count, char ch) { - if (count > 1) { - res += ch + "" + count; - count = 1; - } else { - res += ch + ""; + return res; } - return res; - } } \ No newline at end of file diff --git a/src/main/java/com/thealgorithms/strings/Upper.java b/src/main/java/com/thealgorithms/strings/Upper.java index 35558462d9cb..8f306a20e8f0 100644 --- a/src/main/java/com/thealgorithms/strings/Upper.java +++ b/src/main/java/com/thealgorithms/strings/Upper.java @@ -6,7 +6,7 @@ public class Upper { * Driver Code */ public static void main(String[] args) { - String[] strings = { "ABC", "ABC123", "abcABC", "abc123ABC" }; + String[] strings = {"ABC", "ABC123", "abcABC", "abc123ABC"}; for (String s : strings) { assert toUpperCase(s).equals(s.toUpperCase()); } @@ -24,10 +24,7 @@ public static String toUpperCase(String s) { } char[] values = s.toCharArray(); for (int i = 0; i < values.length; ++i) { - if ( - Character.isLetter(values[i]) && - Character.isLowerCase(values[i]) - ) { + if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) { values[i] = Character.toUpperCase(values[i]); } } diff --git a/src/main/java/com/thealgorithms/strings/ValidParentheses.java b/src/main/java/com/thealgorithms/strings/ValidParentheses.java index e2b0f8e9b87a..5d3738522d44 100644 --- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java @@ -1,33 +1,31 @@ package com.thealgorithms.strings; -// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. -// An input string is valid if: -// Open brackets must be closed by the same type of brackets. -// Open brackets must be closed in the correct order. -// Every close bracket has a corresponding open bracket of the same type. - +// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine +// if the input string is valid. An input string is valid if: Open brackets must be closed by +// the same type of brackets. Open brackets must be closed in the correct order. Every close +// bracket has a corresponding open bracket of the same type. public class ValidParentheses { - public static boolean isValid(String s) { - char[] stack = new char[s.length()]; - int head = 0; - for(char c : s.toCharArray()) { - switch(c) { - case '{': - case '[': - case '(': - stack[head++] = c; - break; - case '}': - if(head == 0 || stack[--head] != '{') return false; - break; - case ')': - if(head == 0 || stack[--head] != '(') return false; - break; - case ']': - if(head == 0 || stack[--head] != '[') return false; - break; - } - } - return head == 0; - } + public static boolean isValid(String s) { + char[] stack = new char[s.length()]; + int head = 0; + for (char c : s.toCharArray()) { + switch (c) { + case '{': + case '[': + case '(': + stack[head++] = c; + break; + case '}': + if (head == 0 || stack[--head] != '{') return false; + break; + case ')': + if (head == 0 || stack[--head] != '(') return false; + break; + case ']': + if (head == 0 || stack[--head] != '[') return false; + break; + } + } + return head == 0; + } } diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java index c4d8aeb9135d..edeb7036a24d 100644 --- a/src/main/java/com/thealgorithms/strings/WordLadder.java +++ b/src/main/java/com/thealgorithms/strings/WordLadder.java @@ -8,22 +8,26 @@ /* **Problem Statement:** - A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: + A transformation sequence from word beginWord to word endWord using a dictionary wordList is a + sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord - Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. + Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in + the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists. **Example 1:** Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] - Output: 5 - Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long. + Output: 5 + Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", + which is 5 words long. **Example 2:** Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0 - Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence. + Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation + sequence. **Constraints:** 1 <= beginWord.length <= 10 diff --git a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java index 7549dd2a7a0b..252517dc80cc 100644 --- a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java +++ b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java @@ -14,7 +14,8 @@ public static int lengthOfLongestSubstring(String s) { // adding key to map if not present if (!map.containsKey(temp)) map.put(temp, 0); // checking if the first value is the dublicate value - else if (s.charAt(start) == temp) start++; + else if (s.charAt(start) == temp) + start++; // checking if the previous value is dublicate value else if (s.charAt(i - 1) == temp) { if (max < map.size()) max = map.size(); diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java index a1d6761415e2..cc6654c169a0 100644 --- a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java +++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java @@ -7,14 +7,16 @@ public static String encode(String s, int numRows) { 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); - if (height_space == 0) pointer += depth_space; else if ( - depth_space == 0 - ) pointer += height_space; else if (bool) { + if (height_space == 0) + pointer += depth_space; + else if (depth_space == 0) + pointer += height_space; + else if (bool) { pointer += depth_space; bool = false; } else { diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java index 139cd1070676..b9de924ab30a 100644 --- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java +++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.*; + import java.util.*; import org.junit.jupiter.api.Test; @@ -9,48 +10,56 @@ public class AllPathsFromSourceToTargetTest { @Test void testForFirstCase() { int vertices = 4; - int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}}; + int[][] a = {{0, 1}, {0, 2}, {0, 3}, {2, 0}, {2, 1}, {1, 3}}; int source = 2; int destination = 3; - List<List<Integer>> list2 = List.of(List.of(2, 0, 1, 3),List.of(2, 0, 3),List.of(2, 1, 3)); - List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List<List<Integer>> list2 + = List.of(List.of(2, 0, 1, 3), List.of(2, 0, 3), List.of(2, 1, 3)); + List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @Test void testForSecondCase() { int vertices = 5; - int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}}; + 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<List<Integer>> 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<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List<List<Integer>> 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<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @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<List<Integer>> list2 = List.of(List.of(1, 0, 2, 5),List.of(1, 0, 5),List.of(1, 5),List.of(1, 2, 5)); - List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List<List<Integer>> list2 + = List.of(List.of(1, 0, 2, 5), List.of(1, 0, 5), List.of(1, 5), List.of(1, 2, 5)); + List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } @Test void testForFourthcase() { int vertices = 3; - int[][] a = {{0,1},{0,2},{1,2}}; + int[][] a = {{0, 1}, {0, 2}, {1, 2}}; int source = 0; int destination = 2; - List<List<Integer>> list2 = List.of(List.of(0, 1, 2),List.of(0, 2)); - List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget(vertices,a,source,destination); - list2=list1; + List<List<Integer>> list2 = List.of(List.of(0, 1, 2), List.of(0, 2)); + List<List<Integer>> list1 = AllPathsFromSourceToTarget.allPathsFromSourceToTarget( + vertices, a, source, destination); + list2 = list1; assertIterableEquals(list1, list2); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java index 418383c8ce7b..ed6148271d91 100644 --- a/src/test/java/com/thealgorithms/backtracking/CombinationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/CombinationTest.java @@ -10,29 +10,20 @@ public class CombinationTest { @Test void testNoElement() { - List<TreeSet<Integer>> result = Combination.combination( - new Integer[] { 1, 2 }, - 0 - ); + List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 0); assertTrue(result == null); } @Test void testLengthOne() { - List<TreeSet<Integer>> result = Combination.combination( - new Integer[] { 1, 2 }, - 1 - ); + List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 1); assertTrue(result.get(0).iterator().next() == 1); assertTrue(result.get(1).iterator().next() == 2); } @Test void testLengthTwo() { - List<TreeSet<Integer>> result = Combination.combination( - new Integer[] { 1, 2 }, - 2 - ); + List<TreeSet<Integer>> result = Combination.combination(new Integer[] {1, 2}, 2); Integer[] arr = result.get(0).toArray(new Integer[2]); assertTrue(arr[0] == 1); assertTrue(arr[1] == 2); diff --git a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java index b46c7e0fe832..7a59b21005da 100644 --- a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java +++ b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java @@ -17,8 +17,8 @@ void testForEmptyImage() { @Test void testForSingleElementImage() { - int[][] image = { { 1 } }; - int[][] expected = { { 3 } }; + int[][] image = {{1}}; + int[][] expected = {{3}}; FloodFill.floodFill(image, 0, 0, 3, 1); assertArrayEquals(expected, image); @@ -27,23 +27,23 @@ void testForSingleElementImage() { @Test void testForImageOne() { int[][] image = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 1, 1, 5, 0, 0 }, - { 0, 3, 1, 1, 5, 5, 3 }, - { 0, 3, 5, 5, 1, 1, 3 }, - { 0, 0, 0, 5, 1, 1, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 1, 1, 5, 0, 0}, + {0, 3, 1, 1, 5, 5, 3}, + {0, 3, 5, 5, 1, 1, 3}, + {0, 0, 0, 5, 1, 1, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; int[][] expected = { - { 0, 0, 0, 0, 0, 0, 0 }, - { 0, 3, 3, 3, 3, 0, 0 }, - { 0, 3, 2, 2, 5, 0, 0 }, - { 0, 3, 2, 2, 5, 5, 3 }, - { 0, 3, 5, 5, 2, 2, 3 }, - { 0, 0, 0, 5, 2, 2, 3 }, - { 0, 0, 0, 3, 3, 3, 3 }, + {0, 0, 0, 0, 0, 0, 0}, + {0, 3, 3, 3, 3, 0, 0}, + {0, 3, 2, 2, 5, 0, 0}, + {0, 3, 2, 2, 5, 5, 3}, + {0, 3, 5, 5, 2, 2, 3}, + {0, 0, 0, 5, 2, 2, 3}, + {0, 0, 0, 3, 3, 3, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); @@ -53,23 +53,23 @@ void testForImageOne() { @Test void testForImageTwo() { int[][] image = { - { 0, 0, 1, 1, 0, 0, 0 }, - { 1, 1, 3, 3, 3, 0, 0 }, - { 1, 3, 1, 1, 5, 0, 0 }, - { 0, 3, 1, 1, 5, 5, 3 }, - { 0, 3, 5, 5, 1, 1, 3 }, - { 0, 0, 0, 5, 1, 1, 3 }, - { 0, 0, 0, 1, 3, 1, 3 }, + {0, 0, 1, 1, 0, 0, 0}, + {1, 1, 3, 3, 3, 0, 0}, + {1, 3, 1, 1, 5, 0, 0}, + {0, 3, 1, 1, 5, 5, 3}, + {0, 3, 5, 5, 1, 1, 3}, + {0, 0, 0, 5, 1, 1, 3}, + {0, 0, 0, 1, 3, 1, 3}, }; int[][] expected = { - { 0, 0, 2, 2, 0, 0, 0 }, - { 2, 2, 3, 3, 3, 0, 0 }, - { 2, 3, 2, 2, 5, 0, 0 }, - { 0, 3, 2, 2, 5, 5, 3 }, - { 0, 3, 5, 5, 2, 2, 3 }, - { 0, 0, 0, 5, 2, 2, 3 }, - { 0, 0, 0, 2, 3, 2, 3 }, + {0, 0, 2, 2, 0, 0, 0}, + {2, 2, 3, 3, 3, 0, 0}, + {2, 3, 2, 2, 5, 0, 0}, + {0, 3, 2, 2, 5, 5, 3}, + {0, 3, 5, 5, 2, 2, 3}, + {0, 0, 0, 5, 2, 2, 3}, + {0, 0, 0, 2, 3, 2, 3}, }; FloodFill.floodFill(image, 2, 2, 2, 1); @@ -79,15 +79,15 @@ void testForImageTwo() { @Test void testForImageThree() { int[][] image = { - { 1, 1, 2, 3, 1, 1, 1 }, - { 1, 0, 0, 1, 0, 0, 1 }, - { 1, 1, 1, 0, 3, 1, 2 }, + {1, 1, 2, 3, 1, 1, 1}, + {1, 0, 0, 1, 0, 0, 1}, + {1, 1, 1, 0, 3, 1, 2}, }; int[][] expected = { - { 4, 4, 2, 3, 4, 4, 4 }, - { 4, 0, 0, 4, 0, 0, 4 }, - { 4, 4, 4, 0, 3, 4, 2 }, + {4, 4, 2, 3, 4, 4, 4}, + {4, 0, 0, 4, 0, 0, 4}, + {4, 4, 4, 0, 3, 4, 2}, }; FloodFill.floodFill(image, 0, 1, 4, 1); diff --git a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java index 35f66f92ead7..1464c5221bff 100644 --- a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java +++ b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java @@ -35,7 +35,7 @@ public void testMaze() { map[3][1] = 1; map[3][2] = 1; - //clone another map for setWay2 method + // clone another map for setWay2 method for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[i].length; j++) { map2[i][j] = map[i][j]; @@ -46,25 +46,25 @@ public void testMaze() { MazeRecursion.setWay2(map2, 1, 1); int[][] expectedMap = new int[][] { - { 1, 1, 1, 1, 1, 1, 1 }, - { 1, 2, 0, 0, 0, 0, 1 }, - { 1, 2, 2, 2, 0, 0, 1 }, - { 1, 1, 1, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 0, 0, 1 }, - { 1, 0, 0, 2, 2, 2, 1 }, - { 1, 1, 1, 1, 1, 1, 1 }, + {1, 1, 1, 1, 1, 1, 1}, + {1, 2, 0, 0, 0, 0, 1}, + {1, 2, 2, 2, 0, 0, 1}, + {1, 1, 1, 2, 0, 0, 1}, + {1, 0, 0, 2, 0, 0, 1}, + {1, 0, 0, 2, 0, 0, 1}, + {1, 0, 0, 2, 2, 2, 1}, + {1, 1, 1, 1, 1, 1, 1}, }; int[][] expectedMap2 = new int[][] { - { 1, 1, 1, 1, 1, 1, 1 }, - { 1, 2, 2, 2, 2, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 1, 1, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 0, 0, 0, 0, 2, 1 }, - { 1, 1, 1, 1, 1, 1, 1 }, + {1, 1, 1, 1, 1, 1, 1}, + {1, 2, 2, 2, 2, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 1, 1, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 0, 0, 0, 0, 2, 1}, + {1, 1, 1, 1, 1, 1, 1}, }; assertArrayEquals(map, expectedMap); diff --git a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java index 3d865da1b8ae..b6c0400c623f 100644 --- a/src/test/java/com/thealgorithms/backtracking/PermutationTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PermutationTest.java @@ -16,16 +16,14 @@ void testNoElement() { @Test void testSingleElement() { - List<Integer[]> result = Permutation.permutation(new Integer[] { 1 }); + List<Integer[]> result = Permutation.permutation(new Integer[] {1}); assertEquals(result.get(0)[0], 1); } @Test void testMultipleElements() { - List<Integer[]> result = Permutation.permutation( - new Integer[] { 1, 2 } - ); - assertTrue(Arrays.equals(result.get(0), new Integer[] { 1, 2 })); - assertTrue(Arrays.equals(result.get(1), new Integer[] { 2, 1 })); + List<Integer[]> result = Permutation.permutation(new Integer[] {1, 2}); + assertTrue(Arrays.equals(result.get(0), new Integer[] {1, 2})); + assertTrue(Arrays.equals(result.get(1), new Integer[] {2, 1})); } } diff --git a/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java index ae16cc159204..b14bce2b1920 100644 --- a/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java +++ b/src/test/java/com/thealgorithms/backtracking/PowerSumTest.java @@ -1,5 +1,6 @@ package com.thealgorithms.backtracking; import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; public class PowerSumTest { @@ -17,12 +18,11 @@ void testNumberHundredAndPowerTwo() { int result = powerSum.powSum(100, 2); assertEquals(3, result); } - + @Test void testNumberHundredAndPowerThree() { PowerSum powerSum = new PowerSum(); int result = powerSum.powSum(100, 3); assertEquals(1, result); } - } diff --git a/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java index 198217bba0e3..fb224a0b5b23 100644 --- a/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java +++ b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java @@ -9,7 +9,7 @@ public class WordSearchTest { @Test void test1() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCCED"; assertTrue(ws.exist(board, word)); } @@ -17,7 +17,7 @@ void test1() { @Test void test2() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "SEE"; assertTrue(ws.exist(board, word)); } @@ -25,7 +25,7 @@ void test2() { @Test void test3() { WordSearch ws = new WordSearch(); - char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}}; + char[][] board = {{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}}; String word = "ABCB"; Assertions.assertFalse(ws.exist(board, word)); } diff --git a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java index 984457e3d921..e143850e1669 100644 --- a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java +++ b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java @@ -10,29 +10,29 @@ class BlowfishTest { @Test void testEncrypt() { - //given + // given String plainText = "123456abcd132536"; String key = "aabb09182736ccdd"; String expectedOutput = "d748ec383d3405f7"; - //when + // when String cipherText = blowfish.encrypt(plainText, key); - //then + // then assertEquals(expectedOutput, cipherText); } @Test void testDecrypt() { - //given + // given String cipherText = "d748ec383d3405f7"; String key = "aabb09182736ccdd"; String expectedOutput = "123456abcd132536"; - //when + // when String plainText = blowfish.decrypt(cipherText, key); - //then + // then assertEquals(expectedOutput, plainText); } } diff --git a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java index 5eb4a37f113a..5fa81f95fa49 100644 --- a/src/test/java/com/thealgorithms/ciphers/CaesarTest.java +++ b/src/test/java/com/thealgorithms/ciphers/CaesarTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CaesarTest { Caesar caesar = new Caesar(); @@ -43,5 +43,4 @@ void caesarBruteForce() { assertEquals(27, allPossibleAnswers.length); assertEquals("Encrypt this text", allPossibleAnswers[5]); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/DESTest.java b/src/test/java/com/thealgorithms/ciphers/DESTest.java index a0c529d5f268..e652c028d5dd 100644 --- a/src/test/java/com/thealgorithms/ciphers/DESTest.java +++ b/src/test/java/com/thealgorithms/ciphers/DESTest.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -//Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm +// Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm public class DESTest { DES des; @@ -17,35 +17,40 @@ public void setUp() { @Test void testEncrypt() { - //given + // given String plainText = "Your lips are smoother than vaseline\r\n"; - //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal - String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" + - "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + - "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + - "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; - - //when + // This is equal to + // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in + // hexadecimal + String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + + // when String cipherText = des.encrypt(plainText); - //then + // then assertEquals(expectedOutput, cipherText); } @Test void testDecrypt() { - //given - //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal - String cipherText = "11000000100110011001111111011101111000110111100011010111111" + - "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + - "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + - "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; - String expectedOutput = "Your lips are smoother than vaseline\r\n";; - - //when + // given + // This is equal to + // c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in + // hexadecimal + String cipherText = "11000000100110011001111111011101111000110111100011010111111" + + "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" + + "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" + + "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011"; + String expectedOutput = "Your lips are smoother than vaseline\r\n"; + ; + + // when String plainText = des.decrypt(cipherText); - //then + // then assertEquals(expectedOutput, plainText); } } diff --git a/src/test/java/com/thealgorithms/ciphers/RSATest.java b/src/test/java/com/thealgorithms/ciphers/RSATest.java index 46fff7963f7a..c82f68d11f4c 100644 --- a/src/test/java/com/thealgorithms/ciphers/RSATest.java +++ b/src/test/java/com/thealgorithms/ciphers/RSATest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class RSATest { RSA rsa = new RSA(1024); @@ -20,5 +20,4 @@ void testRSA() { // then assertEquals("Such secure", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java index e9bbcf951391..f593a07d89b7 100644 --- a/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class SimpleSubCipherTest { SimpleSubCipher simpleSubCipher = new SimpleSubCipher(); @@ -33,5 +33,4 @@ void simpleSubCipherDecryptTest() { // then assertEquals("defend the east wall of the castle", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java b/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java index 59fb9c072ba5..f7cace2e08aa 100644 --- a/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class SimpleSubstitutionCipherTest { @Test diff --git a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java index 421edf3aba04..c5935de95dfa 100644 --- a/src/test/java/com/thealgorithms/ciphers/VigenereTest.java +++ b/src/test/java/com/thealgorithms/ciphers/VigenereTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.ciphers; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class VigenereTest { Vigenere vigenere = new Vigenere(); @@ -33,5 +33,4 @@ void vigenereDecryptTest() { // then assertEquals("Hello World!", decryptedText); } - } diff --git a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java index 0ad4c9fb2974..6ef478f95358 100644 --- a/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java +++ b/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java @@ -23,7 +23,7 @@ class LFSRTest { }; // Represents 11 1010 1011 0011 1100 1011 - byte[] frameCounterBytes = { (byte) 203, (byte) 179, 58 }; + byte[] frameCounterBytes = {(byte) 203, (byte) 179, 58}; @Test void initialize() { @@ -46,7 +46,7 @@ void initialize() { expected.set(16); expected.set(17); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); lfsr0.initialize(sessionKey, frameCounter); assertEquals(expected.toString(), lfsr0.toString()); } @@ -56,7 +56,7 @@ void clock() { BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); BitSet frameCounter = BitSet.valueOf(frameCounterBytes); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); lfsr0.initialize(sessionKey, frameCounter); BitSet expected = new BitSet(19); @@ -85,7 +85,7 @@ void getClockBit() { BitSet sessionKey = BitSet.valueOf(sessionKeyBytes); BitSet frameCounter = BitSet.valueOf(frameCounterBytes); - LFSR lfsr0 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 }); + LFSR lfsr0 = new LFSR(19, 8, new int[] {13, 16, 17, 18}); assertFalse(lfsr0.getClockBit()); diff --git a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java index 336aeef3ebbe..29265bd9d6e9 100644 --- a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java +++ b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class BinaryToDecimalTest { @Test diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java index 573793236be3..a5abcb95cb8d 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToBinaryTest.java @@ -1,12 +1,13 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class HexaDecimalToBinaryTest { @Test - public void testHexaDecimalToBinary(){ + public void testHexaDecimalToBinary() { HexaDecimalToBinary hexaDecimalToBinary = new HexaDecimalToBinary(); assertEquals("1111111111111111111111111111111", hexaDecimalToBinary.convert("7fffffff")); assertEquals("101010111100110111101111", hexaDecimalToBinary.convert("abcdef")); diff --git a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java index 5a7838e772b1..c9c2ab2161ed 100644 --- a/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java +++ b/src/test/java/com/thealgorithms/conversions/HexaDecimalToDecimalTest.java @@ -1,13 +1,13 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class HexaDecimalToDecimalTest { @Test - public void testhexaDecimalToDecimal(){ + public void testhexaDecimalToDecimal() { assertEquals(161, HexaDecimalToDecimal.getHexaToDec("A1")); assertEquals(428, HexaDecimalToDecimal.getHexaToDec("1ac")); } diff --git a/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java b/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java index 52eda44cd2b5..c51986f2a8d9 100644 --- a/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java +++ b/src/test/java/com/thealgorithms/conversions/RomanToIntegerTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.conversions; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class RomanToIntegerTest { @Test diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java index 70fb6608e481..ab7eff7185cf 100644 --- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java +++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java @@ -1,16 +1,15 @@ package com.thealgorithms.datastructures.buffers; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.RepeatedTest; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicIntegerArray; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; class CircularBufferTest { private static final int BUFFER_SIZE = 10; @@ -34,25 +33,21 @@ void isFull() { buffer.put(generateInt()); assertFalse(buffer.isFull()); - for (int i = 1; i < BUFFER_SIZE; i++) - buffer.put(generateInt()); + for (int i = 1; i < BUFFER_SIZE; i++) buffer.put(generateInt()); assertTrue(buffer.isFull()); } @Test void get() { assertNull(buffer.get()); - for (int i = 0; i < 100; i++) - buffer.put(i); - for (int i = 0; i < BUFFER_SIZE; i++) - assertEquals(i, buffer.get()); + for (int i = 0; i < 100; i++) buffer.put(i); + for (int i = 0; i < BUFFER_SIZE; i++) assertEquals(i, buffer.get()); assertNull(buffer.get()); } @Test void put() { - for (int i = 0; i < BUFFER_SIZE; i++) - assertTrue(buffer.put(generateInt())); + for (int i = 0; i < BUFFER_SIZE; i++) assertTrue(buffer.put(generateInt())); assertFalse(buffer.put(generateInt())); } @@ -119,8 +114,7 @@ private void shutDownExecutorSafely(ExecutorService executorService) { public List<Integer> getSortedListFrom(AtomicIntegerArray atomicArray) { int length = atomicArray.length(); ArrayList<Integer> result = new ArrayList<>(length); - for (int i = 0; i < length; i++) - result.add(atomicArray.get(i)); + for (int i = 0; i < length; i++) result.add(atomicArray.get(i)); result.sort(Comparator.comparingInt(o -> o)); return result; } diff --git a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java index 6faf6da3a4b4..6a94345d625e 100644 --- a/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java +++ b/src/test/java/com/thealgorithms/datastructures/caches/LFUCacheTest.java @@ -15,19 +15,19 @@ void testLFUCacheWithIntegerValueShouldPass() { lfuCache.put(4, 40); lfuCache.put(5, 50); - //get method call will increase frequency of key 1 by 1 + // get method call will increase frequency of key 1 by 1 assertEquals(10, lfuCache.get(1)); - //this operation will remove value with key as 2 + // this operation will remove value with key as 2 lfuCache.put(6, 60); - //will return null as value with key 2 is now evicted + // will return null as value with key 2 is now evicted assertEquals(null, lfuCache.get(2)); - //should return 60 + // should return 60 assertEquals(60, lfuCache.get(6)); - //this operation will remove value with key as 3 + // this operation will remove value with key as 3 lfuCache.put(7, 70); assertEquals(null, lfuCache.get(2)); @@ -43,19 +43,19 @@ void testLFUCacheWithStringValueShouldPass() { lfuCache.put(4, "Delta"); lfuCache.put(5, "Eplison"); - //get method call will increase frequency of key 1 by 1 + // get method call will increase frequency of key 1 by 1 assertEquals("Alpha", lfuCache.get(1)); - //this operation will remove value with key as 2 + // this operation will remove value with key as 2 lfuCache.put(6, "Digamma"); - //will return null as value with key 2 is now evicted + // will return null as value with key 2 is now evicted assertEquals(null, lfuCache.get(2)); - //should return string Digamma + // should return string Digamma assertEquals("Digamma", lfuCache.get(6)); - //this operation will remove value with key as 3 + // this operation will remove value with key as 3 lfuCache.put(7, "Zeta"); assertEquals(null, lfuCache.get(2)); diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java index 3746753b6c68..9890463de3ff 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java @@ -10,36 +10,30 @@ class HamiltonianCycleTest { @Test void testFindHamiltonianCycleShouldReturnHamiltonianCycle() { - int[] expectedArray = { 0, 1, 2, 4, 3, 0 }; + int[] expectedArray = {0, 1, 2, 4, 3, 0}; int[][] inputArray = { - { 0, 1, 0, 1, 0 }, - { 1, 0, 1, 1, 1 }, - { 0, 1, 0, 0, 1 }, - { 1, 1, 0, 0, 1 }, - { 0, 1, 1, 1, 0 }, + {0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 1}, + {0, 1, 1, 1, 0}, }; - assertArrayEquals( - expectedArray, - hamiltonianCycle.findHamiltonianCycle(inputArray) - ); + assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); } @Test void testFindHamiltonianCycleShouldReturnInfinityArray() { - int[] expectedArray = { -1, -1, -1, -1, -1, -1 }; + int[] expectedArray = {-1, -1, -1, -1, -1, -1}; int[][] inputArray = { - { 0, 1, 0, 1, 0 }, - { 1, 0, 1, 1, 1 }, - { 0, 1, 0, 0, 1 }, - { 1, 1, 0, 0, 0 }, - { 0, 1, 1, 0, 0 }, + {0, 1, 0, 1, 0}, + {1, 0, 1, 1, 1}, + {0, 1, 0, 0, 1}, + {1, 1, 0, 0, 0}, + {0, 1, 1, 0, 0}, }; - assertArrayEquals( - expectedArray, - hamiltonianCycle.findHamiltonianCycle(inputArray) - ); + assertArrayEquals(expectedArray, hamiltonianCycle.findHamiltonianCycle(inputArray)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java index 5395b04ee732..c1e68acac2e6 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java @@ -5,7 +5,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class KosarajuTest { @@ -14,7 +13,7 @@ public class KosarajuTest { @Test public void findStronglyConnectedComps() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList<List<Integer>>(n); @@ -36,10 +35,10 @@ public void findStronglyConnectedComps() { List<List<Integer>> actualResult = kosaraju.kosaraju(n, adjList); List<List<Integer>> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 0, 1, 2 3 - 5, 4, 6 + 5, 4, 6 7 */ expectedResult.add(Arrays.asList(1, 2, 0)); @@ -51,7 +50,7 @@ public void findStronglyConnectedComps() { @Test public void findStronglyConnectedCompsShouldGetSingleNodes() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList<List<Integer>>(n); @@ -71,11 +70,10 @@ public void findStronglyConnectedCompsShouldGetSingleNodes() { List<List<Integer>> actualResult = kosaraju.kosaraju(n, adjList); List<List<Integer>> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 0, 1, 2, 3, 4, 5, 6, 7 */ expectedResult.add(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 0)); assertTrue(expectedResult.equals(actualResult)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java index 2166b2ef6c68..dc81d99dd0bf 100644 --- a/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java @@ -5,15 +5,14 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class TarjansAlgorithmTest { - + TarjansAlgorithm tarjansAlgo = new TarjansAlgorithm(); @Test - public void findStronglyConnectedComps(){ + public void findStronglyConnectedComps() { var v = 5; var graph = new ArrayList<List<Integer>>(); for (int i = 0; i < v; i++) { @@ -27,10 +26,10 @@ public void findStronglyConnectedComps(){ var actualResult = tarjansAlgo.stronglyConnectedComponents(v, graph); /* - Expected result: + Expected result: 0, 1, 2 3 - 4 + 4 */ List<List<Integer>> expectedResult = new ArrayList<>(); @@ -42,7 +41,7 @@ public void findStronglyConnectedComps(){ @Test public void findStronglyConnectedCompsShouldGetSingleNodes() { - //Create a adjacency list of graph + // Create a adjacency list of graph var n = 8; var adjList = new ArrayList<List<Integer>>(n); @@ -62,11 +61,10 @@ public void findStronglyConnectedCompsShouldGetSingleNodes() { List<List<Integer>> actualResult = tarjansAlgo.stronglyConnectedComponents(n, adjList); List<List<Integer>> expectedResult = new ArrayList<>(); /* - Expected result: + Expected result: 7, 6, 5, 4, 3, 2, 1, 0 */ expectedResult.add(Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0)); assertTrue(expectedResult.equals(actualResult)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java index fc6655fa3d3e..c7391c3af56f 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java @@ -93,7 +93,7 @@ void avoidInfiniteLoops() { private HashMapCuckooHashing createHashMapCuckooHashing() { HashMapCuckooHashing hashTable = new HashMapCuckooHashing(10); - int[] values = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222 }; + int[] values = {11, 22, 33, 44, 55, 66, 77, 88, 99, 111, 222}; Arrays.stream(values).forEach(hashTable::insertKey2HashTable); return hashTable; } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java index 45c7b6c5d19d..7f7c36011115 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java @@ -1,17 +1,14 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement; - import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; - +import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement; +import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.junit.jupiter.api.Test; -import java.util.ArrayList; - -public class MajorityElementTest{ +public class MajorityElementTest { @Test void testMajorityWithSingleMajorityElement() { int[] nums = {1, 2, 3, 9, 9, 6, 7, 8, 9, 9, 9, 9}; @@ -42,7 +39,7 @@ void testMajorityWithNoMajorityElement() { @Test void testMajorityWithEmptyArray() { int[] nums = {}; - List<Integer> expected = Collections.emptyList(); + List<Integer> expected = Collections.emptyList(); List<Integer> actual = MajorityElement.majority(nums); assertEquals(expected, actual); } diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java index 5ccbcc304d94..ea6595cc803c 100644 --- a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.datastructures.hashmap.hashing; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.Random; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; abstract class MapTest { abstract <Key extends Comparable<Key>, Value> Map<Key, Value> getMap(); diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java index b0cb0d19674b..983444eb5060 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java @@ -4,25 +4,25 @@ import org.junit.jupiter.api.Test; public class LeftistHeapTest { - - @Test - void testLeftistHeap() { - LeftistHeap heap = new LeftistHeap(); - Assertions.assertTrue(heap.isEmpty()); - heap.insert(6); - Assertions.assertTrue(!heap.isEmpty()); - heap.insert(2); - heap.insert(3); - heap.insert(1); - heap.in_order(); - Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3, 1]")); - Assertions.assertTrue(heap.extract_min() == 1); - Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3]")); - heap.insert(8); - heap.insert(12); - heap.insert(4); - Assertions.assertTrue(heap.in_order().toString().equals("[8, 3, 12, 2, 6, 4]")); - heap.clear(); - Assertions.assertTrue(heap.isEmpty()); - } + + @Test + void testLeftistHeap() { + LeftistHeap heap = new LeftistHeap(); + Assertions.assertTrue(heap.isEmpty()); + heap.insert(6); + Assertions.assertTrue(!heap.isEmpty()); + heap.insert(2); + heap.insert(3); + heap.insert(1); + heap.in_order(); + Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3, 1]")); + Assertions.assertTrue(heap.extract_min() == 1); + Assertions.assertTrue(heap.in_order().toString().equals("[6, 2, 3]")); + heap.insert(8); + heap.insert(12); + heap.insert(4); + Assertions.assertTrue(heap.in_order().toString().equals("[8, 3, 12, 2, 6, 4]")); + heap.clear(); + Assertions.assertTrue(heap.isEmpty()); + } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java index 94896132cb36..57eedb97c202 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java @@ -1,12 +1,10 @@ package com.thealgorithms.datastructures.lists; - -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class SinglyLinkedListTest { @@ -23,7 +21,7 @@ private SinglyLinkedList createSampleList(int length) { } for (int i = 0; i < length - 1; i++) { - nodeList.get(i).next = nodeList.get(i+1); + nodeList.get(i).next = nodeList.get(i + 1); } return new SinglyLinkedList(nodeList.get(0), length); @@ -31,7 +29,7 @@ private SinglyLinkedList createSampleList(int length) { @Test void detectLoop() { - //List has cycle + // List has cycle Node firstNode = new Node(1); Node secondNode = new Node(2); Node thirdNode = new Node(3); @@ -53,16 +51,16 @@ void detectLoop() { void middle() { int oddNumberOfNode = 7; SinglyLinkedList list = createSampleList(oddNumberOfNode); - assertEquals(oddNumberOfNode/2 + 1, list.middle().value); + assertEquals(oddNumberOfNode / 2 + 1, list.middle().value); int evenNumberOfNode = 8; list = createSampleList(evenNumberOfNode); - assertEquals(evenNumberOfNode/2, list.middle().value); + assertEquals(evenNumberOfNode / 2, list.middle().value); - //return null if empty + // return null if empty list = new SinglyLinkedList(); assertNull(list.middle()); - //return head if there is only one node + // return head if there is only one node list = createSampleList(1); assertEquals(list.getHead(), list.middle()); } @@ -72,7 +70,7 @@ void swap() { SinglyLinkedList list = createSampleList(5); assertEquals(1, list.getHead().value); assertEquals(5, list.getNth(4)); - list.swapNodes(1,5); + list.swapNodes(1, 5); assertEquals(5, list.getHead().value); assertEquals(1, list.getNth(4)); } @@ -97,67 +95,69 @@ void search() { void deleteNth() { SinglyLinkedList list = createSampleList(10); assertTrue(list.search(7)); - list.deleteNth(6); //Index 6 has value 7 + list.deleteNth(6); // Index 6 has value 7 assertFalse(list.search(7)); } - //Test to check whether the method reverseList() works fine + // Test to check whether the method reverseList() works fine @Test - void reverseList(){ + void reverseList() { - //Creating a new LinkedList of size:4 - //The linkedlist will be 1->2->3->4->null + // Creating a new LinkedList of size:4 + // The linkedlist will be 1->2->3->4->null SinglyLinkedList list = createSampleList(4); - - //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node - //The reversed linkedlist will be 4->3->2->1->null - Node head=list.reverseList(list.getHead()); - - //Recording the Nodes after reversing the LinkedList - Node firstNode = head; //4 - Node secondNode = firstNode.next; //3 - Node thirdNode = secondNode.next; //2 - Node fourthNode = thirdNode.next; //1 - - //Checking whether the LinkedList is reversed or not by comparing the original list and reversed list nodes - assertEquals(1,fourthNode.value); - assertEquals(2,thirdNode.value); - assertEquals(3,secondNode.value); - assertEquals(4,firstNode.value); + + // Reversing the LinkedList using reverseList() method and storing the head of the reversed + // linkedlist in a head node The reversed linkedlist will be 4->3->2->1->null + Node head = list.reverseList(list.getHead()); + + // Recording the Nodes after reversing the LinkedList + Node firstNode = head; // 4 + Node secondNode = firstNode.next; // 3 + Node thirdNode = secondNode.next; // 2 + Node fourthNode = thirdNode.next; // 1 + + // Checking whether the LinkedList is reversed or not by comparing the original list and + // reversed list nodes + assertEquals(1, fourthNode.value); + assertEquals(2, thirdNode.value); + assertEquals(3, secondNode.value); + assertEquals(4, firstNode.value); } - - //Test to check whether implemented reverseList() method handles NullPointer Exception for TestCase where head==null + + // Test to check whether implemented reverseList() method handles NullPointer Exception for + // TestCase where head==null @Test - void reverseListNullPointer(){ - //Creating a linkedlist with first node assigned to null - SinglyLinkedList list=new SinglyLinkedList(); - Node first=list.getHead(); - - //Reversing the linkedlist - Node head=list.reverseList(first); - - //checking whether the method works fine if the input is null - assertEquals(head,first); + void reverseListNullPointer() { + // Creating a linkedlist with first node assigned to null + SinglyLinkedList list = new SinglyLinkedList(); + Node first = list.getHead(); + + // Reversing the linkedlist + Node head = list.reverseList(first); + + // checking whether the method works fine if the input is null + assertEquals(head, first); } - //Testing reverseList() method for a linkedlist of size: 20 + // Testing reverseList() method for a linkedlist of size: 20 @Test - void reverseListTest(){ - //Creating a new linkedlist + void reverseListTest() { + // Creating a new linkedlist SinglyLinkedList list = createSampleList(20); - //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node - Node head=list.reverseList(list.getHead()); - - //Storing the head in a temp variable, so that we cannot loose the track of head - Node temp=head; - - int i=20; //This is for the comparison of values of nodes of the reversed linkedlist - //Checking whether the reverseList() method performed its task - while(temp!=null && i>0){ - assertEquals(i,temp.value); - temp=temp.next; - i--; + // Reversing the LinkedList using reverseList() method and storing the head of the reversed + // linkedlist in a head node + Node head = list.reverseList(list.getHead()); + + // Storing the head in a temp variable, so that we cannot loose the track of head + Node temp = head; + + int i = 20; // This is for the comparison of values of nodes of the reversed linkedlist + // Checking whether the reverseList() method performed its task + while (temp != null && i > 0) { + assertEquals(i, temp.value); + temp = temp.next; + i--; } } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java index 9214b613246c..fb45fa5677ab 100644 --- a/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java +++ b/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java @@ -69,16 +69,14 @@ void removeFromTail() { @Test void checkSortedOnLowestLayer() { SkipList<String> skipList = new SkipList<>(); - String[] values = { "d", "b", "a", "c" }; + String[] values = {"d", "b", "a", "c"}; 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); + assertArrayEquals(new String[] {"a", "b", "c", "d"}, actualOrder); } private SkipList<String> createSkipList() { diff --git a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java index e153890ee204..5bc90fc06815 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java @@ -1,29 +1,26 @@ package com.thealgorithms.datastructures.queues; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; class LinkedQueueTest { - @Test - public void testQue() { - LinkedQueue<Integer> queue = new LinkedQueue<>(); - for (int i = 1; i < 5; i++) - queue.enqueue(i); + @Test + public void testQue() { + LinkedQueue<Integer> queue = new LinkedQueue<>(); + for (int i = 1; i < 5; i++) queue.enqueue(i); - assertEquals(queue.peekRear(), 4); - assertEquals(queue.peek(2), 2); + assertEquals(queue.peekRear(), 4); + assertEquals(queue.peek(2), 2); - assertEquals(queue.peek(4), 4); + assertEquals(queue.peek(4), 4); - final int[] element = { 1 }; + final int[] element = {1}; - // iterates over all the elements present - // as in the form of nodes - queue.forEach(integer -> { - if (element[0]++ != integer) - throw new AssertionError(); - }); - } + // iterates over all the elements present + // as in the form of nodes + queue.forEach(integer -> { + if (element[0]++ != integer) throw new AssertionError(); + }); + } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java b/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java index e5af3026a795..1a3b5aadebb2 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java @@ -26,7 +26,7 @@ void testPQDeletion() { myQueue.insert(5); myQueue.insert(3); myQueue.insert(10); - + myQueue.remove(); Assertions.assertEquals(myQueue.peek(), 5); myQueue.remove(); @@ -46,7 +46,7 @@ void testPQExtra() { myQueue.insert(10); Assertions.assertEquals(myQueue.isEmpty(), false); Assertions.assertEquals(myQueue.isFull(), true); - + myQueue.remove(); Assertions.assertEquals(myQueue.getSize(), 3); Assertions.assertEquals(myQueue.peek(), 5); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java index 83458f6f8d79..aab3b82c45eb 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java @@ -15,19 +15,19 @@ public void testNullArray() { @Test public void testEmptyArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {}); Assertions.assertNull(actualBST); } @Test public void testSingleElementArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{Integer.MIN_VALUE}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {Integer.MIN_VALUE}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } @Test public void testCreateBSTFromSmallArray() { - BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{1, 2, 3}); + BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[] {1, 2, 3}); Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST)); } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java index 2ed3b534ee8f..b153c5d667de 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java @@ -6,73 +6,71 @@ public class BinaryTreeTest { - //checks that adding populating the tree and searching for data - //retrieves the expected data -@Test -void test1(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - + // checks that adding populating the tree and searching for data + // retrieves the expected data + @Test + void test1() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); - assertEquals(t.find(5).data, 5); - assertEquals(t.find(7).data, 7); -} + assertEquals(t.find(5).data, 5); + assertEquals(t.find(7).data, 7); + } - //checks that removing data from the tree - //properly removes and makes the new root the expected new root -@Test -void test2(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); - t.remove(3); - t.remove(5); - t.remove(7); - + // checks that removing data from the tree + // properly removes and makes the new root the expected new root + @Test + void test2() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); + t.remove(3); + t.remove(5); + t.remove(7); - assertEquals(t.getRoot().data, 9); -} + assertEquals(t.getRoot().data, 9); + } -//checks that removing an unexistend node returns false -// as specified by the documentation of the function -@Test -void test3(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); + // checks that removing an unexistend node returns false + // as specified by the documentation of the function + @Test + void test3() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); -} + assertEquals(t.remove(9), true); + assertEquals(t.remove(398745987), false); + } -//check if the bfs, inOrder, preOrder and postOrder functions -//worg as expected, also increases the coverage measures in -//JaCoCo -@Test -void test4(){ - BinaryTree t = new BinaryTree(); - t.put(3); - t.put(5); - t.put(7); - t.put(9); - t.put(12); + // check if the bfs, inOrder, preOrder and postOrder functions + // worg as expected, also increases the coverage measures in + // JaCoCo + @Test + void test4() { + BinaryTree t = new BinaryTree(); + t.put(3); + t.put(5); + t.put(7); + t.put(9); + t.put(12); - t.bfs(t.find(12)); - t.inOrder(t.getRoot()); - t.preOrder(t.getRoot()); - t.postOrder(t.getRoot()); + t.bfs(t.find(12)); + t.inOrder(t.getRoot()); + t.preOrder(t.getRoot()); + t.postOrder(t.getRoot()); - assertEquals(t.remove(9), true); - assertEquals(t.remove(398745987), false); -} + assertEquals(t.remove(9), true); + assertEquals(t.remove(398745987), false); + } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java index ab865ff64404..779c68137e42 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java @@ -1,11 +1,11 @@ package com.thealgorithms.datastructures.trees; -import com.thealgorithms.datastructures.trees.BinaryTree.Node; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import com.thealgorithms.datastructures.trees.BinaryTree.Node; +import org.junit.jupiter.api.Test; + public class CeilInBinarySearchTreeTest { @Test @@ -15,37 +15,37 @@ public void testRootNull() { @Test public void testKeyPresentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 100).data); } @Test public void testKeyPresentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200}); assertEquals(10, CeilInBinarySearchTree.getCeil(root, 10).data); } @Test public void testKeyAbsentRootIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(100, CeilInBinarySearchTree.getCeil(root, 75).data); } @Test public void testKeyAbsentLeafIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(50, CeilInBinarySearchTree.getCeil(root, 40).data); } @Test public void testKeyAbsentLeftMostNodeIsCeil() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertEquals(5, CeilInBinarySearchTree.getCeil(root, 1).data); } @Test public void testKeyAbsentCeilIsNull() { - final Node root = TreeTestUtils.createTree(new Integer[]{100, 10, 200, 5, 50, 150, 300}); + final Node root = TreeTestUtils.createTree(new Integer[] {100, 10, 200, 5, 50, 150, 300}); assertNull(CeilInBinarySearchTree.getCeil(root, 400)); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java index 041b2eea20b2..db444e7d7a38 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author Albina Gimaletdinova on 17/02/2023 */ @@ -16,7 +16,7 @@ public void testRootNull() { @Test public void testOneNode() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{Integer.MIN_VALUE}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {Integer.MIN_VALUE}); assertTrue(CheckBinaryTreeIsValidBST.isBST(root)); } @@ -29,7 +29,8 @@ public void testOneNode() { */ @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)); } @@ -42,7 +43,8 @@ public void testBinaryTreeIsBST() { */ @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)); } @@ -55,7 +57,8 @@ public void testBinaryTreeWithDuplicatedNodesIsNotBST() { */ @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/CheckTreeIsSymmetricTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java index 932d5b882cf9..a610a32aa91f 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author kumanoit on 10/10/22 IST 1:02 AM */ @@ -17,20 +17,19 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,4,4,3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 4, 4, 3}); assertTrue(CheckTreeIsSymmetric.isSymmetric(root)); } @Test public void testNonSymmetricTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1,2,2,3,5,4,3}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 2, 3, 5, 4, 3}); assertFalse(CheckTreeIsSymmetric.isSymmetric(root)); } - } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java index 59352f543914..5329776847e9 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.datastructures.trees; +import java.util.Arrays; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import java.util.Arrays; - /** * @author Albina Gimaletdinova on 14/05/2023 */ @@ -13,7 +12,8 @@ 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,7 +28,8 @@ public void testOnEmptyArraysShouldCreateNullTree() { // 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); @@ -43,7 +44,8 @@ public void testOnSingleNodeTreeShouldCreateCorrectTree() { // 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); @@ -58,7 +60,8 @@ public void testOnRightSkewedTreeShouldCreateCorrectTree() { // 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); @@ -73,7 +76,8 @@ public void testOnLeftSkewedTreeShouldCreateCorrectTree() { // 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); @@ -88,7 +92,8 @@ public void testOnNormalTreeShouldCreateCorrectTree() { // 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 6b882cae8e04..2b85cf0c1c0f 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 21/02/2023 @@ -26,7 +25,7 @@ public void testNullRoot() { */ @Test public void testRecursiveInorder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List<Integer> expected = List.of(4, 2, 5, 1, 6, 3, 7); assertEquals(expected, InorderTraversal.recursiveInorder(root)); @@ -44,7 +43,8 @@ public void testRecursiveInorder() { */ @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<Integer> expected = List.of(5, 6, 7, 8); assertEquals(expected, InorderTraversal.recursiveInorder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java index e4080373e340..49babb033e81 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java @@ -7,18 +7,18 @@ public class KDTreeTest { KDTree.Point pointOf(int x, int y) { - return new KDTree.Point(new int[] { x, y }); + return new KDTree.Point(new int[] {x, y}); } @Test void findMin() { int[][] coordinates = { - { 30, 40 }, - { 5, 25 }, - { 70, 70 }, - { 10, 12 }, - { 50, 30 }, - { 35, 45 }, + {30, 40}, + {5, 25}, + {70, 70}, + {10, 12}, + {50, 30}, + {35, 45}, }; KDTree kdTree = new KDTree(coordinates); @@ -29,12 +29,12 @@ void findMin() { @Test void delete() { int[][] coordinates = { - { 30, 40 }, - { 5, 25 }, - { 70, 70 }, - { 10, 12 }, - { 50, 30 }, - { 35, 45 }, + {30, 40}, + {5, 25}, + {70, 70}, + {10, 12}, + {50, 30}, + {35, 45}, }; KDTree kdTree = new KDTree(coordinates); @@ -46,12 +46,12 @@ void delete() { @Test void findNearest() { int[][] coordinates = { - { 2, 3 }, - { 5, 4 }, - { 9, 6 }, - { 4, 7 }, - { 8, 1 }, - { 7, 2 }, + {2, 3}, + {5, 4}, + {9, 6}, + {4, 7}, + {8, 1}, + {7, 2}, }; KDTree kdTree = new KDTree(coordinates); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java index bbec32a71c89..6df221280f86 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java @@ -8,7 +8,7 @@ public class LazySegmentTreeTest { @Test void build() { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRoot().getValue()); assertEquals(15, lazySegmentTree.getRoot().getLeft().getValue()); @@ -17,7 +17,7 @@ void build() { @Test void update() { - int[] arr = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; + int[] arr = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(10, lazySegmentTree.getRoot().getValue()); @@ -36,7 +36,7 @@ void update() { @Test void get() { - int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); assertEquals(55, lazySegmentTree.getRange(0, 10)); assertEquals(3, lazySegmentTree.getRange(0, 2)); @@ -46,14 +46,15 @@ void get() { @Test void updateAndGet() { - int[] arr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); - for (int i = 0; i < 10; i++) for (int j = i + 1; j < 10; j++) { - lazySegmentTree.updateRange(i, j, 1); - assertEquals(j - i, lazySegmentTree.getRange(i, j)); - lazySegmentTree.updateRange(i, j, -1); - assertEquals(0, lazySegmentTree.getRange(i, j)); - } + for (int i = 0; i < 10; i++) + for (int j = i + 1; j < 10; j++) { + lazySegmentTree.updateRange(i, j, 1); + assertEquals(j - i, lazySegmentTree.getRange(i, j)); + lazySegmentTree.updateRange(i, j, -1); + assertEquals(0, lazySegmentTree.getRange(i, j)); + } } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java index 8b0a6b65b011..d8f5ed929b47 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 08/02/2023 @@ -18,7 +17,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(List.of(50)), LevelOrderTraversal.traverse(root)); } @@ -31,8 +30,9 @@ public void testSingleNodeTree() { */ @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)); + 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)); } /* @@ -47,8 +47,8 @@ public void testLevelOrderTraversalCompleteTree() { @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}); + 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)); + 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 2774dc099938..1104aa242ace 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * Given tree is traversed in a 'post-order' way: LEFT -> RIGHT -> ROOT. @@ -28,7 +27,7 @@ public void testNullRoot() { */ @Test public void testPostOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List<Integer> expected = List.of(4, 5, 2, 6, 7, 3, 1); assertEquals(expected, PostOrderTraversal.recursivePostOrder(root)); @@ -46,7 +45,8 @@ public void testPostOrder() { */ @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<Integer> 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 6f4106978a06..4e1f710224d9 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 17/02/2023 @@ -26,7 +25,7 @@ public void testNullRoot() { */ @Test public void testRecursivePreOrder() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); List<Integer> expected = List.of(1, 2, 4, 5, 3, 6, 7); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); @@ -44,7 +43,8 @@ public void testRecursivePreOrder() { */ @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<Integer> expected = List.of(5, 6, 7, 8); assertEquals(expected, PreOrderTraversal.recursivePreOrder(root)); diff --git a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java index 365ee99f75d9..440222880517 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; + /** * @author Albina Gimaletdinova on 12/01/2023 */ @@ -16,14 +16,14 @@ public void testBothRootsAreNull() { @Test public void testOneRootIsNull() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {100}); assertFalse(SameTreesCheck.check(root, null)); } @Test public void testSingleNodeTreesAreSame() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{100}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{100}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {100}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {100}); assertTrue(SameTreesCheck.check(p, q)); } @@ -36,12 +36,11 @@ public void testSingleNodeTreesAreSame() { */ @Test public void testSameTreesIsSuccessful() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); assertTrue(SameTreesCheck.check(p, q)); } - /* 1 1 / \ / \ @@ -51,8 +50,8 @@ public void testSameTreesIsSuccessful() { */ @Test public void testSameTreesFails() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6}); assertFalse(SameTreesCheck.check(p, q)); } @@ -63,9 +62,8 @@ public void testSameTreesFails() { */ @Test public void testTreesWithDifferentStructure() { - final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[]{1, 2}); - final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[]{1, null, 2}); + final BinaryTree.Node p = TreeTestUtils.createTree(new Integer[] {1, 2}); + final BinaryTree.Node q = TreeTestUtils.createTree(new Integer[] {1, null, 2}); assertFalse(SameTreesCheck.check(p, q)); } } - diff --git a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java index 454aaae0ec74..3bd197bf8bf8 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java @@ -1,8 +1,8 @@ package com.thealgorithms.datastructures.trees; +import com.thealgorithms.datastructures.trees.BinaryTree.Node; import java.util.LinkedList; import java.util.Queue; -import com.thealgorithms.datastructures.trees.BinaryTree.Node; public class TreeTestUtils { diff --git a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java index 74b036d1f23b..4b80a30804a6 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 13/01/2023 @@ -18,7 +17,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(50), VerticalOrderTraversal.verticalTraversal(root)); } @@ -31,7 +30,7 @@ public void testSingleNodeTree() { */ @Test public void testVerticalTraversalCompleteTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{1, 2, 3, 4, 5, 6, 7}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, 4, 5, 6, 7}); assertEquals(List.of(4, 2, 1, 5, 6, 3, 7), VerticalOrderTraversal.verticalTraversal(root)); } @@ -47,7 +46,8 @@ public void testVerticalTraversalCompleteTree() { @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)); + 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 6b89fcff7862..5ac0012ba454 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.datastructures.trees; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Collections; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /** * @author Albina Gimaletdinova on 11/01/2023 @@ -18,7 +17,7 @@ public void testRootNull() { @Test public void testSingleNodeTree() { - final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{50}); + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {50}); assertEquals(List.of(List.of(50)), ZigzagTraversal.traverse(root)); } @@ -31,8 +30,9 @@ public void testSingleNodeTree() { */ @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)); + 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)); } /* @@ -47,8 +47,8 @@ public void testZigzagTraversalCompleteTree() { @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}); + 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)); + ZigzagTraversal.traverse(root)); } } diff --git a/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java b/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java index df9cce34ff79..bf1a60e84e77 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java @@ -35,5 +35,4 @@ public void testPower() { assertEquals(1, new BinaryExponentiation().power(1, 10000000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 100000000000000000L)); } - } diff --git a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java index adc6871baa0b..7fb4f178f835 100644 --- a/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java +++ b/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java @@ -13,30 +13,29 @@ class StrassenMatrixMultiplicationTest { @Test public void StrassenMatrixMultiplicationTest2x2() { - int[][] A = { { 1, 2 }, { 3, 4 } }; - int[][] B = { { 5, 6 }, { 7, 8 } }; - int[][] expResult = { { 19, 22 }, { 43, 50 } }; + int[][] A = {{1, 2}, {3, 4}}; + int[][] B = {{5, 6}, {7, 8}}; + int[][] expResult = {{19, 22}, {43, 50}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } @Test void StrassenMatrixMultiplicationTest4x4() { - int[][] A = { { 1, 2, 5, 4 }, { 9, 3, 0, 6 }, { 4, 6, 3, 1 }, { 0, 2, 0, 6 } }; - int[][] B = { { 1, 0, 4, 1 }, { 1, 2, 0, 2 }, { 0, 3, 1, 3 }, { 1, 8, 1, 2 } }; - int[][] expResult = { { 7, 51, 13, 28 }, { 18, 54, 42, 27 }, { 11, 29, 20, 27 }, { 8, 52, 6, 16 } }; + int[][] A = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}}; + int[][] B = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}}; + int[][] expResult = {{7, 51, 13, 28}, {18, 54, 42, 27}, {11, 29, 20, 27}, {8, 52, 6, 16}}; int[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } @Test 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[][] 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[][] actResult = SMM.multiply(A, B); assertArrayEquals(expResult, actResult); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java index 7d13caabf757..bc569cc294b0 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java @@ -1,28 +1,28 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class EggDroppingTest { @Test - void hasMultipleEggSingleFloor(){ - assertEquals(1,EggDropping.minTrials(3,1)); + void hasMultipleEggSingleFloor() { + assertEquals(1, EggDropping.minTrials(3, 1)); } @Test - void hasSingleEggSingleFloor(){ - assertEquals(1,EggDropping.minTrials(1,1)); + void hasSingleEggSingleFloor() { + assertEquals(1, EggDropping.minTrials(1, 1)); } @Test - void hasSingleEggMultipleFloor(){ - assertEquals(3,EggDropping.minTrials(1,3)); + void hasSingleEggMultipleFloor() { + assertEquals(3, EggDropping.minTrials(1, 3)); } @Test - void hasMultipleEggMultipleFloor(){ - assertEquals(7,EggDropping.minTrials(100,101)); + void hasMultipleEggMultipleFloor() { + assertEquals(7, EggDropping.minTrials(100, 101)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java index 7d06618c4fd6..0a15144feee8 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java @@ -1,34 +1,34 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class KnapsackMemoizationTest { KnapsackMemoization knapsackMemoization = new KnapsackMemoization(); @Test void Test1() { - int[] weight = { 1, 3, 4, 5 }; - int[] value = { 1, 4, 5, 7 }; + int[] weight = {1, 3, 4, 5}; + int[] value = {1, 4, 5, 7}; int capacity = 10; assertEquals(13, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } @Test void Test2() { - int[] weight = { 95, 4, 60, 32, 23, 72, 80, 62, 65, 46 }; - int[] value = { 55, 10, 47, 5, 4, 50, 8, 61, 85, 87 }; + int[] weight = {95, 4, 60, 32, 23, 72, 80, 62, 65, 46}; + int[] value = {55, 10, 47, 5, 4, 50, 8, 61, 85, 87}; int capacity = 269; assertEquals(295, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } @Test void Test3() { - int[] weight = { 10, 20, 30 }; - int[] value = { 60, 100, 120 }; + int[] weight = {10, 20, 30}; + int[] value = {60, 100, 120}; int capacity = 50; assertEquals(220, knapsackMemoization.knapSack(capacity, weight, value, weight.length)); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java index 4e3cfa3c4b7d..a22bf3fea30c 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java @@ -1,10 +1,10 @@ package com.thealgorithms.dynamicprogramming; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import static org.junit.jupiter.api.Assertions.assertEquals; - public class LevenshteinDistanceTests { @ParameterizedTest @@ -13,5 +13,4 @@ void levenshteinDistanceTest(String str1, String str2, int distance) { int result = LevenshteinDistance.calculateLevenshteinDistance(str1, str2); assertEquals(distance, result); } - } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java index 9b1afc6d1266..7e673ed75f9c 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java @@ -1,127 +1,101 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + /** * @author georgioct@csd.auth.gr */ public class OptimalJobSchedulingTest { @Test - public void testOptimalJobScheduling1(){ + public void testOptimalJobScheduling1() { int numberProcesses = 5; int numberMachines = 4; - int[][] Run = { - {5, 1, 3, 2}, - {4, 2, 1, 3}, - {1, 5, 2, 1}, - {2, 3, 4, 2}, - {1, 1, 3, 1}}; + int[][] Run = {{5, 1, 3, 2}, {4, 2, 1, 3}, {1, 5, 2, 1}, {2, 3, 4, 2}, {1, 1, 3, 1}}; - int[][] Transfer = { - {0, 1, 2, 4}, - {1, 0, 2, 3}, - {2, 2, 0, 1}, - {4, 3, 1, 0}}; + 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(); + int[][] costs = {{5, 1, 3, 2}, {6, 3, 4, 5}, {5, 8, 6, 6}, {7, 9, 10, 8}, {8, 9, 12, 9}}; - int[][] costs = { - {5, 1, 3, 2}, - {6, 3, 4, 5}, - {5, 8, 6, 6}, - {7, 9, 10, 8}, - {8, 9, 12, 9}}; - - for (int i=0; i < numberProcesses; i++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++){ + for (int j = 0; j < numberMachines; j++) { - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } @Test - public void testOptimalJobScheduling2(){ + public void testOptimalJobScheduling2() { int numberProcesses = 3; int numberMachines = 3; - int[][] Run = { - {5, 1, 3}, - {4, 2, 1}, - {1, 5, 2}}; + int[][] Run = {{5, 1, 3}, {4, 2, 1}, {1, 5, 2}}; - int[][] Transfer = { - {0, 1, 2}, - {1, 0, 2}, - {2, 2, 0}}; + 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(); - int[][] costs = { - {5, 1, 3}, - {6, 3, 4}, - {5, 8, 6}}; + int[][] costs = {{5, 1, 3}, {6, 3, 4}, {5, 8, 6}}; - for (int i=0; i < numberProcesses; i++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++){ + for (int j = 0; j < numberMachines; j++) { - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } @Test - public void testOptimalJobScheduling3(){ + public void testOptimalJobScheduling3() { int numberProcesses = 6; int numberMachines = 4; int[][] Run = { - {5, 1, 3, 2}, - {4, 2, 1, 1}, - {1, 5, 2, 6}, - {1, 1, 2, 3}, - {2, 1, 4, 6}, - {3, 2, 2, 3}, + {5, 1, 3, 2}, + {4, 2, 1, 1}, + {1, 5, 2, 6}, + {1, 1, 2, 3}, + {2, 1, 4, 6}, + {3, 2, 2, 3}, }; int[][] Transfer = { - {0, 1, 2, 1}, - {1, 0, 2, 3}, - {2, 2, 0, 2}, - {1, 3, 2, 0}, + {0, 1, 2, 1}, + {1, 0, 2, 3}, + {2, 2, 0, 2}, + {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++){ + for (int i = 0; i < numberProcesses; i++) { - for (int j=0; j < numberMachines; j++){ + for (int j = 0; j < numberMachines; j++) { - assertEquals(costs[i][j],opt.getCost(i,j)); + assertEquals(costs[i][j], opt.getCost(i, j)); } } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java index ad0aac266c8d..ebd6ba12d2a5 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java @@ -1,24 +1,24 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class PartitionProblemTest { @Test - public void testIfSumOfTheArrayIsOdd(){ - assertFalse(PartitionProblem.partition(new int[]{1, 2, 2})); + public void testIfSumOfTheArrayIsOdd() { + assertFalse(PartitionProblem.partition(new int[] {1, 2, 2})); } @Test - public void testIfSizeOfTheArrayIsOne(){ - assertFalse(PartitionProblem.partition(new int[]{2})); + public void testIfSizeOfTheArrayIsOne() { + assertFalse(PartitionProblem.partition(new int[] {2})); } @Test - public void testIfSumOfTheArrayIsEven1(){ - assertTrue(PartitionProblem.partition(new int[]{1, 2, 3, 6})); + public void testIfSumOfTheArrayIsEven1() { + assertTrue(PartitionProblem.partition(new int[] {1, 2, 3, 6})); } @Test - public void testIfSumOfTheArrayIsEven2(){ - assertFalse(PartitionProblem.partition(new int[]{1, 2, 3, 8})); + public void testIfSumOfTheArrayIsEven2() { + assertFalse(PartitionProblem.partition(new int[] {1, 2, 3, 8})); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java index 5a532067e020..13f7b6f9c408 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java @@ -1,30 +1,31 @@ package com.thealgorithms.dynamicprogramming; import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.jupiter.api.Test; public class SubsetCountTest { public static SubsetCount obj = new SubsetCount(); @Test - void hasMultipleSubset(){ - int[] arr = new int[]{1,2,3,3}; + void hasMultipleSubset() { + int[] arr = new int[] {1, 2, 3, 3}; assertEquals(3, obj.getCount(arr, 6)); } @Test - void singleElementSubset(){ - int[] arr = new int[]{1,1,1,1}; + void singleElementSubset() { + int[] arr = new int[] {1, 1, 1, 1}; assertEquals(4, obj.getCount(arr, 1)); } @Test - void hasMultipleSubsetSO(){ - int[] arr = new int[]{1,2,3,3}; + void hasMultipleSubsetSO() { + int[] arr = new int[] {1, 2, 3, 3}; assertEquals(3, obj.getCountSO(arr, 6)); } @Test - void singleSubsetSO(){ - int[] arr = new int[]{1,1,1,1}; - assertEquals(1,obj.getCountSO(arr, 4)); + void singleSubsetSO() { + int[] arr = new int[] {1, 1, 1, 1}; + assertEquals(1, obj.getCountSO(arr, 4)); } } diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java index bc6b4adb8486..7df3127eec82 100644 --- a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java +++ b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java @@ -1,24 +1,33 @@ package com.thealgorithms.dynamicprogramming; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class climbStairsTest { @Test - void climbStairsTestForTwo(){assertEquals(2, ClimbingStairs.numberOfWays(2));} + void climbStairsTestForTwo() { + assertEquals(2, ClimbingStairs.numberOfWays(2)); + } @Test - void climbStairsTestForZero(){assertEquals(0, ClimbingStairs.numberOfWays(0));} + void climbStairsTestForZero() { + assertEquals(0, ClimbingStairs.numberOfWays(0)); + } @Test - void climbStairsTestForOne(){assertEquals(1, ClimbingStairs.numberOfWays(1));} + void climbStairsTestForOne() { + assertEquals(1, ClimbingStairs.numberOfWays(1)); + } @Test - void climbStairsTestForFive(){assertEquals(8, ClimbingStairs.numberOfWays(5));} + void climbStairsTestForFive() { + assertEquals(8, ClimbingStairs.numberOfWays(5)); + } @Test - void climbStairsTestForThree(){assertEquals(3, ClimbingStairs.numberOfWays(3));} + void climbStairsTestForThree() { + assertEquals(3, ClimbingStairs.numberOfWays(3)); + } } diff --git a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java index c31802f9b31a..8d52f2b96e7b 100644 --- a/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java +++ b/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java @@ -1,16 +1,15 @@ package com.thealgorithms.geometry; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +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)}; + 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/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java index 5d0c3b06c369..5d4c0f84bffd 100644 --- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java +++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java @@ -1,102 +1,99 @@ package com.thealgorithms.io; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.*; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class BufferedReaderTest { - @Test - public void testPeeks() throws IOException { - String text = "Hello!\nWorld!"; - int len = text.length(); - byte[] bytes = text.getBytes(); - - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); - - // read the first letter - assertEquals(reader.read(), 'H'); - len--; - assertEquals(reader.available(), len); - - // position: H[e]llo!\nWorld! - // reader.read() will be == 'e' - assertEquals(reader.peek(1), 'l'); - assertEquals(reader.peek(2), 'l'); // second l - assertEquals(reader.peek(3), 'o'); - } - - @Test - public void testMixes() throws IOException { - String text = "Hello!\nWorld!"; - int len = text.length(); - byte[] bytes = text.getBytes(); - - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); - - // read the first letter - assertEquals(reader.read(), 'H'); // first letter - len--; - - assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H') - assertEquals(reader.read(), 'e'); // second letter - len--; - assertEquals(reader.available(), len); - - // position: H[e]llo!\nWorld! - assertEquals(reader.peek(2), 'o'); // second l - assertEquals(reader.peek(3), '!'); - assertEquals(reader.peek(4), '\n'); - - assertEquals(reader.read(), 'l'); // third letter - assertEquals(reader.peek(1), 'o'); // fourth letter - - for (int i = 0; i < 6; i++) - reader.read(); - try { - System.out.println((char) reader.peek(4)); - } catch (Exception ignored) { - System.out.println("[cached intentional error]"); - // intentional, for testing purpose + @Test + public void testPeeks() throws IOException { + String text = "Hello!\nWorld!"; + int len = text.length(); + byte[] bytes = text.getBytes(); + + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); + + // read the first letter + assertEquals(reader.read(), 'H'); + len--; + assertEquals(reader.available(), len); + + // position: H[e]llo!\nWorld! + // reader.read() will be == 'e' + assertEquals(reader.peek(1), 'l'); + assertEquals(reader.peek(2), 'l'); // second l + assertEquals(reader.peek(3), 'o'); + } + + @Test + public void testMixes() throws IOException { + String text = "Hello!\nWorld!"; + int len = text.length(); + byte[] bytes = text.getBytes(); + + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); + + // read the first letter + assertEquals(reader.read(), 'H'); // first letter + len--; + + assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H') + assertEquals(reader.read(), 'e'); // second letter + len--; + assertEquals(reader.available(), len); + + // position: H[e]llo!\nWorld! + assertEquals(reader.peek(2), 'o'); // second l + assertEquals(reader.peek(3), '!'); + assertEquals(reader.peek(4), '\n'); + + assertEquals(reader.read(), 'l'); // third letter + assertEquals(reader.peek(1), 'o'); // fourth letter + + for (int i = 0; i < 6; i++) reader.read(); + try { + System.out.println((char) reader.peek(4)); + } catch (Exception ignored) { + System.out.println("[cached intentional error]"); + // intentional, for testing purpose + } } - } - - @Test - public void testBlockPractical() throws IOException { - String text = "!Hello\nWorld!"; - byte[] bytes = text.getBytes(); - int len = bytes.length; - - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - BufferedReader reader = new BufferedReader(input); - - - assertEquals(reader.peek(), 'H'); - assertEquals(reader.read(), '!'); // read the first letter - len--; - - // this only reads the next 5 bytes (Hello) because - // the default buffer size = 5 - assertEquals(new String(reader.readBlock()), "Hello"); - len -= 5; - assertEquals(reader.available(), len); - - // maybe kind of a practical demonstration / use case - if (reader.read() == '\n') { - assertEquals(reader.read(), 'W'); - assertEquals(reader.read(), 'o'); - - // the rest of the blocks - assertEquals(new String(reader.readBlock()), "rld!"); - } else { - // should not reach - throw new IOException("Something not right"); + + @Test + public void testBlockPractical() throws IOException { + String text = "!Hello\nWorld!"; + byte[] bytes = text.getBytes(); + int len = bytes.length; + + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + BufferedReader reader = new BufferedReader(input); + + assertEquals(reader.peek(), 'H'); + assertEquals(reader.read(), '!'); // read the first letter + len--; + + // this only reads the next 5 bytes (Hello) because + // the default buffer size = 5 + assertEquals(new String(reader.readBlock()), "Hello"); + len -= 5; + assertEquals(reader.available(), len); + + // maybe kind of a practical demonstration / use case + if (reader.read() == '\n') { + assertEquals(reader.read(), 'W'); + assertEquals(reader.read(), 'o'); + + // the rest of the blocks + assertEquals(new String(reader.readBlock()), "rld!"); + } else { + // should not reach + throw new IOException("Something not right"); + } } - } } diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java index 2da961d7ca32..eba7f2b4c57a 100644 --- a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java +++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java @@ -13,10 +13,8 @@ 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 6322341da658..c1dae5746d37 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java @@ -15,10 +15,8 @@ void testGetMinValue() { @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 9f5a3730e272..3d1b58a5124c 100644 --- a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java +++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java @@ -10,14 +10,8 @@ public class AbsoluteValueTest { @Test void testGetAbsValue() { - Stream - .generate(() -> ThreadLocalRandom.current().nextInt()) + Stream.generate(() -> ThreadLocalRandom.current().nextInt()) .limit(1000) - .forEach(number -> - assertEquals( - Math.abs(number), - AbsoluteValue.getAbsValue(number) - ) - ); + .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 6020054c147e..3e4485e12c4c 100644 --- a/src/test/java/com/thealgorithms/maths/AreaTest.java +++ b/src/test/java/com/thealgorithms/maths/AreaTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + /** * @author Amarildo Aliaj */ @@ -67,24 +67,52 @@ void surfaceAreaCone() { @Test void testAllIllegalInput() { 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(10, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), - () -> 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(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), - () -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), - () -> 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.surfaceAreaCube(0)), + () + -> assertThrows(IllegalArgumentException.class, () -> Area.surfaceAreaSphere(0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(0, 10)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaRectangle(10, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaCylinder(0, 1)), + () + -> 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(1, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(0, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaParallelogram(1, 0)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(0, 1, 1)), + () + -> assertThrows( + IllegalArgumentException.class, () -> Area.surfaceAreaTrapezium(1, 0, 1)), + () + -> 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))); } } \ 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 29125efe5fbb..c322cdc6272c 100644 --- a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class AutomorphicNumberTest { @Test void testAutomorphicNumber() { - int[] trueTestCases = { 0, 1, 25, 625, 12890625}; - int[] falseTestCases = { -5, 2, 26, 1234 }; + int[] trueTestCases = {0, 1, 25, 625, 12890625}; + int[] falseTestCases = {-5, 2, 26, 1234}; for (Integer n : trueTestCases) { assertTrue(AutomorphicNumber.isAutomorphic(n)); assertTrue(AutomorphicNumber.isAutomorphic2(n)); @@ -19,7 +20,9 @@ void testAutomorphicNumber() { 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/AverageTest.java b/src/test/java/com/thealgorithms/maths/AverageTest.java index 3069c163bf71..2008232c3b18 100644 --- a/src/test/java/com/thealgorithms/maths/AverageTest.java +++ b/src/test/java/com/thealgorithms/maths/AverageTest.java @@ -30,5 +30,4 @@ public void testAverage_int_5() { int[] numbers = {2, 4, 10}; Assertions.assertEquals(5, Average.average(numbers)); } - } diff --git a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java index 504435aebce3..118e8db8726d 100644 --- a/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java +++ b/src/test/java/com/thealgorithms/maths/CollatzConjectureTest.java @@ -27,34 +27,13 @@ void nextNumberFromOddNumber() { @Test void collatzConjecture() { - final List<Integer> expected = List.of( - 35, - 106, - 53, - 160, - 80, - 40, - 20, - 10, - 5, - 16, - 8, - 4, - 2, - 1 - ); + final List<Integer> expected = List.of(35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1); assertIterableEquals(expected, cConjecture.collatzConjecture(35)); } @Test void sequenceOfNotNaturalFirstNumber() { - assertThrows( - IllegalArgumentException.class, - () -> cConjecture.collatzConjecture(0) - ); - assertThrows( - IllegalArgumentException.class, - () -> cConjecture.collatzConjecture(-1) - ); + assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(0)); + assertThrows(IllegalArgumentException.class, () -> cConjecture.collatzConjecture(-1)); } } diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index 1dfb92d0d1e3..de9f561b7e19 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -9,34 +9,24 @@ public class DistanceFormulaTest { @Test void euclideanTest1() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(1, 1, 2, 2), - 1.4142135623730951 - ); + Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 1, 2, 2), 1.4142135623730951); } @Test void euclideanTest2() { - Assertions.assertEquals( - DistanceFormula.euclideanDistance(1, 3, 8, 0), - 7.0710678118654755 - ); + Assertions.assertEquals(DistanceFormula.euclideanDistance(1, 3, 8, 0), 7.0710678118654755); } @Test void euclideanTest3() { Assertions.assertEquals( - DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), - 110.91911467371168 - ); + DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100), 110.91911467371168); } @Test void euclideanTest4() { Assertions.assertEquals( - DistanceFormula.euclideanDistance(1000, 13, 20000, 84), - 19022.067605809836 - ); + DistanceFormula.euclideanDistance(1000, 13, 20000, 84), 19022.067605809836); } @Test @@ -46,65 +36,53 @@ public void manhattantest1() { @Test public void manhattantest2() { - assertEquals( - DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), - 18.8 - ); + assertEquals(DistanceFormula.manhattanDistance(6.5, 8.4, 20.1, 13.6), 18.8); } @Test public void manhattanTest3() { - assertEquals( - DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), - 26.442 - ); + assertEquals(DistanceFormula.manhattanDistance(10.112, 50, 8, 25.67), 26.442); } @Test public void hammingTest1() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 0, 0, 0, 0 }; + int[] array1 = {1, 1, 1, 1}; + int[] array2 = {0, 0, 0, 0}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 4); } @Test public void hammingTest2() { - int[] array1 = { 1, 1, 1, 1 }; - int[] array2 = { 1, 1, 1, 1 }; + int[] array1 = {1, 1, 1, 1}; + int[] array2 = {1, 1, 1, 1}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 0); } @Test public void hammingTest3() { - int[] array1 = { 1, 0, 0, 1, 1, 0, 1, 1, 0 }; - int[] array2 = { 0, 1, 0, 0, 1, 1, 1, 0, 0 }; + int[] array1 = {1, 0, 0, 1, 1, 0, 1, 1, 0}; + int[] array2 = {0, 1, 0, 0, 1, 1, 1, 0, 0}; assertEquals(DistanceFormula.hammingDistance(array1, array2), 5); } @Test public void minkowskiTest1() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 1), 10); } @Test public void minkowskiTest2() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals( - DistanceFormula.minkowskiDistance(array1, array2, 2), - 5.477225575051661 - ); + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; + assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 2), 5.477225575051661); } @Test public void minkowskiTest3() { - double[] array1 = { 1, 3, 8, 5 }; - double[] array2 = { 4, 2, 6, 9 }; - assertEquals( - DistanceFormula.minkowskiDistance(array1, array2, 3), - 4.641588833612778 - ); + double[] array1 = {1, 3, 8, 5}; + double[] array2 = {4, 2, 6, 9}; + assertEquals(DistanceFormula.minkowskiDistance(array1, array2, 3), 4.641588833612778); } } diff --git a/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java b/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java index 24bdc864e957..e15ab0a589c1 100644 --- a/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/DudeneyNumberTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class DudeneyNumberTest { @Test @@ -13,6 +13,5 @@ void isDudeney() { assertTrue(() -> DudeneyNumber.isDudeney(validDudeneyNumber)); assertFalse(() -> DudeneyNumber.isDudeney(invalidDudeneyNumber)); - } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java index a7a18fe198f1..17f8d454c5ff 100644 --- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java @@ -9,33 +9,21 @@ public class FindMaxTest { @Test public void testFindMax0() { - assertEquals( - 10, - FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - ); + assertEquals(10, FindMax.findMax(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } @Test public void testFindMax1() { - assertEquals( - 7, - FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 }) - ); + assertEquals(7, FindMax.findMax(new int[] {6, 3, 5, 1, 7, 4, 1})); } @Test public void testFindMax2() { - assertEquals( - 10, - FindMax.findMax(new int[] { 10, 0 }) - ); + assertEquals(10, FindMax.findMax(new int[] {10, 0})); } @Test public void testFindMaxThrowsExceptionForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> FindMax.findMax(new int[]{}) - ); + assertThrows(IllegalArgumentException.class, () -> FindMax.findMax(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java index dc9835475a08..7599b9029bf1 100644 --- a/src/test/java/com/thealgorithms/maths/FindMinTest.java +++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java @@ -9,32 +9,26 @@ public class FindMinTest { @Test public void testFindMinValue() { - assertEquals( - 1, - FindMin.findMin(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - ); + assertEquals(1, FindMin.findMin(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})); } @Test public void test1() { - assertEquals(1, FindMin.findMin(new int[] { 1, 3, 5, 7, 9 })); + assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9})); } @Test public void test2() { - assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 })); + assertEquals(0, FindMin.findMin(new int[] {0, 192, 384, 576})); } @Test public void test3() { - assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 })); + assertEquals(0, FindMin.findMin(new int[] {10, 10, 0, 10})); } @Test public void testFindMinThrowsExceptionForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> FindMin.findMin(new int[]{}) - ); + assertThrows(IllegalArgumentException.class, () -> FindMin.findMin(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java index 1a8501eabe9e..a5fd867e900e 100644 --- a/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java @@ -6,43 +6,23 @@ public class FrizzyNumberTest { @Test public void testFrizziesForBase2() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(2, 1)); - assertEquals( - 3, - FrizzyNumber.getNthFrizzy(2, 3)); - assertEquals( - 1000, - FrizzyNumber.getNthFrizzy(2, 1000)); + assertEquals(1, FrizzyNumber.getNthFrizzy(2, 1)); + assertEquals(3, FrizzyNumber.getNthFrizzy(2, 3)); + assertEquals(1000, FrizzyNumber.getNthFrizzy(2, 1000)); } @Test public void testFrizziesForBase3() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(3, 1)); - assertEquals( - 3, - FrizzyNumber.getNthFrizzy(3, 2)); - assertEquals( - 29430, - FrizzyNumber.getNthFrizzy(3, 1000)); + assertEquals(1, FrizzyNumber.getNthFrizzy(3, 1)); + assertEquals(3, FrizzyNumber.getNthFrizzy(3, 2)); + assertEquals(29430, FrizzyNumber.getNthFrizzy(3, 1000)); } @Test public void testFrizziesForBase69() { - assertEquals( - 1, - FrizzyNumber.getNthFrizzy(69, 1)); - assertEquals( - 69, - FrizzyNumber.getNthFrizzy(69, 2)); - assertEquals( - 328510, - FrizzyNumber.getNthFrizzy(69, 9)); - assertEquals( - 333340, - FrizzyNumber.getNthFrizzy(69, 15)); + assertEquals(1, FrizzyNumber.getNthFrizzy(69, 1)); + assertEquals(69, FrizzyNumber.getNthFrizzy(69, 2)); + assertEquals(328510, FrizzyNumber.getNthFrizzy(69, 9)); + assertEquals(333340, FrizzyNumber.getNthFrizzy(69, 15)); } } diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java index bbf10cad0bdb..49a9023288c9 100644 --- a/src/test/java/com/thealgorithms/maths/GCDTest.java +++ b/src/test/java/com/thealgorithms/maths/GCDTest.java @@ -7,26 +7,17 @@ public class GCDTest { @Test void test1() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(-1, 0) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1, 0)); } @Test void test2() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(10, -2) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2)); } @Test void test3() { - Assertions.assertThrows( - ArithmeticException.class, - () -> GCD.gcd(-5, -3) - ); + Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3)); } @Test @@ -48,19 +39,20 @@ void test6() { void test7() { Assertions.assertEquals(GCD.gcd(9, 6), 3); } - + @Test void testArrayGcd1() { - Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3); + Assertions.assertEquals(GCD.gcd(new int[] {9, 6}), 3); } @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 void testArrayGcdForEmptyInput() { - Assertions.assertEquals(GCD.gcd(new int[]{}), 0); - } + Assertions.assertEquals(GCD.gcd(new int[] {}), 0); + } } diff --git a/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java b/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java index f9176961f2eb..bea4e0a63d1f 100644 --- a/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class HarshadNumberTest { @Test public void harshadNumber() { - + assertTrue(HarshadNumber.isHarshad(18)); assertFalse(HarshadNumber.isHarshad(-18)); assertFalse(HarshadNumber.isHarshad(19)); diff --git a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java index c3ccde86c4ce..32feeacdb916 100644 --- a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java @@ -17,17 +17,11 @@ void test2() { @Test void test3() { - Assertions.assertEquals( - HeronsFormula.Herons(1, 1, 1), - 0.4330127018922193 - ); + Assertions.assertEquals(HeronsFormula.Herons(1, 1, 1), 0.4330127018922193); } @Test void test4() { - Assertions.assertEquals( - HeronsFormula.Herons(4, 5, 8), - 8.181534085976786 - ); + Assertions.assertEquals(HeronsFormula.Herons(4, 5, 8), 8.181534085976786); } } diff --git a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java index 326c1a9a7305..52322e5558a9 100644 --- a/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java +++ b/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java @@ -3,7 +3,6 @@ import static org.junit.jupiter.api.Assertions.*; import java.util.List; - import org.junit.jupiter.api.Test; public class KaprekarNumbersTest { @@ -51,10 +50,7 @@ void testFor98() { @Test void testForRangeOfNumber() { try { - List<Long> rangedNumbers = KaprekarNumbers.kaprekarNumberInRange( - 1, - 100000 - ); + List<Long> rangedNumbers = KaprekarNumbers.kaprekarNumberInRange(1, 100000); long[] allTheNumbers = { 1, 9, diff --git a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java index 7af452e1b4c7..705f1a1006fa 100644 --- a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class LeonardoNumberTest { @Test void leonardoNumberNegative() { - assertThrows(ArithmeticException.class, ()-> LeonardoNumber.leonardoNumber(-1)); + assertThrows(ArithmeticException.class, () -> LeonardoNumber.leonardoNumber(-1)); } @Test void leonardoNumberZero() { @@ -23,6 +24,6 @@ void leonardoNumberFive() { } @Test void leonardoNumberTwenty() { - assertEquals(21891 , LeonardoNumber.leonardoNumber(20)); + assertEquals(21891, LeonardoNumber.leonardoNumber(20)); } } diff --git a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java index d8fd39d99339..526b6aa2b405 100644 --- a/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java @@ -8,65 +8,57 @@ class LiouvilleLambdaFunctionTest { @Test void testLiouvilleLambdaMustThrowExceptionIfNumberIsZero() { - //given + // given int number = 0; String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - } - ); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testLiouvilleLambdaMustThrowExceptionIfNumberIsNegative() { - //given + // given int number = -1; String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - LiouvilleLambdaFunction.liouvilleLambda(number); - } - ); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { LiouvilleLambdaFunction.liouvilleLambda(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testLiouvilleLambdaMustReturnNegativeOne() { - //given + // given int number = 11; int expectedOutput = -1; - //when + // when int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then + // then assertEquals(expectedOutput, actualOutput); } @Test void testLiouvilleLambdaMustReturnPositiveOne() { - //given + // given int number = 10; int expectedOutput = 1; - //when + // when int actualOutput = LiouvilleLambdaFunction.liouvilleLambda(number); - //then + // then assertEquals(expectedOutput, actualOutput); } } diff --git a/src/test/java/com/thealgorithms/maths/LongDivisionTest.java b/src/test/java/com/thealgorithms/maths/LongDivisionTest.java index 65ee328c054a..f0d702efa127 100644 --- a/src/test/java/com/thealgorithms/maths/LongDivisionTest.java +++ b/src/test/java/com/thealgorithms/maths/LongDivisionTest.java @@ -1,55 +1,58 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class LongDivisionTest { - // Requirement: Dividend (positive) is greater than divisor (positive), returns correct integer after division + // Requirement: Dividend (positive) is greater than divisor (positive), returns correct integer + // after division @Test void testOne() { - assertEquals(3, LongDivision.divide(10,3)); + assertEquals(3, LongDivision.divide(10, 3)); } - // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer after division + // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer + // after division @Test void testTwo() { - assertEquals(-2, LongDivision.divide(7,-3)); + assertEquals(-2, LongDivision.divide(7, -3)); } - - // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer after division - // Basically the same as in the first test + + // Requirement: Dividend (positive) is greater than divisor (negative), returns correct integer + // after division Basically the same as in the first test @Test void testThree() { - assertEquals(10, LongDivision.divide(105,10)); + assertEquals(10, LongDivision.divide(105, 10)); } // Requirement: Dividend (negative), divisor (positive), returns correct integer after division // Tests the case where the dividend is less than 0. @Test void testNegativeDividend() { - assertEquals(-1, LongDivision.divide(-5,3)); + assertEquals(-1, LongDivision.divide(-5, 3)); } - + // Requirement: Dividend (positive), divisor (positive), returns correct integer after division - // Tests the case where the dividend is less than the divisor. The test should return 0 in this case. + // Tests the case where the dividend is less than the divisor. The test should return 0 in this + // case. @Test void testDividendLessThanDivisor() { - assertEquals(0, LongDivision.divide(3,5)); + assertEquals(0, LongDivision.divide(3, 5)); } // Requirement: Dividend (neither), divisor (positive), returns correct integer after division // Tests the case where the dividend is 0. This should return a 0. @Test void testDividendIsZero() { - assertEquals(0, LongDivision.divide(0,5)); + assertEquals(0, LongDivision.divide(0, 5)); } // Requirement: Dividend (positive), divisor (neither), returns correct integer after division // Tests the case where the divisor is 0. This should return a 0. @Test void testDivisionByZero() { - assertEquals(0, LongDivision.divide(5,0)); + assertEquals(0, LongDivision.divide(5, 0)); } } diff --git a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java index e5ac62240989..3576268c5d0c 100644 --- a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java +++ b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java @@ -1,8 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class LucasSeriesTest { @Test void lucasSeriesTwo() { diff --git a/src/test/java/com/thealgorithms/maths/MedianTest.java b/src/test/java/com/thealgorithms/maths/MedianTest.java index f3825b7f12b7..d2b637abd3cb 100644 --- a/src/test/java/com/thealgorithms/maths/MedianTest.java +++ b/src/test/java/com/thealgorithms/maths/MedianTest.java @@ -1,8 +1,9 @@ package com.thealgorithms.maths; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class MedianTest { @Test void medianSingleValue() { diff --git a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java index f5897c2b8815..b4f51bf51cef 100644 --- a/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java +++ b/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java @@ -8,39 +8,31 @@ class MobiusFunctionTest { @Test void testMobiusForZero() { - //given + // given int number = 0; String expectedMessage = "Number must be greater than zero."; - //when + // when Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - MobiusFunction.mobius(number); - } - ); + IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @Test void testMobiusForNegativeNumber() { - //given + // given int number = -1; String expectedMessage = "Number must be greater than zero."; - //when + // when Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - MobiusFunction.mobius(number); - } - ); + IllegalArgumentException.class, () -> { MobiusFunction.mobius(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } @@ -150,13 +142,13 @@ void testMobiusFunction() { }; for (int i = 1; i <= 100; i++) { - //given + // given int expectedValue = expectedResultArray[i - 1]; - //when + // when int actualValue = MobiusFunction.mobius(i); - //then + // then assertEquals(expectedValue, actualValue); } } diff --git a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java index 597d08922069..3fe58dadf8a5 100644 --- a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; - import org.junit.jupiter.api.Test; public class NthUglyNumberTest { @@ -51,7 +50,7 @@ public void testGetWithSameObject() { for (final var tc : testCases.entrySet()) { assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue()); } - + assertEquals(uglyNumbers.get(999), 385875); } @@ -67,21 +66,14 @@ public void testGetWithBase2() { assertEquals(uglyNumbers.get(5), 32); } - @Test public void testGetThrowsAnErrorForNegativeInput() { var uglyNumbers = new NthUglyNumber(new int[] {1, 2}); - assertThrows( - IllegalArgumentException.class, - () -> uglyNumbers.get(-1) - ); + assertThrows(IllegalArgumentException.class, () -> uglyNumbers.get(-1)); } @Test public void testConstructorThrowsAnErrorForEmptyInput() { - assertThrows( - IllegalArgumentException.class, - () -> new NthUglyNumber(new int[] {}) - ); + assertThrows(IllegalArgumentException.class, () -> new NthUglyNumber(new int[] {})); } } diff --git a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java index a01c11038684..4f5ec4cef095 100644 --- a/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java +++ b/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java @@ -9,14 +9,14 @@ class PascalTriangleTest { @Test void testForOne() { int[][] result = PascalTriangle.pascal(1); - int[][] expected = { { 1 } }; + int[][] expected = {{1}}; assertArrayEquals(result, expected); } @Test void testForTwo() { int[][] result = PascalTriangle.pascal(2); - int[][] expected = { { 1, 0 }, { 1, 1 } }; + int[][] expected = {{1, 0}, {1, 1}}; assertArrayEquals(result, expected); } @@ -24,11 +24,11 @@ void testForTwo() { void testForFive() { int[][] result = PascalTriangle.pascal(5); int[][] expected = { - { 1, 0, 0, 0, 0 }, - { 1, 1, 0, 0, 0 }, - { 1, 2, 1, 0, 0 }, - { 1, 3, 3, 1, 0 }, - { 1, 4, 6, 4, 1 }, + {1, 0, 0, 0, 0}, + {1, 1, 0, 0, 0}, + {1, 2, 1, 0, 0}, + {1, 3, 3, 1, 0}, + {1, 4, 6, 4, 1}, }; assertArrayEquals(result, expected); } @@ -37,14 +37,14 @@ void testForFive() { void testForEight() { int[][] result = PascalTriangle.pascal(8); int[][] expected = { - { 1, 0, 0, 0, 0, 0, 0, 0 }, - { 1, 1, 0, 0, 0, 0, 0, 0 }, - { 1, 2, 1, 0, 0, 0, 0, 0 }, - { 1, 3, 3, 1, 0, 0, 0, 0 }, - { 1, 4, 6, 4, 1, 0, 0, 0 }, - { 1, 5, 10, 10, 5, 1, 0, 0 }, - { 1, 6, 15, 20, 15, 6, 1, 0 }, - { 1, 7, 21, 35, 35, 21, 7, 1 }, + {1, 0, 0, 0, 0, 0, 0, 0}, + {1, 1, 0, 0, 0, 0, 0, 0}, + {1, 2, 1, 0, 0, 0, 0, 0}, + {1, 3, 3, 1, 0, 0, 0, 0}, + {1, 4, 6, 4, 1, 0, 0, 0}, + {1, 5, 10, 10, 5, 1, 0, 0}, + {1, 6, 15, 20, 15, 6, 1, 0}, + {1, 7, 21, 35, 35, 21, 7, 1}, }; assertArrayEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java index adaccff0a40d..4dc7c8ce53ad 100644 --- a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; class PerfectNumberTest { @Test public void perfectNumber() { - int[] trueTestCases = { 6, 28, 496, 8128, 33550336 }; - int[] falseTestCases = { -6, 0, 1, 9, 123 }; + int[] trueTestCases = {6, 28, 496, 8128, 33550336}; + int[] falseTestCases = {-6, 0, 1, 9, 123}; for (Integer n : trueTestCases) { assertTrue(PerfectNumber.isPerfectNumber(n)); assertTrue(PerfectNumber.isPerfectNumber2(n)); diff --git a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java index 481260c9f1c9..487b477816fd 100644 --- a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java +++ b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java @@ -8,7 +8,7 @@ public class PerfectSquareTest { @Test public void TestPerfectSquareifiscorrect() { - //Valid Partition + // Valid Partition int number = 9; boolean result = PerfectSquare.isPerfectSquare(number); @@ -18,7 +18,7 @@ public void TestPerfectSquareifiscorrect() { @Test public void TestPerfectSquareifisnotcorrect() { - //Invalid Partition 1 + // Invalid Partition 1 int number = 3; boolean result = PerfectSquare.isPerfectSquare(number); @@ -28,7 +28,7 @@ public void TestPerfectSquareifisnotcorrect() { @Test public void TestPerfectSquareifisNegativeNumber() { - //Invalid Partition 2 + // Invalid Partition 2 int number = -10; boolean result = PerfectSquare.isPerfectSquare(number); diff --git a/src/test/java/com/thealgorithms/maths/PerimeterTest.java b/src/test/java/com/thealgorithms/maths/PerimeterTest.java index 5af109d5ef40..94d3d3ae0577 100644 --- a/src/test/java/com/thealgorithms/maths/PerimeterTest.java +++ b/src/test/java/com/thealgorithms/maths/PerimeterTest.java @@ -37,7 +37,7 @@ void testcase5() { void testcase6() { Assertions.assertEquals(43.982297150257104, Perimeter.perimeterCircle(7)); } - + // Perimeter of Irregular polygon @Test void testcase7() { diff --git a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java index d5d51600850c..83a52355326e 100644 --- a/src/test/java/com/thealgorithms/maths/PollardRhoTest.java +++ b/src/test/java/com/thealgorithms/maths/PollardRhoTest.java @@ -9,46 +9,42 @@ class PollardRhoTest { @Test void testPollardRhoForNumber315MustReturn5() { - //given + // given int number = 315; int expectedResult = 5; - //when + // when int actualResult = PollardRho.pollardRho(number); - //then + // then assertEquals(expectedResult, actualResult); } @Test void testPollardRhoForNumber187MustReturn11() { - //given + // given int number = 187; int expectedResult = 11; - //when + // when int actualResult = PollardRho.pollardRho(number); - //then + // then assertEquals(expectedResult, actualResult); } @Test void testPollardRhoForNumber239MustThrowException() { - //given + // given int number = 239; String expectedMessage = "GCD cannot be found."; - //when - Exception exception = assertThrows( - RuntimeException.class, - () -> { - PollardRho.pollardRho(number); - } - ); + // when + Exception exception + = assertThrows(RuntimeException.class, () -> { PollardRho.pollardRho(number); }); String actualMessage = exception.getMessage(); - //then + // then assertEquals(expectedMessage, actualMessage); } } diff --git a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java index 2a1f6f6e01b9..edc684481c2f 100644 --- a/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java +++ b/src/test/java/com/thealgorithms/maths/PrimeFactorizationTest.java @@ -9,23 +9,23 @@ class PrimeFactorizationTest { @Test void testpFactorsMustReturnEmptyList() { - //given + // given int n = 0; - //then + // then assertTrue(PrimeFactorization.pfactors(n).isEmpty()); } @Test void testpFactorsMustReturnNonEmptyList() { - //given + // given int n = 198; int expectedListSize = 4; - //when + // when List<Integer> actualResultList = PrimeFactorization.pfactors(n); - //then + // then assertEquals(expectedListSize, actualResultList.size()); assertEquals(2, actualResultList.get(0)); assertEquals(3, actualResultList.get(1)); diff --git a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java index 36a72c7ea138..e4ca04fd0403 100644 --- a/src/test/java/com/thealgorithms/maths/PronicNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/PronicNumberTest.java @@ -8,25 +8,25 @@ public class PronicNumberTest { @Test void testForPronicNumber() { - //given + // given int number = 30; - //when + // when boolean result = PronicNumber.isPronic(number); - //then + // then assertTrue(result); } @Test void testForNonPronicNumber() { - //given + // given int number = 21; - //when + // when boolean result = PronicNumber.isPronic(number); - //then + // then assertFalse(result); } } diff --git a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java index a6c25df5a541..e870962b185e 100644 --- a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java @@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; - import org.junit.jupiter.api.Test; public class ReverseNumberTest { @@ -25,9 +24,6 @@ public void testReverseNumber() { @Test public void testReverseNumberThrowsExceptionForNegativeInput() { - assertThrows( - IllegalArgumentException.class, - () -> ReverseNumber.reverseNumber(-1) - ); + assertThrows(IllegalArgumentException.class, () -> ReverseNumber.reverseNumber(-1)); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java index 88e670bf9668..a59c05832119 100644 --- a/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareFreeIntegerTest.java @@ -4,62 +4,153 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.List; - import org.junit.jupiter.api.Test; class SquareFreeIntegerTest { - @Test - void testIsSquareFreeInteger() { + @Test + void testIsSquareFreeInteger() { - //given - List<Integer> 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); + // given + List<Integer> 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 - boolean isNumberSquareFree = SquareFreeInteger.isSquareFreeInteger(i); - boolean isNumberPresentInList = listOfSquareFreeIntegers.contains(i); + for (int i = 1; i <= 2500; i++) { + // when + boolean isNumberSquareFree = SquareFreeInteger.isSquareFreeInteger(i); + boolean isNumberPresentInList = listOfSquareFreeIntegers.contains(i); - //then - assertEquals(isNumberSquareFree,isNumberPresentInList); - } - } + // then + assertEquals(isNumberSquareFree, isNumberPresentInList); + } + } - @Test - void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() { - //given - int number = 0; - String expectedMessage = "Number must be greater than zero."; + @Test + void testIsSquareFreeIntegerThrowExceptionIfNumberIsZero() { + // given + int number = 0; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - SquareFreeInteger.isSquareFreeInteger(number); - } - ); - String actualMessage = exception.getMessage(); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + // then + assertEquals(expectedMessage, actualMessage); + } - @Test - void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() { - //given - int number = -1; - String expectedMessage = "Number must be greater than zero."; + @Test + void testIsSquareFreeIntegerMustThrowExceptionIfNumberIsNegative() { + // given + int number = -1; + String expectedMessage = "Number must be greater than zero."; - //when - Exception exception = assertThrows( - IllegalArgumentException.class, - () -> { - SquareFreeInteger.isSquareFreeInteger(number); - } - ); - String actualMessage = exception.getMessage(); + // when + Exception exception = assertThrows(IllegalArgumentException.class, + () -> { SquareFreeInteger.isSquareFreeInteger(number); }); + String actualMessage = exception.getMessage(); - //then - assertEquals(expectedMessage, actualMessage); - } + // then + assertEquals(expectedMessage, actualMessage); + } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java index 36fbba375793..067b68962bdb 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonTestMethod.java @@ -7,25 +7,16 @@ public class SquareRootWithNewtonRaphsonTestMethod { @Test void testfor1() { - Assertions.assertEquals( - 1, - SquareRootWithNewtonRaphsonMethod.squareRoot(1) - ); + Assertions.assertEquals(1, SquareRootWithNewtonRaphsonMethod.squareRoot(1)); } @Test void testfor2() { - Assertions.assertEquals( - 1.414213562373095, - SquareRootWithNewtonRaphsonMethod.squareRoot(2) - ); + Assertions.assertEquals(1.414213562373095, SquareRootWithNewtonRaphsonMethod.squareRoot(2)); } @Test void testfor625() { - Assertions.assertEquals( - 25.0, - SquareRootWithNewtonRaphsonMethod.squareRoot(625) - ); + Assertions.assertEquals(25.0, SquareRootWithNewtonRaphsonMethod.squareRoot(625)); } } diff --git a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java index 7e8d916c6aa1..3d13e43665af 100644 --- a/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java +++ b/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java @@ -7,33 +7,21 @@ public class SquareRootwithBabylonianMethodTest { @Test void testfor4() { - Assertions.assertEquals( - 2, - SquareRootWithBabylonianMethod.square_Root(4) - ); + Assertions.assertEquals(2, SquareRootWithBabylonianMethod.square_Root(4)); } @Test void testfor1() { - Assertions.assertEquals( - 1, - SquareRootWithBabylonianMethod.square_Root(1) - ); + Assertions.assertEquals(1, SquareRootWithBabylonianMethod.square_Root(1)); } @Test void testfor2() { - Assertions.assertEquals( - 1.4142135381698608, - SquareRootWithBabylonianMethod.square_Root(2) - ); + Assertions.assertEquals(1.4142135381698608, SquareRootWithBabylonianMethod.square_Root(2)); } @Test void testfor625() { - Assertions.assertEquals( - 25, - SquareRootWithBabylonianMethod.square_Root(625) - ); + Assertions.assertEquals(25, SquareRootWithBabylonianMethod.square_Root(625)); } } diff --git a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java index 192b686c1d2a..2c10d2d14f3e 100644 --- a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java @@ -7,26 +7,20 @@ public class StandardDeviationTest { @Test void test1() { - double[] t1 = new double[] { 1, 1, 1, 1, 1 }; + double[] t1 = new double[] {1, 1, 1, 1, 1}; Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0); } @Test void test2() { - double[] t2 = new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - Assertions.assertEquals( - StandardDeviation.stdDev(t2), - 2.8722813232690143 - ); + double[] t2 = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143); } @Test void test3() { - double[] t3 = new double[] { 1.1, 8.5, 20.3, 2.4, 6.2 }; - Assertions.assertEquals( - StandardDeviation.stdDev(t3), - 6.8308125431752265 - ); + double[] t3 = new double[] {1.1, 8.5, 20.3, 2.4, 6.2}; + Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265); } @Test @@ -38,9 +32,6 @@ void test4() { 100.00045, 56.7, }; - Assertions.assertEquals( - StandardDeviation.stdDev(t4), - 38.506117353865775 - ); + Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775); } } diff --git a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java index b2a0dc608c88..436b1fd011c6 100644 --- a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java +++ b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java @@ -22,9 +22,6 @@ void test3() { @Test void test4() { - Assertions.assertEquals( - StandardScore.zScore(8.9, 3, 4.2), - 1.4047619047619049 - ); + Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049); } } diff --git a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java index ad2158ac3f5c..63f53bc6e0ba 100644 --- a/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java +++ b/src/test/java/com/thealgorithms/maths/SumWithoutArithmeticOperatorsTest.java @@ -1,39 +1,40 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class SumWithoutArithmeticOperatorsTest { SumWithoutArithmeticOperators obj = new SumWithoutArithmeticOperators(); @Test - void addZerotoZero(){ - assertEquals(0,obj.getSum(0, 0)); + void addZerotoZero() { + assertEquals(0, obj.getSum(0, 0)); } @Test - void addZerotoNumber(){ - assertEquals(5,obj.getSum(0, 5)); - assertEquals(28,obj.getSum(28, 0)); + void addZerotoNumber() { + assertEquals(5, obj.getSum(0, 5)); + assertEquals(28, obj.getSum(28, 0)); } @Test - void addOddtoEven(){ - assertEquals(13,obj.getSum(3, 10)); - assertEquals(55,obj.getSum(49, 6)); + void addOddtoEven() { + assertEquals(13, obj.getSum(3, 10)); + assertEquals(55, obj.getSum(49, 6)); } @Test - void addEventoOdd(){ - assertEquals(13,obj.getSum(10, 3)); - assertEquals(41,obj.getSum(40, 1)); + void addEventoOdd() { + assertEquals(13, obj.getSum(10, 3)); + assertEquals(41, obj.getSum(40, 1)); } @Test - void addRandoms(){ - assertEquals(88,obj.getSum(44, 44)); - assertEquals(370,obj.getSum(100, 270)); - assertEquals(3,obj.getSum(1, 2)); - assertEquals(5,obj.getSum(2, 3)); + void addRandoms() { + assertEquals(88, obj.getSum(44, 44)); + assertEquals(370, obj.getSum(100, 270)); + assertEquals(3, obj.getSum(1, 2)); + assertEquals(5, obj.getSum(2, 3)); } } diff --git a/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java b/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java index d1f009540941..e214b0ada347 100644 --- a/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java +++ b/src/test/java/com/thealgorithms/maths/TwinPrimeTest.java @@ -6,55 +6,55 @@ class TwinPrimeTest { - @Test - void shouldReturn7() { - //given - int number = 5; - int expectedResult = 7; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturn5() { - //given - int number = 3; - int expectedResult = 5; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturnNegative1() { - //given - int number = 4; - int expectedResult = -1; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } - - @Test - void shouldReturn19() { - //given - int number = 17; - int expectedResult = 19; - - //when - int actualResult = TwinPrime.getTwinPrime(number); - - //then - assertEquals(expectedResult,actualResult); - } + @Test + void shouldReturn7() { + // given + int number = 5; + int expectedResult = 7; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturn5() { + // given + int number = 3; + int expectedResult = 5; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturnNegative1() { + // given + int number = 4; + int expectedResult = -1; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } + + @Test + void shouldReturn19() { + // given + int number = 17; + int expectedResult = 19; + + // when + int actualResult = TwinPrime.getTwinPrime(number); + + // then + assertEquals(expectedResult, actualResult); + } } diff --git a/src/test/java/com/thealgorithms/maths/VolumeTest.java b/src/test/java/com/thealgorithms/maths/VolumeTest.java index e9a80b4bbb7f..9692246b6a91 100644 --- a/src/test/java/com/thealgorithms/maths/VolumeTest.java +++ b/src/test/java/com/thealgorithms/maths/VolumeTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.maths; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class VolumeTest { diff --git a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java index ef350ffbeece..431d8daa2bab 100644 --- a/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java +++ b/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java @@ -8,39 +8,39 @@ class ArrayLeftRotationTest { @Test void testForOneElement() { - int[] arr = { 3 }; + int[] arr = {3}; int[] result = ArrayLeftRotation.rotateLeft(arr, 3); assertArrayEquals(arr, result); } @Test void testForZeroStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int[] result = ArrayLeftRotation.rotateLeft(arr, 0); assertArrayEquals(arr, result); } @Test void testForEqualSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int[] result = ArrayLeftRotation.rotateLeft(arr, 5); assertArrayEquals(arr, result); } @Test void testForLowerSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int n = 2; - int[] expected = { 5, 8, 6, 3, 1 }; + int[] expected = {5, 8, 6, 3, 1}; int[] result = ArrayLeftRotation.rotateLeft(arr, n); assertArrayEquals(expected, result); } @Test void testForHigherSizeStep() { - int[] arr = { 3, 1, 5, 8, 6 }; + int[] arr = {3, 1, 5, 8, 6}; int n = 7; - int[] expected = { 5, 8, 6, 3, 1 }; + int[] expected = {5, 8, 6, 3, 1}; int[] result = ArrayLeftRotation.rotateLeft(arr, n); assertArrayEquals(expected, result); } diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java index 35f1ef7ec399..0a82ebdf011f 100644 --- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java @@ -19,9 +19,9 @@ class BestFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - 2 processes shall fit to one block instead of using a different block each - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - 2 processes shall fit to one block instead of using a different block each + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(3, 0, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ void testFitForUseOfOneBlock() { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(3, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ void testFitForEqualProcecesses() { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ void testFitForNoEmptyBlockCell() { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ void testFitForSameInputDifferentQuery() { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = bestFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/CRC16Test.java b/src/test/java/com/thealgorithms/others/CRC16Test.java index 057d5b7d234f..513ec989291a 100644 --- a/src/test/java/com/thealgorithms/others/CRC16Test.java +++ b/src/test/java/com/thealgorithms/others/CRC16Test.java @@ -1,9 +1,9 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + class CRC16Test { CRC16 crc = new CRC16(); @@ -19,5 +19,4 @@ void testCRC16() { // then assertEquals("10FC", resultCRC16); } - } diff --git a/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java b/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java index 906ab829c264..a581a35bf963 100644 --- a/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.java @@ -1,27 +1,27 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class CRCAlgorithmTest { @Test - void test1(){ + void test1() { CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 0.0); - //A bit-error rate of 0.0 should not provide any wrong messages + // A bit-error rate of 0.0 should not provide any wrong messages c.changeMess(); c.divideMessageWithP(false); assertEquals(c.getWrongMess(), 0); } @Test - void test2(){ + void test2() { CRCAlgorithm c = new CRCAlgorithm("10010101010100101010010000001010010101010", 10, 1.0); - //A bit error rate of 1.0 should not provide any correct messages + // A bit error rate of 1.0 should not provide any correct messages c.changeMess(); c.divideMessageWithP(false); assertEquals(c.getCorrectMess(), 0); diff --git a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java index 89fc9b32e30d..e80cf9127e29 100644 --- a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java +++ b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java @@ -9,49 +9,49 @@ public class CalculateMaxOfMinTest { @Test void testForOneElement() { - int[] a = { 10, 20, 30, 50, 10, 70, 30 }; + int[] a = {10, 20, 30, 50, 10, 70, 30}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 70); } @Test void testForTwoElements() { - int[] a = { 5, 3, 2, 6, 3, 2, 6 }; + int[] a = {5, 3, 2, 6, 3, 2, 6}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 6); } @Test void testForThreeElements() { - int[] a = { 10, 10, 10, 10, 10, 10, 10 }; + int[] a = {10, 10, 10, 10, 10, 10, 10}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 10); } @Test void testForFourElements() { - int[] a = { 70, 60, 50, 40, 30, 20 }; + int[] a = {70, 60, 50, 40, 30, 20}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 70); } @Test void testForFiveElements() { - int[] a = { 50 }; + int[] a = {50}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 50); } @Test void testForSixElements() { - int[] a = { 1, 4, 7, 9, 2, 4, 6 }; + int[] a = {1, 4, 7, 9, 2, 4, 6}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == 9); } @Test void testForSevenElements() { - int[] a = { -1, -5, -7, -9, -12, -14 }; + int[] a = {-1, -5, -7, -9, -12, -14}; int k = CalculateMaxOfMin.calculateMaxOfMin(a); assertTrue(k == -1); } diff --git a/src/test/java/com/thealgorithms/others/ConwayTest.java b/src/test/java/com/thealgorithms/others/ConwayTest.java index 04b357949767..5e61836f3cdd 100644 --- a/src/test/java/com/thealgorithms/others/ConwayTest.java +++ b/src/test/java/com/thealgorithms/others/ConwayTest.java @@ -1,37 +1,42 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ConwayTest { @Test - public void testGenerateWith1(){ + public void testGenerateWith1() { assertEquals("31131211131221", Conway.generateList("1", 8).get(7)); } @Test - public void testGenerateWith123456(){ - assertEquals("13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", Conway.generateList("123456", 20).get(11)); + public void testGenerateWith123456() { + assertEquals( + "13211321322113311213212312311211131122211213211331121321122112133221123113112221131112212211131221121321131211132221123113112221131112311332211211131221131211132211121312211231131112311211232221143113112221131112311332111213122112311311123112112322211531131122211311123113321112131221123113111231121123222116", + Conway.generateList("123456", 20).get(11)); } @Test - public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C(){ - assertEquals("311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); + public void testGenerateWith1A1Z3E1R1T3G1F1D2E1S1C() { + assertEquals( + "311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211A311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211Z111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211R311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211T111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122111213122112311311222113111221131221221321132132211331121321231231121113112221121321133112132112211213322112311311222113111231133211121312211231131122211322311311222112111312211311123113322112132113212231121113112221121321132122211322212221121123222112111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312113221133211322112211213322112132113213221133112132123123112111311222112132113311213211231232112311311222112111312211311123113322112132113213221133112132123222113221321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211G311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211F311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211D111312211312111322212321121113121112131112132112311321322112111312212321121113122112131112131221121321132132211231131122211331121321232221121113122113121122132112311321322112111312211312111322211213111213122112132113121113222112132113213221133112132123222112311311222113111231132231121113112221121321133112132112211213322112111312211312111322212311222122132113213221123113112221133112132123222112111312211312111322212311322123123112111321322123122113222122211211232221121113122113121113222123211211131211121311121321123113213221121113122123211211131221121311121312211213211321322112311311222113311213212322211211131221131211221321123113213221121113122113121113222112131112131221121321131211132221121321132132211331121321232221123113112221131112311322311211131122211213211331121321122112133221121113122113121113222123112221221321132132211231131122211331121321232221121113122113121113222123113221231231121113213221231221132221222112112322211E311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211S311311222113111231133211121312211231131112311211133112111312211213211312111322211231131122111213122112311311222112111331121113112221121113122113121113222112132113213221232112111312111213322112311311222113111221221113122112132113121113222112311311222113111231133221121113311211131122211211131221131112311332211211131221131211132221232112111312111213322112132113213221133112132113221321123113213221121113122123211211131221222112112322211231131122211311123113321112132132112211131221131211132221121321132132212321121113121112133221123113112221131112311332111213211322111213111213211231131211132211121311222113321132211221121332211C", + Conway.generateList("1A1Z3E1R1T3G1F1D2E1S1C", 20).get(19)); } @Test - public void testGenerateNextElementWith1(){ + public void testGenerateNextElementWith1() { assertEquals("11", Conway.generateNextElement("1")); } @Test - public void testGenerateNextElementWith123456(){ + public void testGenerateNextElementWith123456() { assertEquals("111213141516", Conway.generateNextElement("123456")); } @Test - public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C(){ - assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); + public void testGenerateNextElementWith1A1Z3E1R1T3G1F1D2E1S1C() { + assertEquals("111A111Z131E111R111T131G111F111D121E111S111C", + Conway.generateNextElement("1A1Z3E1R1T3G1F1D2E1S1C")); } } diff --git a/src/test/java/com/thealgorithms/others/CountCharTest.java b/src/test/java/com/thealgorithms/others/CountCharTest.java index 9e9972c6838e..aae875b7f21e 100644 --- a/src/test/java/com/thealgorithms/others/CountCharTest.java +++ b/src/test/java/com/thealgorithms/others/CountCharTest.java @@ -1,17 +1,16 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class CountCharTest { @Test - void testCountCharacters(){ + void testCountCharacters() { String input = "12345"; int expectedValue = 5; assertEquals(expectedValue, CountChar.CountCharacters(input)); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java index e30ffd423585..070812f114d8 100644 --- a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java +++ b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java @@ -9,49 +9,49 @@ public class CountFriendsPairingTest { @Test void testForOneElement() { - int[] a = { 1, 2, 2 }; + int[] a = {1, 2, 2}; assertTrue(CountFriendsPairing.countFriendsPairing(3, a)); } @Test void testForTwoElements() { - int[] a = { 1, 2, 2, 3 }; + int[] a = {1, 2, 2, 3}; assertTrue(CountFriendsPairing.countFriendsPairing(4, a)); } @Test void testForThreeElements() { - int[] a = { 1, 2, 2, 3, 3 }; + int[] a = {1, 2, 2, 3, 3}; assertTrue(CountFriendsPairing.countFriendsPairing(5, a)); } @Test void testForFourElements() { - int[] a = { 1, 2, 2, 3, 3, 4 }; + int[] a = {1, 2, 2, 3, 3, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(6, a)); } @Test void testForFiveElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4 }; + int[] a = {1, 2, 2, 3, 3, 4, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(7, a)); } @Test void testForSixElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4}; assertTrue(CountFriendsPairing.countFriendsPairing(8, a)); } @Test void testForSevenElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5}; assertTrue(CountFriendsPairing.countFriendsPairing(9, a)); } @Test void testForEightElements() { - int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 }; + int[] a = {1, 2, 2, 3, 3, 4, 4, 4, 5, 5}; assertTrue(CountFriendsPairing.countFriendsPairing(10, a)); } } diff --git a/src/test/java/com/thealgorithms/others/CountWordsTest.java b/src/test/java/com/thealgorithms/others/CountWordsTest.java index a2b0c03df220..d5ebe654b325 100644 --- a/src/test/java/com/thealgorithms/others/CountWordsTest.java +++ b/src/test/java/com/thealgorithms/others/CountWordsTest.java @@ -5,7 +5,6 @@ import java.util.HashMap; import org.junit.jupiter.api.Test; - class CountWordsTest { @Test public void testWordCount() { diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java index 33b77350e077..b726a746d5ac 100644 --- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java @@ -19,9 +19,9 @@ class FirstFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - no use of one block for two processes - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - no use of one block for two processes + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 0, 2, 1)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ void testFitForUseOfOneBlock() { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ void testFitForEqualProcecesses() { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ void testFitForNoEmptyBlockCell() { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ void testFitForSameInputDifferentQuery() { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = firstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java index 74ca9a3efb75..ac2aa9648c07 100644 --- a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java +++ b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java @@ -9,49 +9,49 @@ public class KadaneAlogrithmTest { @Test void testForOneElement() { - int[] a = { -1 }; + int[] a = {-1}; assertTrue(KadaneAlgorithm.max_Sum(a, -1)); } @Test void testForTwoElements() { - int[] a = { -2, 1 }; + int[] a = {-2, 1}; assertTrue(KadaneAlgorithm.max_Sum(a, 1)); } @Test void testForThreeElements() { - int[] a = { 5, 3, 12 }; + int[] a = {5, 3, 12}; assertTrue(KadaneAlgorithm.max_Sum(a, 20)); } @Test void testForFourElements() { - int[] a = { -1, -3, -7, -4 }; + int[] a = {-1, -3, -7, -4}; assertTrue(KadaneAlgorithm.max_Sum(a, -1)); } @Test void testForFiveElements() { - int[] a = { 4, 5, 3, 0, 2 }; + int[] a = {4, 5, 3, 0, 2}; assertTrue(KadaneAlgorithm.max_Sum(a, 14)); } @Test void testForSixElements() { - int[] a = { -43, -45, 47, 12, 87, -13 }; + int[] a = {-43, -45, 47, 12, 87, -13}; assertTrue(KadaneAlgorithm.max_Sum(a, 146)); } @Test void testForSevenElements() { - int[] a = { 9, 8, 2, 23, 13, 6, 7 }; + int[] a = {9, 8, 2, 23, 13, 6, 7}; assertTrue(KadaneAlgorithm.max_Sum(a, 68)); } @Test void testForEightElements() { - int[] a = { 9, -5, -5, -2, 4, 5, 0, 1 }; + int[] a = {9, -5, -5, -2, 4, 5, 0, 1}; assertTrue(KadaneAlgorithm.max_Sum(a, 10)); } } diff --git a/src/test/java/com/thealgorithms/others/LineSweepTest.java b/src/test/java/com/thealgorithms/others/LineSweepTest.java index 428556d404c5..20cf1cd75153 100644 --- a/src/test/java/com/thealgorithms/others/LineSweepTest.java +++ b/src/test/java/com/thealgorithms/others/LineSweepTest.java @@ -1,29 +1,28 @@ package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class LineSweepTest { - @Test - void testForOverlap(){ - int[][]arr = {{0,10},{7,20},{15,24}}; + void testForOverlap() { + int[][] arr = {{0, 10}, {7, 20}, {15, 24}}; assertTrue(LineSweep.isOverlap(arr)); } @Test - void testForNoOverlap(){ - int[][]arr = {{0,10},{11,20},{21,24}}; + void testForNoOverlap() { + int[][] arr = {{0, 10}, {11, 20}, {21, 24}}; assertFalse(LineSweep.isOverlap(arr)); } @Test - void testForOverlapWhenEndAEqualsStartBAndViceVersa(){ - int[][]arr = {{0,10},{10,20},{21,24}}; + void testForOverlapWhenEndAEqualsStartBAndViceVersa() { + int[][] arr = {{0, 10}, {10, 20}, {21, 24}}; assertTrue(LineSweep.isOverlap(arr)); } @Test - void testForMaximumEndPoint(){ - int[][]arr = {{10,20},{1,100},{14,16},{1,8}}; - assertEquals(100,LineSweep.FindMaximumEndPoint(arr)); + void testForMaximumEndPoint() { + int[][] arr = {{10, 20}, {1, 100}, {14, 16}, {1, 8}}; + assertEquals(100, LineSweep.FindMaximumEndPoint(arr)); } - } diff --git a/src/test/java/com/thealgorithms/others/LinkListSortTest.java b/src/test/java/com/thealgorithms/others/LinkListSortTest.java index 7c6da59cb896..e0e258aacd69 100644 --- a/src/test/java/com/thealgorithms/others/LinkListSortTest.java +++ b/src/test/java/com/thealgorithms/others/LinkListSortTest.java @@ -9,49 +9,49 @@ public class LinkListSortTest { @Test void testForOneElement() { - int[] a = { 56 }; + int[] a = {56}; assertTrue(LinkListSort.isSorted(a, 2)); } @Test void testForTwoElements() { - int[] a = { 6, 4 }; + int[] a = {6, 4}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForThreeElements() { - int[] a = { 875, 253, 12 }; + int[] a = {875, 253, 12}; assertTrue(LinkListSort.isSorted(a, 3)); } @Test void testForFourElements() { - int[] a = { 86, 32, 87, 13 }; + int[] a = {86, 32, 87, 13}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForFiveElements() { - int[] a = { 6, 5, 3, 0, 9 }; + int[] a = {6, 5, 3, 0, 9}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForSixElements() { - int[] a = { 9, 65, 432, 32, 47, 327 }; + int[] a = {9, 65, 432, 32, 47, 327}; assertTrue(LinkListSort.isSorted(a, 3)); } @Test void testForSevenElements() { - int[] a = { 6, 4, 2, 1, 3, 6, 7 }; + int[] a = {6, 4, 2, 1, 3, 6, 7}; assertTrue(LinkListSort.isSorted(a, 1)); } @Test void testForEightElements() { - int[] a = { 123, 234, 145, 764, 322, 367, 768, 34 }; + int[] a = {123, 234, 145, 764, 322, 367, 768, 34}; assertTrue(LinkListSort.isSorted(a, 2)); } } diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java index 3124d7b0224f..1de115bb8695 100644 --- a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java +++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java @@ -1,14 +1,13 @@ package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.HashMap; import java.util.ArrayList; import java.util.Arrays; - +import java.util.HashMap; import org.junit.jupiter.api.Test; public class LowestBasePalindromeTest { @@ -17,14 +16,18 @@ public void testIsPalindromicPositive() { assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>())); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1)))); assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 1)))); - assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 1)))); - assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 2, 1)))); + assertTrue( + LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 1)))); + assertTrue( + LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 2, 1)))); } @Test public void testIsPalindromicNegative() { - assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2)))); - assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 1, 1)))); + assertFalse( + LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2)))); + assertFalse( + LowestBasePalindrome.isPalindromic(new ArrayList<Integer>(Arrays.asList(1, 2, 1, 1)))); } @Test @@ -45,17 +48,13 @@ public void testIsPalindromicInBaseNegative() { @Test public void testIsPalindromicInBaseThrowsExceptionForNegativeNumbers() { assertThrows( - IllegalArgumentException.class, - () -> LowestBasePalindrome.isPalindromicInBase(-1, 5) - ); + IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)); } @Test public void testIsPalindromicInBaseThrowsExceptionForWrongBases() { assertThrows( - IllegalArgumentException.class, - () -> LowestBasePalindrome.isPalindromicInBase(10, 1) - ); + IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(10, 1)); } @Test diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java index bd1df90717aa..2de6b411080c 100644 --- a/src/test/java/com/thealgorithms/others/NextFitTest.java +++ b/src/test/java/com/thealgorithms/others/NextFitTest.java @@ -19,9 +19,9 @@ class NextFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - third process does not fit because of algorithms procedure - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 - third process does not fit because of algorithms procedure + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, -255, 2)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ void testFitForUseOfOneBlock() { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(1, 2, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ void testFitForEqualProcecesses() { @Test void testFitForNoEmptyBlockCell() { - //test3 for more processes than blocks - no empty space left to none of the blocks - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 for more processes than blocks - no empty space left to none of the blocks + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, 2)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ void testFitForNoEmptyBlockCell() { @Test void testFitForSameInputDifferentQuery() { - //test4 for more processes than blocks - one element does not fit due to input series - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 for more processes than blocks - one element does not fit due to input series + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(0, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ void testFitForSameInputDifferentQuery() { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = nextFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); diff --git a/src/test/java/com/thealgorithms/others/PasswordGenTest.java b/src/test/java/com/thealgorithms/others/PasswordGenTest.java index 3bdcc9553231..8bf0d58e67e4 100644 --- a/src/test/java/com/thealgorithms/others/PasswordGenTest.java +++ b/src/test/java/com/thealgorithms/others/PasswordGenTest.java @@ -9,12 +9,8 @@ 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 @@ -27,12 +23,8 @@ public void generateOneCharacterPassword() { 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 867311e1bce1..033936511cde 100644 --- a/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java +++ b/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.java @@ -1,32 +1,25 @@ package com.thealgorithms.others; -import java.util.List; +import static org.junit.jupiter.api.Assertions.*; +import java.util.List; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; 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<Integer> res = printClass.print(matrix, matrix.length, matrix[0].length); - List<Integer> 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<Integer> 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); } @Test public void testTwo() { - int[][] matrix = { - { 2, 2 } - }; + int[][] matrix = {{2, 2}}; var printClass = new PrintAMatrixInSpiralOrder(); List<Integer> res = printClass.print(matrix, matrix.length, matrix[0].length); List<Integer> list = List.of(2, 2); diff --git a/src/test/java/com/thealgorithms/others/TwoPointersTest.java b/src/test/java/com/thealgorithms/others/TwoPointersTest.java index 7241140c7246..8cadb031111b 100644 --- a/src/test/java/com/thealgorithms/others/TwoPointersTest.java +++ b/src/test/java/com/thealgorithms/others/TwoPointersTest.java @@ -1,44 +1,43 @@ package com.thealgorithms.others; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class TwoPointersTest { - @Test - void twoPointersFirstTestCase(){ - int[] arr = {2,6,9,22,121}; + void twoPointersFirstTestCase() { + int[] arr = {2, 6, 9, 22, 121}; int key = 28; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersSecondTestCase(){ - int[] arr = {-1,-12,12,0,8}; + void twoPointersSecondTestCase() { + int[] arr = {-1, -12, 12, 0, 8}; int key = 0; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersThirdTestCase(){ - int[] arr = {12,35,12,152,0}; + void twoPointersThirdTestCase() { + int[] arr = {12, 35, 12, 152, 0}; int key = 13; - assertEquals(false, TwoPointers.isPairedSum(arr,key)); + assertEquals(false, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersFourthTestCase(){ - int[] arr = {-2,5,-1,52,31}; + void twoPointersFourthTestCase() { + int[] arr = {-2, 5, -1, 52, 31}; int key = -3; - assertEquals(true, TwoPointers.isPairedSum(arr,key)); + assertEquals(true, TwoPointers.isPairedSum(arr, key)); } @Test - void twoPointersFiftiethTestCase(){ - int[] arr = {25,1,0,61,21}; + void twoPointersFiftiethTestCase() { + int[] arr = {25, 1, 0, 61, 21}; int key = 12; - assertEquals(false, TwoPointers.isPairedSum(arr,key)); + assertEquals(false, TwoPointers.isPairedSum(arr, key)); } } diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java index 5d27d0de1805..6f2a53b3dfe7 100644 --- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java +++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java @@ -19,9 +19,9 @@ class WorstFitCPUTest { @Test void testFitForUseOfOneBlock() { - //test1 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 5, 15, 2 }; + // test1 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 5, 15, 2}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, -255, 3)); assertEquals(testMemAllocation, memAllocation); @@ -29,9 +29,9 @@ void testFitForUseOfOneBlock() { @Test void testFitForEqualProcecesses() { - //test2 - sizeOfBlocks = new int[] { 5, 12, 17, 10 }; - sizeOfProcesses = new int[] { 10, 10, 10, 10 }; + // test2 + sizeOfBlocks = new int[] {5, 12, 17, 10}; + sizeOfProcesses = new int[] {10, 10, 10, 10}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 3, -255)); assertEquals(testMemAllocation, memAllocation); @@ -39,9 +39,9 @@ void testFitForEqualProcecesses() { @Test void testFitForNoEmptyBlockCell() { - //test3 - could suits best, bad use of memory allocation due to worstFit algorithm - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 12, 10, 7 }; + // test3 - could suits best, bad use of memory allocation due to worstFit algorithm + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 12, 10, 7}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -49,9 +49,9 @@ void testFitForNoEmptyBlockCell() { @Test void testFitForSameInputDifferentQuery() { - //test4 same example different series - same results - sizeOfBlocks = new int[] { 5, 12, 17 }; - sizeOfProcesses = new int[] { 5, 7, 10, 12 }; + // test4 same example different series - same results + sizeOfBlocks = new int[] {5, 12, 17}; + sizeOfProcesses = new int[] {5, 7, 10, 12}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(2, 1, 2, -255)); assertEquals(testMemAllocation, memAllocation); @@ -59,9 +59,9 @@ void testFitForSameInputDifferentQuery() { @Test void testFitForMoreBlocksNoFit() { - //test5 for more blocks than processes - sizeOfBlocks = new int[] { 5, 4, -1, 3, 6 }; - sizeOfProcesses = new int[] { 10, 11 }; + // test5 for more blocks than processes + sizeOfBlocks = new int[] {5, 4, -1, 3, 6}; + sizeOfProcesses = new int[] {10, 11}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); testMemAllocation = new ArrayList<>(Arrays.asList(-255, -255)); assertEquals(testMemAllocation, memAllocation); @@ -69,12 +69,11 @@ void testFitForMoreBlocksNoFit() { @Test void testFitBadCase() { - //test6 for only two process fit - sizeOfBlocks = new int[] { 7, 17, 7, 5, 6 }; - sizeOfProcesses = new int[] { 8, 10, 10, 8, 8, 8 }; + // test6 for only two process fit + sizeOfBlocks = new int[] {7, 17, 7, 5, 6}; + sizeOfProcesses = new int[] {8, 10, 10, 8, 8, 8}; memAllocation = worstFit.fitProcess(sizeOfBlocks, sizeOfProcesses); - testMemAllocation = - new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255)); + testMemAllocation = new ArrayList<>(Arrays.asList(1, -255, -255, 1, -255, -255)); assertEquals(testMemAllocation, memAllocation); } } diff --git a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java index bbefadee8e56..f9b517eb6793 100644 --- a/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java @@ -46,8 +46,8 @@ public void checkForSameBits() { @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,23 +56,16 @@ public void checkForLongDataBits() { 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/FCFSSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java index c25a9c93049e..87b3d12c8dcf 100644 --- a/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java @@ -1,16 +1,14 @@ package com.thealgorithms.scheduling; -import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class FCFSSchedulingTest { - @Test public void testingProcesses() { List<ProcessDetails> processes = addProcessesForFCFS(); @@ -31,7 +29,6 @@ public void testingProcesses() { assertEquals("P3", processes.get(2).getProcessId()); assertEquals(15, processes.get(2).getWaitingTime()); assertEquals(23, processes.get(2).getTurnAroundTimeTime()); - } private List<ProcessDetails> addProcessesForFCFS() { @@ -46,5 +43,4 @@ private List<ProcessDetails> addProcessesForFCFS() { return processDetails; } - } diff --git a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java index 935ff733562f..1d9b7a7f3154 100644 --- a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java @@ -3,16 +3,16 @@ import static org.junit.jupiter.api.Assertions.*; import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Test; class RRSchedulingTest { @Test public void testingProcesses() { List<ProcessDetails> 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(); @@ -41,7 +41,6 @@ public void testingProcesses() { assertEquals("P6", processes.get(5).getProcessId()); assertEquals(11, processes.get(5).getWaitingTime()); assertEquals(15, processes.get(5).getTurnAroundTimeTime()); - } private List<ProcessDetails> addProcessesForRR() { diff --git a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java index 8ba3b6795d86..66bfe0957f31 100644 --- a/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java +++ b/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java @@ -1,120 +1,109 @@ package com.thealgorithms.scheduling; -import com.thealgorithms.devutils.entities.ProcessDetails; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; +import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class SJFSchedulingTest { - private ArrayList<ProcessDetails> process; - void initialisation0() - { + private ArrayList<ProcessDetails> process; + void initialisation0() { - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,6)); - process.add(new ProcessDetails("2",1,2)); + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 6)); + process.add(new ProcessDetails("2", 1, 2)); } - void initialisation1() - { - - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,6)); - process.add(new ProcessDetails("2",1,2)); - process.add(new ProcessDetails("3",4 ,3)); - process.add(new ProcessDetails("4",3,1)); - process.add(new ProcessDetails("5",6 ,4)); - process.add(new ProcessDetails("6",5,5)); + void initialisation1() { + + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 6)); + process.add(new ProcessDetails("2", 1, 2)); + process.add(new ProcessDetails("3", 4, 3)); + process.add(new ProcessDetails("4", 3, 1)); + process.add(new ProcessDetails("5", 6, 4)); + process.add(new ProcessDetails("6", 5, 5)); } - void initialisation2() - { - - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,3)); - process.add(new ProcessDetails("2",1,2)); - process.add(new ProcessDetails("3",2 ,1)); + void initialisation2() { + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 3)); + process.add(new ProcessDetails("2", 1, 2)); + process.add(new ProcessDetails("3", 2, 1)); } - void initialisation3(){ - process=new ArrayList<>(); - process.add(new ProcessDetails("1",0 ,3)); - process.add(new ProcessDetails("2",5,2)); - process.add(new ProcessDetails("3",9 ,1)); + void initialisation3() { + process = new ArrayList<>(); + process.add(new ProcessDetails("1", 0, 3)); + process.add(new ProcessDetails("2", 5, 2)); + process.add(new ProcessDetails("3", 9, 1)); } @Test - void constructor() - { + void constructor() { initialisation0(); - SJFScheduling a=new SJFScheduling(process); - assertEquals( 6,a.processes.get(0).getBurstTime()); - assertEquals( 2,a.processes.get(1).getBurstTime()); + SJFScheduling a = new SJFScheduling(process); + assertEquals(6, a.processes.get(0).getBurstTime()); + assertEquals(2, a.processes.get(1).getBurstTime()); } - @Test - void sort() - { + @Test + void sort() { initialisation1(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.sortByArrivalTime(); - assertEquals("1",a.processes.get(0).getProcessId()); - assertEquals("2",a.processes.get(1).getProcessId()); - assertEquals("3",a.processes.get(3).getProcessId()); - assertEquals("4",a.processes.get(2).getProcessId()); - assertEquals("5",a.processes.get(5).getProcessId()); - assertEquals("6",a.processes.get(4).getProcessId()); - + assertEquals("1", a.processes.get(0).getProcessId()); + assertEquals("2", a.processes.get(1).getProcessId()); + assertEquals("3", a.processes.get(3).getProcessId()); + assertEquals("4", a.processes.get(2).getProcessId()); + assertEquals("5", a.processes.get(5).getProcessId()); + assertEquals("6", a.processes.get(4).getProcessId()); } @Test - void scheduling(){ + void scheduling() { initialisation1(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "4" , a.schedule.get(1)); - assertEquals( "2" , a.schedule.get(2)); - assertEquals( "3" , a.schedule.get(3)); - assertEquals("5" , a.schedule.get(4)); - assertEquals( "6", a.schedule.get(5)); - - + assertEquals("1", a.schedule.get(0)); + assertEquals("4", a.schedule.get(1)); + assertEquals("2", a.schedule.get(2)); + assertEquals("3", a.schedule.get(3)); + assertEquals("5", a.schedule.get(4)); + assertEquals("6", a.schedule.get(5)); } @Test - void schedulingOf_TwoProcesses(){ + void schedulingOf_TwoProcesses() { initialisation0(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "2" , a.schedule.get(1)); + assertEquals("1", a.schedule.get(0)); + assertEquals("2", a.schedule.get(1)); } @Test - void schedulingOfA_ShortestJobArrivingLast(){ + void schedulingOfA_ShortestJobArrivingLast() { initialisation2(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "3" , a.schedule.get(1)); - assertEquals( "2" , a.schedule.get(2)); + assertEquals("1", a.schedule.get(0)); + assertEquals("3", a.schedule.get(1)); + assertEquals("2", a.schedule.get(2)); } @Test - void scheduling_WithProcessesNotComingBackToBack(){ + void scheduling_WithProcessesNotComingBackToBack() { initialisation3(); - SJFScheduling a=new SJFScheduling(process); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertEquals( "1" , a.schedule.get(0)); - assertEquals( "2" , a.schedule.get(1)); - assertEquals( "3" , a.schedule.get(2)); + assertEquals("1", a.schedule.get(0)); + assertEquals("2", a.schedule.get(1)); + assertEquals("3", a.schedule.get(2)); } @Test - void schedulingOf_nothing(){ - process=new ArrayList<>(); - SJFScheduling a=new SJFScheduling(process); + void schedulingOf_nothing() { + process = new ArrayList<>(); + SJFScheduling a = new SJFScheduling(process); a.scheduleProcesses(); - assertTrue( a.schedule.isEmpty()); - + assertTrue(a.schedule.isEmpty()); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index 0db17bdb2406..4910762cc03f 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -4,20 +4,19 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.*; -import org.junit.jupiter.api.Test; import org.junit.jupiter.api.AfterAll; - +import org.junit.jupiter.api.Test; public class BinarySearch2dArrayTest { @Test // valid test case public void BinarySearch2dArrayTestMiddle() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 6; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 1, 1 }; + int[] expected = {1, 1}; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(1, ans[1]); @@ -26,11 +25,11 @@ public void BinarySearch2dArrayTestMiddle() { @Test // valid test case public void BinarySearch2dArrayTestMiddleSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 8; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 1, 3 }; + int[] expected = {1, 3}; System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); assertEquals(3, ans[1]); @@ -39,11 +38,11 @@ public void BinarySearch2dArrayTestMiddleSide() { @Test // valid test case public void BinarySearch2dArrayTestUpper() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 2; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 0, 1 }; + int[] expected = {0, 1}; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(1, ans[1]); @@ -52,11 +51,11 @@ public void BinarySearch2dArrayTestUpper() { @Test // valid test case public void BinarySearch2dArrayTestUpperSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 1; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 0, 0 }; + int[] expected = {0, 0}; System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); assertEquals(0, ans[1]); @@ -65,11 +64,11 @@ public void BinarySearch2dArrayTestUpperSide() { @Test // valid test case public void BinarySearch2dArrayTestLower() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 10; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 2, 1 }; + int[] expected = {2, 1}; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(1, ans[1]); @@ -78,11 +77,11 @@ public void BinarySearch2dArrayTestLower() { @Test // valid test case public void BinarySearch2dArrayTestLowerSide() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 11; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { 2, 2 }; + int[] expected = {2, 2}; System.out.println(Arrays.toString(ans)); assertEquals(2, ans[0]); assertEquals(2, ans[1]); @@ -91,11 +90,11 @@ public void BinarySearch2dArrayTestLowerSide() { @Test // valid test case public void BinarySearch2dArrayTestNotFound() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 101; int[] ans = BinarySearch2dArray.BinarySearch(arr, target); - int[] expected = { -1, -1 }; + int[] expected = {-1, -1}; System.out.println(Arrays.toString(ans)); assertEquals(-1, ans[0]); assertEquals(-1, ans[1]); @@ -106,7 +105,7 @@ public void BinarySearch2dArrayTestNotFound() { */ @Test public void BinarySearch2dArrayTestOneRow() { - int[][] arr = { { 1, 2, 3, 4 }}; + int[][] arr = {{1, 2, 3, 4}}; int target = 2; // Assert that the requirement, that the array only has one row, is fulfilled. @@ -122,10 +121,11 @@ public void BinarySearch2dArrayTestOneRow() { */ @Test public void BinarySearch2dArrayTestTargetInMiddle() { - int[][] arr = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15} }; + int[][] arr = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}}; int target = 8; - // Assert that the requirement, that the target is in the middle row and middle column, is fulfilled. - assertEquals(arr[arr.length/2][arr[0].length/2], target); + // Assert that the requirement, that the target is in the middle row and middle column, is + // fulfilled. + assertEquals(arr[arr.length / 2][arr[0].length / 2], target); int[] ans = BinarySearch2dArray.BinarySearch(arr, target); System.out.println(Arrays.toString(ans)); assertEquals(1, ans[0]); @@ -138,13 +138,13 @@ public void BinarySearch2dArrayTestTargetInMiddle() { */ @Test public void BinarySearch2dArrayTestTargetAboveMiddleRowInMiddleColumn() { - int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; + int[][] arr = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int target = 3; // Assert that the requirement, that he target is in the middle column, // in an array with an even number of columns, and on the row "above" the middle row. assertEquals(arr[0].length % 2, 0); - assertEquals(arr[arr.length/2-1][arr[0].length/2], target); + assertEquals(arr[arr.length / 2 - 1][arr[0].length / 2], target); int[] ans = BinarySearch2dArray.BinarySearch(arr, target); System.out.println(Arrays.toString(ans)); assertEquals(0, ans[0]); @@ -160,7 +160,7 @@ public void BinarySearch2dArrayTestEmptyArray() { 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 d0ddc8200194..5912458fbbf3 100644 --- a/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java @@ -1,28 +1,21 @@ package com.thealgorithms.searches; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.*; +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") - ) - ); + 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"))); @Test void searchI() { diff --git a/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java b/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java index 320222f5abd6..ac731b0f5dea 100644 --- a/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java +++ b/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java @@ -8,10 +8,9 @@ public class HowManyTimesRotatedTest { @Test public void testHowManyTimesRotated() { - int[] arr1 = {5, 1,2,3,4}; + int[] arr1 = {5, 1, 2, 3, 4}; assertEquals(1, HowManyTimesRotated.rotated(arr1)); - int[] arr2 = {15,17,2,3,5}; + int[] arr2 = {15, 17, 2, 3, 5}; assertEquals(2, HowManyTimesRotated.rotated(arr2)); } } - diff --git a/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java index 8194d345d1cb..afcbc52fdaca 100644 --- a/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java @@ -1,72 +1,69 @@ package com.thealgorithms.searches; -import com.thealgorithms.searches.OrderAgnosticBinarySearch; - -import org.junit.jupiter.api.Test; - -import java.util.*; - import static org.junit.jupiter.api.Assertions.assertEquals; +import com.thealgorithms.searches.OrderAgnosticBinarySearch; +import java.util.*; +import org.junit.jupiter.api.Test; public class OrderAgnosticBinarySearchTest { - @Test - //valid Test Case - public void ElementInMiddle() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 30); - System.out.println(answer); - int expected = 2; - assertEquals(expected, answer); - } + @Test + // valid Test Case + public void ElementInMiddle() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 30); + System.out.println(answer); + int expected = 2; + assertEquals(expected, answer); + } - @Test - //valid Test Case - public void RightHalfDescOrder() { - int[] arr = {50, 40, 30, 20, 10}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); - System.out.println(answer); - int expected = 4; - assertEquals(expected, answer); - } + @Test + // valid Test Case + public void RightHalfDescOrder() { + int[] arr = {50, 40, 30, 20, 10}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); + System.out.println(answer); + int expected = 4; + assertEquals(expected, answer); + } - @Test - //valid test case - public void LeftHalfDescOrder() { - int[] arr = {50, 40, 30, 20, 10}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); - System.out.println(answer); - int expected = 0; - assertEquals(expected, answer); - } + @Test + // valid test case + public void LeftHalfDescOrder() { + int[] arr = {50, 40, 30, 20, 10}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); + System.out.println(answer); + int expected = 0; + assertEquals(expected, answer); + } - @Test - //valid test case - public void RightHalfAscOrder() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); - System.out.println(answer); - int expected = 4; - assertEquals(expected, answer); - } + @Test + // valid test case + public void RightHalfAscOrder() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 50); + System.out.println(answer); + int expected = 4; + assertEquals(expected, answer); + } - @Test - //valid test case - public void LeftHalfAscOrder() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); - System.out.println(answer); - int expected = 0; - assertEquals(expected, answer); - } + @Test + // valid test case + public void LeftHalfAscOrder() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 10); + System.out.println(answer); + int expected = 0; + assertEquals(expected, answer); + } - @Test - //valid test case - public void ElementNotFound() { - int[] arr = {10, 20, 30, 40, 50}; - int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 100); - System.out.println(answer); - int expected = -1; - assertEquals(expected, answer); - } - } + @Test + // valid test case + public void ElementNotFound() { + int[] arr = {10, 20, 30, 40, 50}; + int answer = OrderAgnosticBinarySearch.BinSearchAlgo(arr, 0, arr.length - 1, 100); + System.out.println(answer); + int expected = -1; + assertEquals(expected, answer); + } +} diff --git a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java index 720a1250be7c..d788c5d1244e 100644 --- a/src/test/java/com/thealgorithms/searches/QuickSelectTest.java +++ b/src/test/java/com/thealgorithms/searches/QuickSelectTest.java @@ -180,10 +180,8 @@ void quickSelectMedianOfManyCharacters() { @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()); } @@ -191,32 +189,25 @@ void quickSelectNullList() { @Test void quickSelectEmptyList() { List<String> 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) - ); - String expectedMsg = - "The index must be less than the number of elements."; + 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()); } @@ -230,15 +221,12 @@ private static List<Integer> generateRandomIntegers(int n) { } private static List<Character> generateRandomCharacters(int n) { - return RANDOM - .ints(n, ASCII_A, ASCII_Z) + return RANDOM.ints(n, ASCII_A, ASCII_Z) .mapToObj(i -> (char) i) .collect(Collectors.toList()); } - private static <T extends Comparable<T>> List<T> getSortedCopyOfList( - List<T> list - ) { + private static <T extends Comparable<T>> List<T> getSortedCopyOfList(List<T> list) { return list.stream().sorted().collect(Collectors.toList()); } } diff --git a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java index b15b53c3cb6a..e706a58fafbe 100644 --- a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java @@ -6,108 +6,108 @@ public class RowColumnWiseSorted2dArrayBinarySearchTest { - @Test - public void rowColumnSorted2dArrayBinarySearchTestMiddle() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 35; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 1, 2 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArrayBinarySearchTestMiddle() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 35; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {1, 2}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArrayBinarySearchTestSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 48; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 2, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArrayBinarySearchTestSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 48; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {2, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestUpper() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 20; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 0, 1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestUpper() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 20; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {0, 1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestUpperSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 40; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 0, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestUpperSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 40; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {0, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestLower() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 31; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 3, 1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestLower() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 31; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {3, 1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestLowerSide() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 51; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { 3, 3 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestLowerSide() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 51; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {3, 3}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } - @Test - public void rowColumnSorted2dArray_BinarySearchTestNotFound() { - Integer[][] arr = { - { 10, 20, 30, 40 }, - { 15, 25, 35, 45 }, - { 18, 28, 38, 48 }, - { 21, 31, 41, 51 }, - }; - Integer target = 101; - int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); - int[] expected = { -1, -1 }; - assertEquals(expected[0], ans[0]); - assertEquals(expected[1], ans[1]); - } + @Test + public void rowColumnSorted2dArray_BinarySearchTestNotFound() { + Integer[][] arr = { + {10, 20, 30, 40}, + {15, 25, 35, 45}, + {18, 28, 38, 48}, + {21, 31, 41, 51}, + }; + Integer target = 101; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(arr, target); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } } diff --git a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java index 0dcc6186fa9b..304544d20e82 100644 --- a/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java +++ b/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java @@ -1,38 +1,29 @@ package com.thealgorithms.searches; import static org.junit.jupiter.api.Assertions.*; + 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); - int[] expectedResult = { 2, 2 }; + int[] expectedResult = {2, 2}; assertArrayEquals(expectedResult, res); } @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); - int[] expectedResult = { -1, -1 }; + int[] expectedResult = {-1, -1}; assertArrayEquals(expectedResult, res); } } diff --git a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java index 804cfc3e9dba..e761eb10948d 100644 --- a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java @@ -4,24 +4,23 @@ import org.junit.jupiter.api.Test; -public class sortOrderAgnosticBinarySearchTest{ +public class sortOrderAgnosticBinarySearchTest { @Test - public void testAscending(){ - int[] arr = {1,2,3,4,5};// for ascending order. + public void testAscending() { + int[] arr = {1, 2, 3, 4, 5}; // for ascending order. int target = 2; - int ans=sortOrderAgnosticBinarySearch.find(arr, target); + int ans = sortOrderAgnosticBinarySearch.find(arr, target); int excepted = 1; - assertEquals(excepted,ans); + assertEquals(excepted, ans); } @Test - public void testDescending(){ - int[] arr = {5,4,3,2,1};// for descending order. + public void testDescending() { + int[] arr = {5, 4, 3, 2, 1}; // for descending order. int target = 2; - int ans=sortOrderAgnosticBinarySearch.find(arr, target); + int ans = sortOrderAgnosticBinarySearch.find(arr, target); int excepted = 3; - assertEquals(excepted,ans ); + assertEquals(excepted, ans); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java index 05f036ed3b65..773eed7ab39a 100644 --- a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; public class BeadSortTest { - //BeadSort can't sort negative number, Character, String. It can sort positive number only + // BeadSort can't sort negative number, Character, String. It can sort positive number only private BeadSort beadSort = new BeadSort(); - + @Test public void beadSortEmptyArray() { int[] inputArray = {}; @@ -18,23 +18,23 @@ public void beadSortEmptyArray() { @Test public void beadSortSingleIntegerArray() { - int[] inputArray = { 4 }; + int[] inputArray = {4}; int[] outputArray = beadSort.sort(inputArray); - int[] expectedOutput = { 4 }; + int[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 99, 27, 15, 23, 36 }; + int[] inputArray = {6, 1, 99, 27, 15, 23, 36}; int[] outputArray = beadSort.sort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void bogoSortDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 27, 15, 23, 27, 36, 23 }; + int[] inputArray = {6, 1, 27, 15, 23, 27, 36, 23}; int[] outputArray = beadSort.sort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36}; assertArrayEquals(outputArray, expectedOutput); diff --git a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java index 656b499c6cfa..5261d6c64785 100644 --- a/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java @@ -11,16 +11,16 @@ class BinaryInsertionSortTest { @Test // valid test case public void BinaryInsertionSortTestNonDuplicate() { - int[] array = { 1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7 }; - int[] expResult = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + int[] array = {1, 0, 2, 5, 3, 4, 9, 8, 10, 6, 7}; + int[] expResult = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] actResult = BIS.binaryInsertSort(array); assertArrayEquals(expResult, actResult); } @Test public void BinaryInsertionSortTestDuplicate() { - int[] array = { 1, 1, 1, 5, 9, 8, 7, 2, 6 }; - int[] expResult = { 1, 1, 1, 2, 5, 6, 7, 8, 9 }; + int[] array = {1, 1, 1, 5, 9, 8, 7, 2, 6}; + int[] expResult = {1, 1, 1, 2, 5, 6, 7, 8, 9}; int[] actResult = BIS.binaryInsertSort(array); assertArrayEquals(expResult, actResult); } diff --git a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java index 249499816a11..3ebfb7a305b0 100644 --- a/src/test/java/com/thealgorithms/sorts/BogoSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BogoSortTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; public class BogoSortTest { - + private BogoSort bogoSort = new BogoSort(); - + @Test public void bogoSortEmptyArray() { Integer[] inputArray = {}; @@ -18,49 +18,49 @@ public void bogoSortEmptyArray() { @Test public void bogoSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void bogoSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = bogoSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bogoSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = bogoSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java index 1d8cdd31c5ab..8690a3f5435c 100644 --- a/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BubbleSortTest.java @@ -22,23 +22,23 @@ public void bubbleSortEmptyArray() { @Test public void bubbleSortSingleIntegerElementArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = bubbleSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortSingleStringElementArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = bubbleSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bubbleSortIntegerArray() { - Integer[] inputArray = { 4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12 }; + Integer[] inputArray = {4, 23, -6, 78, 1, 54, 23, -6, -231, 9, 12}; Integer[] outputArray = bubbleSort.sort(inputArray); Integer[] expectedOutput = { -231, diff --git a/src/test/java/com/thealgorithms/sorts/BucketSortTest.java b/src/test/java/com/thealgorithms/sorts/BucketSortTest.java index 1f66be5bd08b..84efde25fdfe 100644 --- a/src/test/java/com/thealgorithms/sorts/BucketSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/BucketSortTest.java @@ -8,15 +8,15 @@ public class BucketSortTest { @Test public void bucketSortSingleIntegerArray() { - int[] inputArray = { 4 }; + int[] inputArray = {4}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { 4 }; + int[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bucketSortNonDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 99, 27, 15, 23, 36 }; + int[] inputArray = {6, 1, 99, 27, 15, 23, 36}; int[] outputArray = BucketSort.bucketSort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99}; assertArrayEquals(outputArray, expectedOutput); @@ -24,7 +24,7 @@ public void bucketSortNonDuplicateIntegerArray() { @Test public void bucketSortDuplicateIntegerArray() { - int[] inputArray = { 6, 1, 27, 15, 23, 27, 36, 23 }; + int[] inputArray = {6, 1, 27, 15, 23, 27, 36, 23}; int[] outputArray = BucketSort.bucketSort(inputArray); int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36}; assertArrayEquals(outputArray, expectedOutput); @@ -32,17 +32,17 @@ public void bucketSortDuplicateIntegerArray() { @Test public void bucketSortNonDuplicateIntegerArrayWithNegativeNum() { - int[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + int[] inputArray = {6, -1, 99, 27, -15, 23, -36}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + int[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } @Test public void bucketSortDuplicateIntegerArrayWithNegativeNum() { - int[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + int[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; int[] outputArray = BucketSort.bucketSort(inputArray); - int[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + int[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java b/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java index 46563d152b45..56628b78de02 100644 --- a/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java @@ -9,11 +9,11 @@ * @see CocktailShakerSort */ public class CocktailShakerSortTest { - + private CocktailShakerSort cocktailShakerSort = new CocktailShakerSort(); @Test - public void cocktailShakerSortEmptyArray(){ + public void cocktailShakerSortEmptyArray() { Integer[] inputArray = {}; Integer[] outputArray = cocktailShakerSort.sort(inputArray); Integer[] expectedOutput = {}; @@ -21,7 +21,7 @@ public void cocktailShakerSortEmptyArray(){ } @Test - public void cocktailShakerSortSingleStringElementArray(){ + public void cocktailShakerSortSingleStringElementArray() { String[] inputArray = {"Test"}; String[] outputArray = cocktailShakerSort.sort(inputArray); String[] expectedOutput = {"Test"}; @@ -29,15 +29,15 @@ public void cocktailShakerSortSingleStringElementArray(){ } @Test - public void cocktailShakerSortIntegerArray(){ - Integer[] inputArray = { 2, 92, 1, 33, -33, 27, 5, 100, 78, 99, -100}; + public void cocktailShakerSortIntegerArray() { + Integer[] inputArray = {2, 92, 1, 33, -33, 27, 5, 100, 78, 99, -100}; Integer[] outputArray = cocktailShakerSort.sort(inputArray); - Integer[] expectedOutput = { -100, -33, 1, 2, 5, 27, 33, 78, 92, 99, 100}; + Integer[] expectedOutput = {-100, -33, 1, 2, 5, 27, 33, 78, 92, 99, 100}; assertArrayEquals(outputArray, expectedOutput); } @Test - public void cocktailShakerSortStringArray(){ + public void cocktailShakerSortStringArray() { String[] inputArray = { "g3x1", "dN62", diff --git a/src/test/java/com/thealgorithms/sorts/CombSortTest.java b/src/test/java/com/thealgorithms/sorts/CombSortTest.java index a6eb40c6b3c9..1b2ca1453195 100644 --- a/src/test/java/com/thealgorithms/sorts/CombSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/CombSortTest.java @@ -12,7 +12,7 @@ public class CombSortTest { private CombSort combSort = new CombSort(); - + @Test public void combSortEmptyArray() { Integer[] inputArray = {}; @@ -28,61 +28,41 @@ public void combSortSingleStringElement() { String[] expectedArray = {"Test"}; assertArrayEquals(outputArray, expectedArray); } - + @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); } - @Test + @Test public void combSortIntegerArray() { - Integer[] inputArray = { 36, 98, -51, -23, 66, -58, 31, 25, -30, 40 }; + Integer[] inputArray = {36, 98, -51, -23, 66, -58, 31, 25, -30, 40}; Integer[] outputArray = combSort.sort(inputArray); - Integer[] expectedArray = { -58, -51, -30, -23, 25, 31, 36, 40, 66, 98 }; + Integer[] expectedArray = {-58, -51, -30, -23, 25, 31, 36, 40, 66, 98}; assertArrayEquals(outputArray, expectedArray); } @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, 0.1065247772, - 0.1961108601, 0.3096396752, - 0.3973191975, 0.6118850724, - 0.6172800885, 0.6433840668, - 0.8335545399, 0.9346214114, + 0.0553975453, + 0.1065247772, + 0.1961108601, + 0.3096396752, + 0.3973191975, + 0.6118850724, + 0.6172800885, + 0.6433840668, + 0.8335545399, + 0.9346214114, }; assertArrayEquals(outputArray, expectedArray); } diff --git a/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java b/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java index 04a612ae90e5..1edfb5facfc2 100644 --- a/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java @@ -22,42 +22,41 @@ void quickSortEmptyArrayShouldPass() { @Test void quickSortSingleValueArrayShouldPass() { - Integer[] array = { 7 }; + Integer[] array = {7}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 7 }; + Integer[] expected = {7}; assertArrayEquals(expected, sorted); } @Test void quickSortWithIntegerArrayShouldPass() { - Integer[] array = { 49, 4, 36, 9, 144, 1 }; + Integer[] array = {49, 4, 36, 9, 144, 1}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 1, 4, 9, 36, 49, 144 }; + Integer[] expected = {1, 4, 9, 36, 49, 144}; assertArrayEquals(expected, sorted); } @Test void quickSortForArrayWithNegativeValuesShouldPass() { - Integer[] array = { 49, -36, -124, -49, 12, 9 }; + Integer[] array = {49, -36, -124, -49, 12, 9}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { -124, -49, -36, 9, 12, 49 }; + Integer[] expected = {-124, -49, -36, 9, 12, 49}; assertArrayEquals(expected, sorted); } @Test void quickSortForArrayWithDuplicateValuesShouldPass() { - Integer[] array = { 36, 1, 49, 1, 4, 9 }; + Integer[] array = {36, 1, 49, 1, 4, 9}; Integer[] sorted = dualPivotquickSort.sort(array); - Integer[] expected = { 1, 1, 4, 9, 36, 49 }; + Integer[] expected = {1, 1, 4, 9, 36, 49}; assertArrayEquals(expected, sorted); } @Test void quickSortWithStringArrayShouldPass() { - String[] array = { "cat", "ant", "eat", "boss", "dog", "apple" }; + String[] array = {"cat", "ant", "eat", "boss", "dog", "apple"}; String[] sorted = dualPivotquickSort.sort(array); - String[] expected = { "ant", "apple", "boss", "cat", "dog", "eat" }; + String[] expected = {"ant", "apple", "boss", "cat", "dog", "eat"}; assertArrayEquals(expected, sorted); } - } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java index 0048c8437d80..7c81aefc6d04 100644 --- a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java @@ -12,8 +12,8 @@ public class DutchNationalFlagSortTest { Partitions on the result array: [ smaller than 1 , equal 1, greater than 1] */ void DNFSTestOdd() { - Integer[] integers = { 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 1, 4, 3 }; + Integer[] integers = {1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 1, 4, 3}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -25,8 +25,8 @@ void DNFSTestOdd() { Partitions on the result array: [ smaller than 3 , equal 3, greater than 3] */ void DNFSTestEven() { - Integer[] integers = { 8, 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 1, 3, 4, 8 }; + Integer[] integers = {8, 1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 1, 3, 4, 8}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers); assertArrayEquals(integers, integersResult); @@ -38,8 +38,8 @@ void DNFSTestEven() { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestEvenStrings() { - String[] strings = { "a", "d", "b", "s", "e", "e" }; - String[] stringsResult = { "a", "b", "s", "e", "e", "d" }; + String[] strings = {"a", "d", "b", "s", "e", "e"}; + String[] stringsResult = {"a", "b", "s", "e", "e", "d"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -51,8 +51,8 @@ void DNFSTestEvenStrings() { Partitions on the result array: [ smaller than b , equal b, greater than b] */ void DNFSTestOddStrings() { - String[] strings = { "a", "d", "b", "s", "e" }; - String[] stringsResult = { "a", "b", "s", "e", "d" }; + String[] strings = {"a", "d", "b", "s", "e"}; + String[] stringsResult = {"a", "b", "s", "e", "d"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings); assertArrayEquals(strings, stringsResult); @@ -64,8 +64,8 @@ void DNFSTestOddStrings() { Partitions on the result array: [ smaller than 0 , equal 0, greater than 0] */ void DNFSTestOddMidGiven() { - Integer[] integers = { 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 4, 3, 1 }; + Integer[] integers = {1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 4, 3, 1}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 0); assertArrayEquals(integers, integersResult); @@ -77,8 +77,8 @@ void DNFSTestOddMidGiven() { Partitions on the result array: [ smaller than 4 , equal 4, greater than 4] */ void DNFSTestEvenMidGiven() { - Integer[] integers = { 8, 1, 3, 1, 4, 0 }; - Integer[] integersResult = { 0, 1, 3, 1, 4, 8 }; + Integer[] integers = {8, 1, 3, 1, 4, 0}; + Integer[] integersResult = {0, 1, 3, 1, 4, 8}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(integers, 4); assertArrayEquals(integers, integersResult); @@ -90,8 +90,8 @@ void DNFSTestEvenMidGiven() { Partitions on the result array: [ smaller than s , equal s, greater than s] */ void DNFSTestEvenStringsMidGiven() { - String[] strings = { "a", "d", "b", "s", "e", "e" }; - String[] stringsResult = { "a", "d", "b", "e", "e", "s" }; + String[] strings = {"a", "d", "b", "s", "e", "e"}; + String[] stringsResult = {"a", "d", "b", "e", "e", "s"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "s"); assertArrayEquals(strings, stringsResult); @@ -103,8 +103,8 @@ void DNFSTestEvenStringsMidGiven() { Partitions on the result array: [ smaller than e , equal e, greater than e] */ void DNFSTestOddStringsMidGiven() { - String[] strings = { "a", "d", "b", "s", "e" }; - String[] stringsResult = { "a", "d", "b", "e", "s" }; + String[] strings = {"a", "d", "b", "s", "e"}; + String[] stringsResult = {"a", "d", "b", "e", "s"}; DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort(); dutchNationalFlagSort.sort(strings, "e"); assertArrayEquals(strings, stringsResult); diff --git a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java index 2202872f763e..87a2c73384c3 100644 --- a/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java @@ -1,11 +1,10 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.function.Function; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; class InsertionSortTest { private InsertionSort insertionSort; diff --git a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java index caaf3f4b5914..91f9aeb43939 100644 --- a/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; + public class IntrospectiveSortTest { @Test // valid test case @@ -34,9 +34,8 @@ public void StrandSortEmptyTest() { // 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 8bc7c0b27b8b..745e11391bb1 100644 --- a/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java +++ b/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java @@ -5,31 +5,31 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.jupiter.api.Test; public class MergeSortRecursiveTest { - -// private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(); - - @Test - void testMergeSortRecursiveCase1 () { - MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); - - List<Integer> expected = Arrays.asList(3, 5, 9, 12, 15, 88); - List<Integer> sorted = mergeSortRecursive.mergeSort(); - - assertEquals(expected, sorted); - } - - @Test - void testMergeSortRecursiveCase2 () { - MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); - - List<Integer> expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); - List<Integer> sorted = mergeSortRecursive.mergeSort(); - - assertEquals(expected, sorted); - } + // private MergeSortRecursive mergeSortRecursive = new MergeSortRecursive(); + + @Test + void testMergeSortRecursiveCase1() { + MergeSortRecursive mergeSortRecursive + = new MergeSortRecursive(Arrays.asList(5, 12, 9, 3, 15, 88)); + + List<Integer> expected = Arrays.asList(3, 5, 9, 12, 15, 88); + List<Integer> sorted = mergeSortRecursive.mergeSort(); + + assertEquals(expected, sorted); + } + + @Test + void testMergeSortRecursiveCase2() { + MergeSortRecursive mergeSortRecursive + = new MergeSortRecursive(Arrays.asList(-3, 5, 3, 4, 3, 7, 40, -20, 30, 0)); + + List<Integer> expected = Arrays.asList(-20, -3, 0, 3, 3, 4, 5, 7, 30, 40); + List<Integer> sorted = mergeSortRecursive.mergeSort(); + + assertEquals(expected, sorted); + } } diff --git a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java index 8c031871f330..e6d86325e6c2 100644 --- a/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java @@ -13,7 +13,7 @@ public class OddEvenSortTest { private OddEvenSort oddEvenSort = new OddEvenSort(); @Test - public void oddEvenSortEmptyArray(){ + public void oddEvenSortEmptyArray() { int[] inputArray = {}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {}; @@ -21,7 +21,7 @@ public void oddEvenSortEmptyArray(){ } @Test - public void oddEvenSortNaturalNumberArray(){ + public void oddEvenSortNaturalNumberArray() { int[] inputArray = {18, 91, 86, 60, 21, 44, 37, 78, 98, 67}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {18, 21, 37, 44, 60, 67, 78, 86, 91, 98}; @@ -29,11 +29,10 @@ public void oddEvenSortNaturalNumberArray(){ } @Test - public void oddEvenSortIntegerArray(){ + public void oddEvenSortIntegerArray() { int[] inputArray = {57, 69, -45, 12, -85, 3, -76, 36, 67, -14}; oddEvenSort.oddEvenSort(inputArray); int[] expectedOutput = {-85, -76, -45, -14, 3, 12, 36, 57, 67, 69}; assertArrayEquals(inputArray, expectedOutput); } - } diff --git a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java index ebe153e68de1..36470f86451d 100644 --- a/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java @@ -9,25 +9,19 @@ class SelectionSortTest { @Test // valid test case void IntegerArrTest() { - Integer[] arr = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; SelectionSort selectionSort = new SelectionSort(); - assertArrayEquals( - new Integer[] { 1, 4, 6, 9, 12, 23, 54, 78, 231 }, - selectionSort.sort(arr) - ); + assertArrayEquals(new Integer[] {1, 4, 6, 9, 12, 23, 54, 78, 231}, selectionSort.sort(arr)); } @Test // valid test case void StringArrTest() { - String[] arr = { "c", "a", "e", "b", "d" }; + String[] arr = {"c", "a", "e", "b", "d"}; SelectionSort selectionSort = new SelectionSort(); - assertArrayEquals( - new String[] { "a", "b", "c", "d", "e" }, - selectionSort.sort(arr) - ); + assertArrayEquals(new String[] {"a", "b", "c", "d", "e"}, selectionSort.sort(arr)); } @Test diff --git a/src/test/java/com/thealgorithms/sorts/ShellSortTest.java b/src/test/java/com/thealgorithms/sorts/ShellSortTest.java index 60c6292f4402..cecc8d8bd581 100644 --- a/src/test/java/com/thealgorithms/sorts/ShellSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/ShellSortTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; public class ShellSortTest { - + private ShellSort shellSort = new ShellSort(); - + @Test public void ShellSortEmptyArray() { Integer[] inputArray = {}; @@ -18,50 +18,49 @@ public void ShellSortEmptyArray() { @Test public void ShellSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void ShellSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = shellSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void ShellSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = shellSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } - } diff --git a/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java b/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java index a4654247cbf4..e476b97b96e0 100644 --- a/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java @@ -5,9 +5,9 @@ import org.junit.jupiter.api.Test; public class SimpleSortTest { - + private SimpleSort simpleSort = new SimpleSort(); - + @Test public void simpleSortEmptyArray() { Integer[] inputArray = {}; @@ -18,49 +18,49 @@ public void simpleSortEmptyArray() { @Test public void simpleSortSingleIntegerArray() { - Integer[] inputArray = { 4 }; + Integer[] inputArray = {4}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { 4 }; + Integer[] expectedOutput = {4}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortSingleStringArray() { - String[] inputArray = { "s" }; + String[] inputArray = {"s"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = { "s" }; + String[] expectedOutput = {"s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortNonDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 99, 27, -15, 23, -36 }; + Integer[] inputArray = {6, -1, 99, 27, -15, 23, -36}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 27, 99}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 27, 99}; assertArrayEquals(outputArray, expectedOutput); } - + @Test public void simpleSortDuplicateIntegerArray() { - Integer[] inputArray = { 6, -1, 27, -15, 23, 27, -36, 23 }; + Integer[] inputArray = {6, -1, 27, -15, 23, 27, -36, 23}; Integer[] outputArray = simpleSort.sort(inputArray); - Integer[] expectedOutput = { -36, -15, -1, 6, 23, 23, 27, 27}; + Integer[] expectedOutput = {-36, -15, -1, 6, 23, 23, 27, 27}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortNonDuplicateStringArray() { - String[] inputArray = { "s", "b", "k", "a", "d", "c", "h" }; + String[] inputArray = {"s", "b", "k", "a", "d", "c", "h"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s" }; + String[] expectedOutput = {"a", "b", "c", "d", "h", "k", "s"}; assertArrayEquals(outputArray, expectedOutput); } @Test public void simpleSortDuplicateStringArray() { - String[] inputArray = { "s", "b", "d", "a", "d", "c", "h", "b" }; + String[] inputArray = {"s", "b", "d", "a", "d", "c", "h", "b"}; String[] outputArray = simpleSort.sort(inputArray); - String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s" }; + String[] expectedOutput = {"a", "b", "b", "c", "d", "d", "h", "s"}; assertArrayEquals(outputArray, expectedOutput); } } diff --git a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java index d4d9eaa1c275..5d5d1556a0b7 100644 --- a/src/test/java/com/thealgorithms/sorts/SlowSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/SlowSortTest.java @@ -71,9 +71,11 @@ public void slowSortDuplicateStringArray() { @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/SortUtilsRandomGeneratorTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java index 30fd22c2da81..16571b3b9d24 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - class SortUtilsRandomGeneratorTest { @RepeatedTest(1000) diff --git a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java index 249c251dd470..34a6b00dd9a8 100644 --- a/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java @@ -1,10 +1,9 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; class SortUtilsTest { diff --git a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java index d7230f6da31c..ac11b8adfbdf 100644 --- a/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java +++ b/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java @@ -1,21 +1,20 @@ package com.thealgorithms.sorts; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class SortingAlgorithmTest { abstract SortAlgorithm getSortAlgorithm(); @Test void shouldAcceptWhenEmptyArrayIsPassed() { - Integer[] array = new Integer[]{}; - Integer[] expected = new Integer[]{}; + Integer[] array = new Integer[] {}; + Integer[] expected = new Integer[] {}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -34,8 +33,8 @@ void shouldAcceptWhenEmptyListIsPassed() { @Test void shouldAcceptWhenSingleValuedArrayIsPassed() { - Integer[] array = new Integer[]{2}; - Integer[] expected = new Integer[]{2}; + Integer[] array = new Integer[] {2}; + Integer[] expected = new Integer[] {2}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -54,8 +53,8 @@ void shouldAcceptWhenSingleValuedListIsPassed() { @Test void shouldAcceptWhenListWithAllPositiveValuesIsPassed() { - Integer[] array = new Integer[]{60, 7, 55, 9, 999, 3}; - Integer[] expected = new Integer[]{3, 7, 9, 55, 60, 999}; + Integer[] array = new Integer[] {60, 7, 55, 9, 999, 3}; + Integer[] expected = new Integer[] {3, 7, 9, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -74,8 +73,8 @@ void shouldAcceptWhenArrayWithAllPositiveValuesIsPassed() { @Test void shouldAcceptWhenArrayWithAllNegativeValuesIsPassed() { - Integer[] array = new Integer[]{-60, -7, -55, -9, -999, -3}; - Integer[] expected = new Integer[]{-999, -60, -55, -9, -7, -3}; + Integer[] array = new Integer[] {-60, -7, -55, -9, -999, -3}; + Integer[] expected = new Integer[] {-999, -60, -55, -9, -7, -3}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -94,8 +93,8 @@ void shouldAcceptWhenListWithAllNegativeValuesIsPassed() { @Test void shouldAcceptWhenArrayWithRealNumberValuesIsPassed() { - Integer[] array = new Integer[]{60, -7, 55, 9, -999, -3}; - Integer[] expected = new Integer[]{-999, -7, -3, 9, 55, 60}; + Integer[] array = new Integer[] {60, -7, 55, 9, -999, -3}; + Integer[] expected = new Integer[] {-999, -7, -3, 9, 55, 60}; Integer[] sorted = getSortAlgorithm().sort(array); @@ -114,8 +113,8 @@ void shouldAcceptWhenListWithRealNumberValuesIsPassed() { @Test void shouldAcceptWhenArrayWithDuplicateValueIsPassed() { - Integer[] array = new Integer[]{60, 7, 55, 55, 999, 3}; - Integer[] expected = new Integer[]{3, 7, 55, 55, 60, 999}; + Integer[] array = new Integer[] {60, 7, 55, 55, 999, 3}; + Integer[] expected = new Integer[] {3, 7, 55, 55, 60, 999}; Integer[] sorted = getSortAlgorithm().sort(array); diff --git a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java index 9e46c9cc266e..aa9e203c840a 100644 --- a/src/test/java/com/thealgorithms/sorts/StrandSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/StrandSortTest.java @@ -11,10 +11,9 @@ class StrandSortTest { @Test // valid test case public void StrandSortNonDuplicateTest() { - int[] expectedArray = { 1, 2, 3, 4, 5 }; - LinkedList<Integer> actualList = StrandSort.strandSort( - new LinkedList<Integer>(Arrays.asList(3, 1, 2, 4, 5)) - ); + int[] expectedArray = {1, 2, 3, 4, 5}; + LinkedList<Integer> actualList + = StrandSort.strandSort(new LinkedList<Integer>(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,10 +24,9 @@ public void StrandSortNonDuplicateTest() { @Test // valid test case public void StrandSortDuplicateTest() { - int[] expectedArray = { 2, 2, 2, 5, 7 }; - LinkedList<Integer> actualList = StrandSort.strandSort( - new LinkedList<Integer>(Arrays.asList(7, 2, 2, 2, 5)) - ); + int[] expectedArray = {2, 2, 2, 5, 7}; + LinkedList<Integer> actualList + = StrandSort.strandSort(new LinkedList<Integer>(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/TimSortTest.java b/src/test/java/com/thealgorithms/sorts/TimSortTest.java index 85df96f5367f..564afe379ac5 100644 --- a/src/test/java/com/thealgorithms/sorts/TimSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TimSortTest.java @@ -1,10 +1,10 @@ package com.thealgorithms.sorts; +import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.*; - class TimSortTest extends SortingAlgorithmTest { @Override SortAlgorithm getSortAlgorithm() { diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java index fe678c00c1bb..6ee84b7b81c3 100644 --- a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java @@ -53,13 +53,10 @@ public void failureTest() { graph.addEdge("6", "2"); graph.addEdge("7", ""); graph.addEdge("8", ""); - Exception exception = assertThrows( - BackEdgeException.class, - () -> TopologicalSort.sort(graph) - ); - String expected = - "This graph contains a cycle. No linear ordering is possible. " + - "Back edge: 6 -> 2"; + 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 5c99c2d691d0..39ec5aad5fd3 100644 --- a/src/test/java/com/thealgorithms/sorts/TreeSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/TreeSortTest.java @@ -12,8 +12,8 @@ public class TreeSortTest { private TreeSort treeSort = new TreeSort(); - @Test - public void treeSortEmptyArray(){ + @Test + public void treeSortEmptyArray() { Integer[] inputArray = {}; Integer[] outputArray = treeSort.sort(inputArray); Integer[] expectedOutput = {}; @@ -30,59 +30,29 @@ public void treeSortSingleStringElement() { @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); } - @Test + @Test public void treeSortIntegerArray() { - Integer[] inputArray = { -97, -44, -4, -85, -92, 74, 79, -26, 76, -5 }; + Integer[] inputArray = {-97, -44, -4, -85, -92, 74, 79, -26, 76, -5}; Integer[] outputArray = treeSort.sort(inputArray); - Integer[] expectedArray = { -97, -92, -85, -44, -26, -5, -4, 74, 76, 79 }; + Integer[] expectedArray = {-97, -92, -85, -44, -26, -5, -4, 74, 76, 79}; assertArrayEquals(outputArray, expectedArray); } @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/sorts/WiggleSortTest.java b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java index cddbb432db7d..449c8c11ba78 100644 --- a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java +++ b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java @@ -10,8 +10,8 @@ public class WiggleSortTest { @Test void WiggleTestNumbersEven() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 3, 4 }; - Integer[] result = { 1, 4, 2, 3 }; + Integer[] values = {1, 2, 3, 4}; + Integer[] result = {1, 4, 2, 3}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -19,8 +19,8 @@ void WiggleTestNumbersEven() { @Test void WiggleTestNumbersOdd() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 3, 4, 5 }; - Integer[] result = { 3, 5, 1, 4, 2 }; + Integer[] values = {1, 2, 3, 4, 5}; + Integer[] result = {3, 5, 1, 4, 2}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -28,8 +28,8 @@ void WiggleTestNumbersOdd() { @Test void WiggleTestNumbersOddDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 7, 2, 2, 2, 5 }; - Integer[] result = { 2, 7, 2, 5, 2 }; + Integer[] values = {7, 2, 2, 2, 5}; + Integer[] result = {2, 7, 2, 5, 2}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -37,8 +37,8 @@ void WiggleTestNumbersOddDuplicates() { @Test void WiggleTestNumbersOddMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 1, 2, 2, 5 }; - Integer[] result = { 2, 5, 1, 2, 1 }; + Integer[] values = {1, 1, 2, 2, 5}; + Integer[] result = {2, 5, 1, 2, 1}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -46,8 +46,8 @@ void WiggleTestNumbersOddMultipleDuplicates() { @Test void WiggleTestNumbersEvenMultipleDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 1, 2, 2, 2, 5 }; - Integer[] result = { 2, 5, 1, 2, 1, 2 }; + Integer[] values = {1, 1, 2, 2, 2, 5}; + Integer[] result = {2, 5, 1, 2, 1, 2}; wiggleSort.sort(values); System.out.println(Arrays.toString(values)); assertArrayEquals(values, result); @@ -56,8 +56,8 @@ void WiggleTestNumbersEvenMultipleDuplicates() { @Test void WiggleTestNumbersEvenDuplicates() { WiggleSort wiggleSort = new WiggleSort(); - Integer[] values = { 1, 2, 4, 4 }; - Integer[] result = { 1, 4, 2, 4 }; + Integer[] values = {1, 2, 4, 4}; + Integer[] result = {1, 4, 2, 4}; wiggleSort.sort(values); assertArrayEquals(values, result); } @@ -65,8 +65,8 @@ void WiggleTestNumbersEvenDuplicates() { @Test void WiggleTestStrings() { WiggleSort wiggleSort = new WiggleSort(); - String[] values = { "a", "b", "d", "c" }; - String[] result = { "a", "d", "b", "c" }; + String[] values = {"a", "b", "d", "c"}; + String[] result = {"a", "d", "b", "c"}; wiggleSort.sort(values); assertArrayEquals(values, result); } diff --git a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java index 386ad125ca6d..1fac37a610ea 100644 --- a/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java +++ b/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java @@ -10,30 +10,16 @@ public class HammingDistanceTest { @Test void testHammingDistance() throws Exception { assertEquals(HammingDistance.calculateHammingDistance("", ""), 0); - assertEquals( - HammingDistance.calculateHammingDistance("java", "java"), - 0 - ); - assertEquals( - HammingDistance.calculateHammingDistance("karolin", "kathrin"), - 3 - ); - assertEquals( - HammingDistance.calculateHammingDistance("kathrin", "kerstin"), - 4 - ); - assertEquals( - HammingDistance.calculateHammingDistance("00000", "11111"), - 5 - ); + assertEquals(HammingDistance.calculateHammingDistance("java", "java"), 0); + assertEquals(HammingDistance.calculateHammingDistance("karolin", "kathrin"), 3); + assertEquals(HammingDistance.calculateHammingDistance("kathrin", "kerstin"), 4); + assertEquals(HammingDistance.calculateHammingDistance("00000", "11111"), 5); } @Test void testNotEqualStringLengths() { Exception exception = assertThrows( - Exception.class, - () -> HammingDistance.calculateHammingDistance("ab", "abc") - ); + 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 9240ac8a51b9..243edf4ffaa7 100644 --- a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java +++ b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + class HorspoolSearchTest { @Test @@ -76,13 +76,12 @@ void testGetLastComparisonsNotMatch() { @Test void testFindFirstPatternNull() { - assertThrows(NullPointerException.class, - () -> HorspoolSearch.findFirst(null, "Hello World")); + assertThrows( + NullPointerException.class, () -> HorspoolSearch.findFirst(null, "Hello World")); } @Test void testFindFirstTextNull() { - assertThrows(NullPointerException.class, - () -> HorspoolSearch.findFirst("Hello", null)); + assertThrows(NullPointerException.class, () -> HorspoolSearch.findFirst("Hello", null)); } } \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java index 08d94250cc99..7392ce2d5783 100644 --- a/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java +++ b/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java @@ -1,7 +1,8 @@ package com.thealgorithms.strings; -import java.util.*; import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; import org.junit.jupiter.api.Test; public class LetterCombinationsOfPhoneNumberTest { @@ -21,14 +22,14 @@ public void letterCombinationsOfPhoneNumber() { // ** Test 2 ** // Input: digits = "2" // Output: ["a","b","c"] - int[] numbers2 = { 2 }; + int[] numbers2 = {2}; List<String> output2 = Arrays.asList("a", "b", "c"); assertTrue(ob.printWords(numbers2, numbers2.length, 0, "").equals(output2)); // ** Test 3 ** // Input: digits = "23" // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] - int[] numbers3 = { 2, 3 }; + int[] numbers3 = {2, 3}; List<String> output3 = Arrays.asList("ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"); assertTrue(ob.printWords(numbers3, numbers3.length, 0, "").equals(output3)); @@ -37,10 +38,10 @@ public void letterCombinationsOfPhoneNumber() { // Output: ["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"] - int[] numbers4 = { 2, 3, 4 }; - List<String> 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"); + int[] numbers4 = {2, 3, 4}; + List<String> 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/LowerTest.java b/src/test/java/com/thealgorithms/strings/LowerTest.java index 7e3ab762cc3b..ebc72f3c7bfd 100644 --- a/src/test/java/com/thealgorithms/strings/LowerTest.java +++ b/src/test/java/com/thealgorithms/strings/LowerTest.java @@ -1,16 +1,16 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class LowerTest { @Test public void toLowerCase() { String input1 = "hello world"; String input2 = "HelLO WoRld"; String input3 = "HELLO WORLD"; - + assertEquals("hello world", Lower.toLowerCase(input1)); assertEquals("hello world", Lower.toLowerCase(input2)); assertEquals("hello world", Lower.toLowerCase(input3)); diff --git a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java index 29dda8c06b80..6d27a8acb415 100644 --- a/src/test/java/com/thealgorithms/strings/MyAtoiTest.java +++ b/src/test/java/com/thealgorithms/strings/MyAtoiTest.java @@ -1,26 +1,26 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class MyAtoiTest { - + @Test void testOne() { assertEquals(42, MyAtoi.myAtoi("42")); } - + @Test void testTwo() { assertEquals(-42, MyAtoi.myAtoi(" -42")); } - + @Test void testThree() { assertEquals(4193, MyAtoi.myAtoi("4193 with words")); } - + @Test void testFour() { assertEquals(0, MyAtoi.myAtoi("0")); diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java index 0545cdb9b016..a3390ff1bb90 100644 --- a/src/test/java/com/thealgorithms/strings/PalindromeTest.java +++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java @@ -8,19 +8,16 @@ public class PalindromeTest { @Test public void palindrome() { - String[] palindromes = { null, "", "aba", "123321", "kayak" }; + 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" }; + 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 d3789d498e65..970e7280496e 100644 --- a/src/test/java/com/thealgorithms/strings/PangramTest.java +++ b/src/test/java/com/thealgorithms/strings/PangramTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; public class PangramTest { @@ -8,12 +9,14 @@ 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")); } diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java index ccf68e1ca0f8..f36994be7cb8 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java @@ -1,33 +1,33 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ReverseStringRecursiveTest { ReverseStringRecursive stringRecursive = new ReverseStringRecursive(); @Test void shouldAcceptWhenEmptyStringIsPassed() { String expected = ""; - String reversed = stringRecursive.reverse(""); + String reversed = stringRecursive.reverse(""); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } @Test void shouldAcceptNotWhenWhenSingleCharacterIsPassed() { String expected = "a"; - String reversed = stringRecursive.reverse("a"); + String reversed = stringRecursive.reverse("a"); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } @Test void shouldAcceptWhenStringIsPassed() { String expected = "dlroWolleH"; - String reversed = stringRecursive.reverse("HelloWorld"); + String reversed = stringRecursive.reverse("HelloWorld"); - assertEquals(expected,reversed); + assertEquals(expected, reversed); } } diff --git a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java index b190a437fa89..137ec7a949ab 100644 --- a/src/test/java/com/thealgorithms/strings/ReverseStringTest.java +++ b/src/test/java/com/thealgorithms/strings/ReverseStringTest.java @@ -1,9 +1,9 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; - import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + public class ReverseStringTest { @Test diff --git a/src/test/java/com/thealgorithms/strings/RotationTest.java b/src/test/java/com/thealgorithms/strings/RotationTest.java index 781a68d8cdb5..239366df92b2 100644 --- a/src/test/java/com/thealgorithms/strings/RotationTest.java +++ b/src/test/java/com/thealgorithms/strings/RotationTest.java @@ -11,5 +11,5 @@ public void testRotation() { assertEquals("eksge", Rotation.rotation("geeks", 2)); assertEquals("anasban", Rotation.rotation("bananas", 3)); assertEquals("abracadabra", Rotation.rotation("abracadabra", 0)); - } + } } diff --git a/src/test/java/com/thealgorithms/strings/StringCompressionTest.java b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java index d02e83ce7e3b..4194cad0b754 100644 --- a/src/test/java/com/thealgorithms/strings/StringCompressionTest.java +++ b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java @@ -1,13 +1,14 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class StringCompressionTest { @ParameterizedTest - @CsvSource({"a,a","aabbb,a2b3","abbbc,ab3c","aabccd,a2bc2d"}) - void stringCompressionTest(String input,String expectedOutput){ - String output=StringCompression.compress(input); + @CsvSource({"a,a", "aabbb,a2b3", "abbbc,ab3c", "aabccd,a2bc2d"}) + void stringCompressionTest(String input, String expectedOutput) { + String output = StringCompression.compress(input); assertEquals(expectedOutput, output); } } diff --git a/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java b/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java index ab215f22e869..13909e636f5c 100644 --- a/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java +++ b/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java @@ -1,24 +1,23 @@ package com.thealgorithms.strings; -import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class ValidParenthesesTest { - + @Test void testOne() { assertEquals(true, ValidParentheses.isValid("()")); } - + @Test void testTwo() { assertEquals(true, ValidParentheses.isValid("()[]{}")); } - - + @Test void testThree() { assertEquals(false, ValidParentheses.isValid("(]")); } - } diff --git a/src/test/java/com/thealgorithms/strings/WordLadderTest.java b/src/test/java/com/thealgorithms/strings/WordLadderTest.java index ad572a136302..5b40df8b4d17 100644 --- a/src/test/java/com/thealgorithms/strings/WordLadderTest.java +++ b/src/test/java/com/thealgorithms/strings/WordLadderTest.java @@ -1,14 +1,15 @@ package com.thealgorithms.strings; import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.Test; + import java.util.*; +import org.junit.jupiter.api.Test; public class WordLadderTest { @Test public void testWordLadder() { - + /** * Test 1: * Input: beginWord = "hit", endWord = "cog", wordList = @@ -33,6 +34,5 @@ public void testWordLadder() { List<String> wordList2 = Arrays.asList("hot", "dot", "dog", "lot", "log"); assertEquals(WordLadder.ladderLength("hit", "cog", wordList2), 0); - - } + } } diff --git a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java index dac3cc8513fb..2dce8cf38c05 100644 --- a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java +++ b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java @@ -9,13 +9,7 @@ public class longestNonRepeativeSubstringTest { public void palindrome() { String input1 = "HelloWorld"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( - longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), - 5 - ); - Assertions.assertEquals( - longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), - 9 - ); + Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input1), 5); + Assertions.assertEquals(longestNonRepeativeSubstring.lengthOfLongestSubstring(input2), 9); } } diff --git a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java index 81d42af93983..02904ddcf6c3 100644 --- a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java +++ b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java @@ -9,13 +9,7 @@ public class zigZagPatternTest { public void palindrome() { String input1 = "HelloWorldFromJava"; String input2 = "javaIsAProgrammingLanguage"; - Assertions.assertEquals( - zigZagPattern.encode(input1, 4), - "HooeWrrmalolFJvlda" - ); - Assertions.assertEquals( - zigZagPattern.encode(input2, 4), - "jAaLgasPrmgaaevIrgmnnuaoig" - ); + Assertions.assertEquals(zigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda"); + Assertions.assertEquals(zigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig"); } }