From da2f82752b9acbd7f70c08830fd921a7a3eeaf26 Mon Sep 17 00:00:00 2001 From: Samuel Facchinello Date: Thu, 13 Jun 2024 18:34:57 +0200 Subject: [PATCH 1/2] enable style NeedBraces --- checkstyle.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/checkstyle.xml b/checkstyle.xml index cb4ee54670ac..712825f6b302 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -155,7 +155,7 @@ - + From f801bfae29f2c9d56bf8c08c0202bd3bb596c61d Mon Sep 17 00:00:00 2001 From: Samuel Facchinello Date: Thu, 13 Jun 2024 18:50:34 +0200 Subject: [PATCH 2/2] style: enable NeedBraces in checkstyle --- .../backtracking/Combination.java | 4 +- .../thealgorithms/backtracking/MColoring.java | 4 +- .../backtracking/WordSearch.java | 8 +- .../com/thealgorithms/ciphers/Blowfish.java | 16 ++- .../ciphers/a5/A5KeyStreamGenerator.java | 4 +- .../ciphers/a5/CompositeLFSR.java | 4 +- .../buffers/CircularBuffer.java | 12 +- .../datastructures/graphs/Kosaraju.java | 8 +- .../graphs/TarjansAlgorithm.java | 4 +- .../hashmap/hashing/HashMap.java | 8 +- .../hashmap/hashing/HashMapCuckooHashing.java | 8 +- .../datastructures/heaps/FibonacciHeap.java | 4 +- .../datastructures/heaps/LeftistHeap.java | 16 ++- .../datastructures/heaps/MaxHeap.java | 4 +- .../datastructures/heaps/MinHeap.java | 4 +- .../datastructures/queues/CircularQueue.java | 3 +- .../datastructures/queues/LinkedQueue.java | 16 ++- .../datastructures/queues/PriorityQueues.java | 8 +- .../datastructures/trees/AVLSimple.java | 30 +++-- .../trees/InorderTraversal.java | 4 +- .../datastructures/trees/KDTree.java | 113 +++++++++++++----- .../datastructures/trees/LazySegmentTree.java | 40 +++++-- .../trees/PreOrderTraversal.java | 12 +- .../datastructures/trees/SameTreesCheck.java | 12 +- .../dynamicprogramming/KadaneAlgorithm.java | 4 +- .../OptimalJobScheduling.java | 20 ++-- .../dynamicprogramming/SubsetCount.java | 16 ++- .../dynamicprogramming/Tribonacci.java | 8 +- .../thealgorithms/geometry/GrahamScan.java | 42 ++++--- .../com/thealgorithms/io/BufferedReader.java | 30 +++-- .../com/thealgorithms/maths/AliquotSum.java | 8 +- .../maths/AutomorphicNumber.java | 12 +- .../thealgorithms/maths/HarshadNumber.java | 8 +- .../thealgorithms/maths/KaprekarNumbers.java | 8 +- .../maths/MillerRabinPrimalityCheck.java | 37 ++++-- .../thealgorithms/maths/PascalTriangle.java | 7 +- .../thealgorithms/maths/PerfectNumber.java | 12 +- .../maths/SumWithoutArithmeticOperators.java | 4 +- .../java/com/thealgorithms/others/CRC16.java | 4 +- ...imumSumOfDistinctSubarraysWithLengthK.java | 4 +- .../scheduling/RRScheduling.java | 4 +- .../searches/BinarySearch2dArray.java | 32 +++-- .../com/thealgorithms/searches/KMPSearch.java | 5 +- .../searches/OrderAgnosticBinarySearch.java | 23 ++-- .../thealgorithms/searches/QuickSelect.java | 4 +- .../searches/RabinKarpAlgorithm.java | 12 +- .../searches/RecursiveBinarySearch.java | 5 +- .../sorts/DualPivotQuickSort.java | 12 +- .../thealgorithms/sorts/InsertionSort.java | 11 +- .../com/thealgorithms/sorts/LinkListSort.java | 44 ++++--- .../thealgorithms/sorts/PigeonholeSort.java | 4 +- .../sorts/SortUtilsRandomGenerator.java | 4 +- .../com/thealgorithms/sorts/StrandSort.java | 9 +- .../thealgorithms/sorts/TopologicalSort.java | 4 +- .../stacks/NextSmallerElement.java | 4 +- .../thealgorithms/stacks/PostfixToInfix.java | 24 +++- .../com/thealgorithms/strings/Anagrams.java | 4 +- .../strings/LongestNonRepeativeSubstring.java | 25 ++-- .../com/thealgorithms/strings/MyAtoi.java | 4 +- .../com/thealgorithms/strings/Pangram.java | 7 +- .../strings/ValidParentheses.java | 12 +- .../strings/zigZagPattern/ZigZagPattern.java | 10 +- .../buffers/CircularBufferTest.java | 32 +++-- .../queues/LinkedQueueTest.java | 8 +- .../trees/LazySegmentTreeTest.java | 3 +- .../thealgorithms/io/BufferedReaderTest.java | 4 +- .../misc/MedianOfRunningArrayTest.java | 4 +- 67 files changed, 626 insertions(+), 258 deletions(-) diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index 80c11ce737fa..bf2a672a0ef8 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -43,7 +43,9 @@ public static List> combination(T[] arr, int n) { * @param the type of elements in the array. */ private static void backtracking(T[] arr, int index, TreeSet currSet, List> result) { - if (index + length - currSet.size() > arr.length) return; + if (index + length - currSet.size() > arr.length) { + return; + } if (length - 1 == currSet.size()) { for (int i = index; i < arr.length; i++) { currSet.add(arr[i]); diff --git a/src/main/java/com/thealgorithms/backtracking/MColoring.java b/src/main/java/com/thealgorithms/backtracking/MColoring.java index 20c42e59e8a1..f069e46cc627 100644 --- a/src/main/java/com/thealgorithms/backtracking/MColoring.java +++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java @@ -59,7 +59,9 @@ static int possiblePaint(ArrayList nodes, int n, int m) { // If number of colors used exceeds m, // return 0 maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color)); - if (maxColors > m) return 0; + if (maxColors > m) { + return 0; + } // If the adjacent node is not visited, // mark it visited and push it in queue diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java index 4ab81bfd7d67..f3a5b0433727 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -51,7 +51,9 @@ 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; @@ -66,7 +68,9 @@ 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; + } } } } diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java index a8fa6fc56088..f6a0a3753e9b 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -1104,7 +1104,9 @@ private String hexToBin(String hex) { private String binToHex(String binary) { long num = Long.parseUnsignedLong(binary, 2); String hex = Long.toHexString(num); - while (hex.length() < (binary.length() / 4)) hex = "0" + hex; + while (hex.length() < (binary.length() / 4)) { + hex = "0" + hex; + } return hex; } @@ -1120,7 +1122,9 @@ 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; } @@ -1202,7 +1206,9 @@ String encrypt(String plainText, String key) { // generating key keyGenerate(key); - for (int i = 0; i < 16; i++) plainText = round(i, plainText); + for (int i = 0; i < 16; i++) { + plainText = round(i, plainText); + } // postprocessing String right = plainText.substring(0, 8); @@ -1224,7 +1230,9 @@ String decrypt(String cipherText, String key) { // generating key keyGenerate(key); - for (int i = 17; i > 1; i--) cipherText = round(i, cipherText); + for (int i = 17; i > 1; i--) { + cipherText = round(i, cipherText); + } // postprocessing String right = cipherText.substring(0, 8); diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java index 2e92498056ae..0b17a685bc57 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java @@ -31,7 +31,9 @@ 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 3cac558237c2..f96946c39490 100644 --- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java +++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java @@ -19,7 +19,9 @@ public boolean clock() { boolean result = false; for (var register : registers) { result ^= register.getLastBit(); - if (register.getClockBit() == majorityBit) register.clock(); + if (register.getClockBit() == majorityBit) { + register.clock(); + } } return result; } diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java index 63295b83abe6..15e9a0956226 100644 --- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java +++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java @@ -24,7 +24,9 @@ public boolean isFull() { } public Item get() { - if (isEmpty()) return null; + if (isEmpty()) { + return null; + } Item item = buffer[getPointer.getAndIncrement()]; size.decrementAndGet(); @@ -32,7 +34,9 @@ public Item get() { } public boolean put(Item item) { - if (isFull()) return false; + if (isFull()) { + return false; + } buffer[putPointer.getAndIncrement()] = item; size.incrementAndGet(); @@ -49,7 +53,9 @@ private static class CircularPointer { } 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/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java index c24046f510af..7c0c0b2bee78 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java @@ -127,7 +127,9 @@ public void findStronglyConnectedComponents(int v, List> transpose private void dfs(int node, int[] vis, List> list) { vis[node] = 1; for (Integer neighbour : list.get(node)) { - if (vis[neighbour] == 0) dfs(neighbour, vis, list); + if (vis[neighbour] == 0) { + dfs(neighbour, vis, list); + } } stack.push(node); } @@ -136,7 +138,9 @@ private void dfs(int node, int[] vis, List> list) { private void dfs2(int node, int[] vis, List> list) { vis[node] = 1; for (Integer neighbour : list.get(node)) { - if (vis[neighbour] == 0) dfs2(neighbour, vis, list); + if (vis[neighbour] == 0) { + dfs2(neighbour, vis, list); + } } scc.add(node); } diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java index 987e73a2a5d5..336e375f7d4e 100644 --- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java +++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java @@ -82,7 +82,9 @@ public List> stronglyConnectedComponents(int v, List Stack st = new Stack(); for (int i = 0; i < v; i++) { - if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph); + if (insertionTime[i] == -1) { + stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph); + } } return sccList; diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java index ad273deaf4f0..e0b394b12bf6 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java @@ -68,10 +68,14 @@ private Node findEnd(Node n) { public Node findKey(int key) { if (!isEmpty()) { Node temp = first; - if (temp.getKey() == key) return temp; + if (temp.getKey() == key) { + return temp; + } while ((temp = temp.getNext()) != null) { - if (temp.getKey() == key) return temp; + if (temp.getKey() == key) { + return temp; + } } } return null; 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 b48502b51d08..a67968d7e659 100644 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java @@ -188,12 +188,14 @@ public int findKeyInTable(int key) { throw new IllegalArgumentException("Table is empty"); } - if (Objects.equals(buckets[hash], wrappedInt)) return hash; + if (Objects.equals(buckets[hash], wrappedInt)) { + return hash; + } hash = hashFunction2(key); - if (!Objects.equals(buckets[hash], wrappedInt)) + if (!Objects.equals(buckets[hash], wrappedInt)) { throw new IllegalArgumentException("Key " + key + " not found in table"); - else { + } else { return hash; } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java index 4aa7db1956ea..4734483b518b 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java @@ -231,7 +231,9 @@ private void updateMin(HeapNode posMin) { private void cascadingCuts(HeapNode curr) { if (!curr.isMarked()) { // stop the recursion curr.mark(); - if (!curr.isRoot()) this.markedHeapNoodesCounter++; + if (!curr.isRoot()) { + this.markedHeapNoodesCounter++; + } } else { if (curr.isRoot()) { return; diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java index 59cb9dfab700..ca18673c6724 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java @@ -56,9 +56,13 @@ public void merge(LeftistHeap h1) { // Function merge with two Nodes a and b public Node merge(Node a, Node b) { - if (a == null) return b; + if (a == null) { + return b; + } - if (b == null) return a; + if (b == null) { + return a; + } // Violates leftist property, so must do a swap if (a.element > b.element) { @@ -93,7 +97,9 @@ public void insert(int a) { // Returns and removes the minimum element in the heap public int extractMin() { // If is empty return -1 - if (isEmpty()) return -1; + if (isEmpty()) { + return -1; + } int min = root.element; root = merge(root.left, root.right); @@ -109,7 +115,9 @@ public ArrayList inOrder() { // Auxiliary function for in_order private void inOrderAux(Node n, ArrayList lst) { - if (n == null) return; + if (n == null) { + return; + } inOrderAux(n.left, lst); lst.add(n.element); inOrderAux(n.right, lst); diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 9a584da0411c..067aae738914 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -98,11 +98,13 @@ public final void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (maxHeap.isEmpty()) try { + if (maxHeap.isEmpty()) { + try { throw new EmptyHeapException("Attempt to delete an element from an empty heap"); } catch (EmptyHeapException e) { e.printStackTrace(); } + } if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) { throw new IndexOutOfBoundsException("Index out of heap range"); } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index f7ff0ec5a73d..6e972205acfe 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -92,11 +92,13 @@ public final void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (minHeap.isEmpty()) try { + if (minHeap.isEmpty()) { + try { throw new EmptyHeapException("Attempt to delete an element from an empty heap"); } catch (EmptyHeapException e) { e.printStackTrace(); } + } if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) { throw new IndexOutOfBoundsException("Index out of heap range"); } diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java index cd3761bdcf75..48d9ffe9a42a 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java @@ -23,8 +23,9 @@ public boolean isEmpty() { public boolean isFull() { if (topOfQueue + 1 == beginningOfQueue) { return true; - } else + } 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 171f24e09396..5fba2ff6a69c 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java @@ -125,9 +125,13 @@ public T peekRear() { */ public T peek(int pos) { - if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); + if (pos > size) { + throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); + } Node node = front; - while (pos-- > 0) node = node.next; + while (pos-- > 0) { + node = node.next; + } return node.data; } @@ -170,14 +174,18 @@ 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 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 16a0c1673886..a5ca48670f2c 100644 --- a/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java +++ b/src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java @@ -87,9 +87,13 @@ private void sink(int pos) { while (2 * pos <= nItems) { int current = 2 * pos; // Jump to the positon of child node // Compare both the children for the greater one - if (current < nItems && queueArray[current] < queueArray[current + 1]) current++; + if (current < nItems && queueArray[current] < queueArray[current + 1]) { + current++; + } // If the parent node is greater, sink operation is complete. Break the loop - if (queueArray[pos] >= queueArray[current]) break; + if (queueArray[pos] >= queueArray[current]) { + break; + } // If not exchange the value of parent with child int temp = queueArray[pos]; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java index 052da616fe8e..e0309122cc12 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java @@ -60,9 +60,13 @@ private Node insert(Node node, int item) { node.height = Math.max(height(node.left), height(node.right)) + 1; int bf = bf(node); // LL case - if (bf > 1 && item < node.left.data) return rightRotate(node); + if (bf > 1 && item < node.left.data) { + return rightRotate(node); + } // RR case - if (bf < -1 && item > node.right.data) return leftRotate(node); + if (bf < -1 && item > node.right.data) { + return leftRotate(node); + } // RL case if (bf < -1 && item < node.right.data) { node.right = rightRotate(node.right); @@ -84,18 +88,24 @@ public void display() { private void display(Node node) { String str = ""; - if (node.left != null) + if (node.left != null) { str += node.left.data + "=>"; - else + } else { str += "END=>"; + } str += node.data + ""; - if (node.right != null) + if (node.right != null) { str += "<=" + node.right.data; - else + } else { str += "<=END"; + } System.out.println(str); - if (node.left != null) display(node.left); - if (node.right != null) display(node.right); + if (node.left != null) { + display(node.left); + } + if (node.right != null) { + display(node.right); + } } private int height(Node node) { @@ -106,7 +116,9 @@ private int height(Node node) { } private int bf(Node node) { - if (node == null) return 0; + if (node == null) { + return 0; + } return height(node.left) - height(node.right); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java index 3bae17ed1bb8..5a001ff9ab9f 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java @@ -36,7 +36,9 @@ public static List recursiveInorder(BinaryTree.Node root) { public static List iterativeInorder(BinaryTree.Node root) { List result = new ArrayList<>(); - if (root == null) return result; + if (root == null) { + return result; + } Deque stack = new ArrayDeque<>(); while (!stack.isEmpty() || root != null) { diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java index e5528c392bb8..5190e82f74ef 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java @@ -34,10 +34,15 @@ 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); } @@ -48,11 +53,16 @@ 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"); + for (Point point : points) { + if (point.getDimension() != k) { + throw new IllegalArgumentException("Points must have the same dimension"); + } + } this.root = build(points, 0); } @@ -119,7 +129,9 @@ public static int comparableDistance(Point p1, Point p2) { 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; + if (i == axis) { + continue; + } int t = p1.getCoordinate(i) - p2.getCoordinate(i); distance += t * t; } @@ -164,10 +176,11 @@ public int getAxis() { * @return The nearest child Node */ public Node getNearChild(Point point) { - if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) { return left; - else + } else { return right; + } } /** @@ -178,10 +191,11 @@ public Node getNearChild(Point point) { * @return The farthest child Node */ public Node getFarChild(Point point) { - if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) + if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) { return right; - else + } else { return left; + } } /** @@ -207,9 +221,13 @@ public Node getRoot() { * @return The root of the KDTree */ private Node build(Point[] points, int depth) { - if (points.length == 0) return null; + if (points.length == 0) { + return null; + } int axis = depth % k; - if (points.length == 1) return new Node(points[0], axis); + if (points.length == 1) { + return new Node(points[0], axis); + } Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis))); int median = points.length >> 1; Node node = new Node(points[median], axis); @@ -225,7 +243,9 @@ 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); } @@ -240,11 +260,14 @@ 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()) + if (root == null) { + return new Node(point, axis); + } + if (point.getCoordinate(axis) < root.getAxisCoordinate()) { root.left = insert(root.left, point, depth + 1); - else + } else { root.right = insert(root.right, point, depth + 1); + } return root; } @@ -257,7 +280,9 @@ private Node insert(Node root, Point point, int depth) { * @return The Node corresponding to the specified point */ public Optional search(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension"); + if (point.getDimension() != k) { + throw new IllegalArgumentException("Point has wrong dimension"); + } return search(root, point); } @@ -270,8 +295,12 @@ public Optional search(Point point) { * @return The Node corresponding to the specified point */ public Optional search(Node root, Point point) { - if (root == null) return Optional.empty(); - if (root.point.equals(point)) return Optional.of(root); + if (root == null) { + return Optional.empty(); + } + if (root.point.equals(point)) { + return Optional.of(root); + } return search(root.getNearChild(point), point); } @@ -295,9 +324,13 @@ public Point findMin(int axis) { * @return The Node with minimum value in the specified axis of the point */ public Node findMin(Node root, int axis) { - if (root == null) return null; + if (root == null) { + return null; + } if (root.getAxis() == axis) { - if (root.left == null) return root; + if (root.left == null) { + return root; + } return findMin(root.left, axis); } else { Node left = findMin(root.left, axis); @@ -327,9 +360,13 @@ public Point findMax(int axis) { * @return The Node with maximum value in the specified axis of the point */ public Node findMax(Node root, int axis) { - if (root == null) return null; + if (root == null) { + return null; + } if (root.getAxis() == axis) { - if (root.right == null) return root; + if (root.right == null) { + return root; + } return findMax(root.right, axis); } else { Node left = findMax(root.left, axis); @@ -358,7 +395,9 @@ public void delete(Point point) { * @return The new root of the subtree */ private Node delete(Node root, Node node) { - if (root == null) return null; + if (root == null) { + return null; + } if (root.equals(node)) { if (root.right != null) { Node min = findMin(root.right, root.getAxis()); @@ -368,13 +407,15 @@ 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 + } else { return null; + } } - if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) + if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) { root.left = delete(root.left, node); - else + } else { root.right = delete(root.right, node); + } return root; } @@ -395,13 +436,21 @@ public Point findNearest(Point point) { * @param nearest The nearest neighbor found so far. * */ private Node findNearest(Node root, Point point, Node nearest) { - if (root == null) return nearest; - if (root.point.equals(point)) return root; + 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; + 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/LazySegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java index 1d8febff4b5f..e7a8e23d6610 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java @@ -40,11 +40,19 @@ public void applyUpdate(int diff) { * Shift the lazy value of this node to its children. */ public void shift() { - if (lazy == 0) return; - if (this.left == null && this.right == null) return; + if (lazy == 0) { + return; + } + if (this.left == null && this.right == null) { + return; + } this.value += this.lazy; - if (this.left != null) this.left.applyUpdate(this.lazy); - if (this.right != null) this.right.applyUpdate(this.lazy); + if (this.left != null) { + this.left.applyUpdate(this.lazy); + } + if (this.right != null) { + this.right.applyUpdate(this.lazy); + } this.lazy = 0; } @@ -56,8 +64,12 @@ public void shift() { * @return The new Node. */ static Node merge(Node left, Node right) { - if (left == null) return right; - if (right == null) return left; + if (left == null) { + return right; + } + if (right == null) { + return left; + } Node result = new Node(left.start, right.end, left.value + right.value); result.left = left; result.right = right; @@ -97,7 +109,9 @@ public LazySegmentTree(int[] array) { * @return The root of the new LazySegmentTree. */ private Node buildTree(int[] array, int start, int end) { - if (end - start < 2) return new Node(start, end, array[start]); + if (end - start < 2) { + return new Node(start, end, array[start]); + } int mid = (start + end) >> 1; Node left = buildTree(array, start, mid); Node right = buildTree(array, mid, end); @@ -117,7 +131,9 @@ private void updateRange(int left, int right, int diff, Node curr) { curr.applyUpdate(diff); return; } - if (left >= curr.end || right <= curr.start) return; + if (left >= curr.end || right <= curr.start) { + return; + } curr.shift(); updateRange(left, right, diff, curr.left); updateRange(left, right, diff, curr.right); @@ -133,8 +149,12 @@ private void updateRange(int left, int right, int diff, Node curr) { * @return The Node representing the sum of the given range. */ 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; + 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)); } diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java index 6a0eef369407..3aceac4d1852 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java @@ -36,15 +36,21 @@ public static List recursivePreOrder(BinaryTree.Node root) { public static List iterativePreOrder(BinaryTree.Node root) { List result = new ArrayList<>(); - if (root == null) return result; + if (root == null) { + return result; + } Deque stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { BinaryTree.Node node = stack.pop(); result.add(node.data); - if (node.right != null) stack.push(node.right); - if (node.left != null) stack.push(node.left); + if (node.right != null) { + stack.push(node.right); + } + if (node.left != null) { + stack.push(node.left); + } } return result; diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java index 883eadd1840a..cff27c12f1ca 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java @@ -52,16 +52,22 @@ public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { BinaryTree.Node second = q2.poll(); // check that some node can be null // if the check is true: both nodes are null or both nodes are not null - if (!equalNodes(first, second)) return false; + if (!equalNodes(first, second)) { + return false; + } if (first != null) { - if (!equalNodes(first.left, second.left)) return false; + if (!equalNodes(first.left, second.left)) { + return false; + } if (first.left != null) { q1.add(first.left); q2.add(second.left); } - if (!equalNodes(first.right, second.right)) return false; + if (!equalNodes(first.right, second.right)) { + return false; + } if (first.right != null) { q1.add(first.right); q2.add(second.right); diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java index de75126044ae..9962cca217a0 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -18,7 +18,9 @@ public static boolean maxSum(int[] a, int predictedAnswer) { // running sum of all the indexs are stored sum = Math.max(sum, runningSum); // the max is stored inorder to the get the maximum sum - if (runningSum < 0) runningSum = 0; + if (runningSum < 0) { + runningSum = 0; + } // if running sum is negative then it is initialized to zero } // for-each loop is used to iterate over the array and find the maximum subarray sum diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java index 0840e08c531c..e31bb73096e8 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -69,19 +69,19 @@ 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 { + } else { int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on - // the Machine the previous one was executed + // the Machine the previous one was executed - for (int k = 0; k < numberMachines; k++) // computes the cost of executing the previous - // process to each and every 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 - + // the Process to our Machine + } return findMin(runningCosts); // returns the minimum running cost } } @@ -98,7 +98,9 @@ private int findMin(int[] costArr) { for (int i = 1; i < costArr.length; i++) { - if (costArr[i] < costArr[min]) min = i; + if (costArr[i] < costArr[min]) { + min = i; + } } return costArr[min]; } diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java index af31294f7e0e..cbe3ccae4ac7 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java @@ -29,12 +29,16 @@ public static int getCount(int[] arr, int target) { for (int i = 0; i < n; i++) { dp[i][0] = 1; } - if (arr[0] <= target) dp[0][arr[0]] = 1; + 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]; + if (arr[idx] <= t) { + pick += dp[idx - 1][target - t]; + } dp[idx][target] = pick + notpick; } } @@ -52,14 +56,18 @@ public static 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; + 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]]; + if (arr[ind] <= t) { + taken = prev[t - arr[ind]]; + } cur[t] = notTaken + taken; } prev = cur; diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java index 407566f481a0..3ff6cc620236 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java @@ -15,8 +15,12 @@ private Tribonacci() { * @return the n-th Tribonacci number */ public static int compute(int n) { - if (n == 0) return 0; - if (n == 1 || n == 2) return 1; + if (n == 0) { + return 0; + } + if (n == 1 || n == 2) { + return 1; + } int first = 0; int second = 1; diff --git a/src/main/java/com/thealgorithms/geometry/GrahamScan.java b/src/main/java/com/thealgorithms/geometry/GrahamScan.java index 4f4aebaed971..2773d03b4769 100644 --- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java +++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java @@ -32,13 +32,21 @@ public GrahamScan(Point[] points) { // find index of first point not equal to a[0] (indexPoint1) and the first point that's not // collinear with either (indexPoint2). int indexPoint1; - for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) - if (!points[0].equals(points[indexPoint1])) break; - if (indexPoint1 == points.length) return; + for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) { + if (!points[0].equals(points[indexPoint1])) { + break; + } + } + if (indexPoint1 == points.length) { + return; + } int indexPoint2; - for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) - if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) break; + for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) { + if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) { + break; + } + } hull.push(points[indexPoint2 - 1]); // Now we simply add the point to the stack based on the orientation. @@ -57,7 +65,9 @@ public GrahamScan(Point[] points) { */ public Iterable hull() { Stack s = new Stack<>(); - for (Point p : hull) s.push(p); + for (Point p : hull) { + s.push(p); + } return s; } @@ -112,7 +122,9 @@ public static int orientation(Point a, Point b, Point c) { */ public int compareTo(Point p2) { int res = Integer.compare(this.y, p2.y); - if (res == 0) res = Integer.compare(this.x, p2.x); + if (res == 0) { + res = Integer.compare(this.x, p2.x); + } return res; } @@ -133,19 +145,21 @@ public int compare(Point p1, Point p2) { int dx2 = p2.x - x; int dy2 = p2.y - y; - if (dy1 >= 0 && dy2 < 0) + if (dy1 >= 0 && dy2 < 0) { return -1; // q1 above; q2 below - else if (dy2 >= 0 && dy1 < 0) + } 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) + } else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal + if (dx1 >= 0 && dx2 < 0) { return -1; - else if (dx2 >= 0 && dx1 < 0) + } else if (dx2 >= 0 && dx1 < 0) { return +1; - else + } else { return 0; - } else + } + } else { return -orientation(Point.this, p1, p2); // both above or below + } } } diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java index fa0237a48049..66673fe281ae 100644 --- a/src/main/java/com/thealgorithms/io/BufferedReader.java +++ b/src/main/java/com/thealgorithms/io/BufferedReader.java @@ -44,7 +44,9 @@ public BufferedReader(InputStream input) throws IOException { public BufferedReader(InputStream input, int bufferSize) throws IOException { this.input = input; - if (input.available() == -1) throw new IOException("Empty or already closed stream provided"); + if (input.available() == -1) { + throw new IOException("Empty or already closed stream provided"); + } this.bufferSize = bufferSize; buffer = new byte[bufferSize]; @@ -55,7 +57,9 @@ public BufferedReader(InputStream input, int bufferSize) throws IOException { */ public int read() throws IOException { if (needsRefill()) { - if (foundEof) return -1; + if (foundEof) { + return -1; + } // the buffer is empty, or the buffer has // been completely read and needs to be refilled refill(); @@ -69,10 +73,11 @@ public int read() throws IOException { public int available() throws IOException { int available = input.available(); - if (needsRefill()) + if (needsRefill()) { // since the block is already empty, // we have no responsibility yet return available; + } return bufferPos - posRead + available; } @@ -90,10 +95,14 @@ public int peek() throws IOException { public int peek(int n) throws IOException { int available = available(); - if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n)); + if (n >= available) { + throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n)); + } pushRefreshData(); - if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + if (n >= bufferSize) { + throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + } return buffer[n]; } @@ -105,7 +114,9 @@ public int peek(int n) throws IOException { */ private void pushRefreshData() throws IOException { - for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i]; + for (int i = posRead, j = 0; i < bufferSize; i++, j++) { + buffer[j] = buffer[i]; + } bufferPos -= posRead; posRead = 0; @@ -127,11 +138,12 @@ public byte[] readBlock() throws IOException { byte[] cloned = new byte[bufferSize]; // arraycopy() function is better than clone() - if (bufferPos >= 0) + 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(); @@ -168,7 +180,9 @@ private void justRefill() throws IOException { } private void assertStreamOpen() { - if (input == null) throw new IllegalStateException("Input Stream already closed!"); + if (input == null) { + throw new IllegalStateException("Input Stream already closed!"); + } } public void close() throws IOException { diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java index 5a5555777425..0dbc58bed605 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -34,7 +34,9 @@ public static int getAliquotValue(int number) { * @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); /* @@ -53,7 +55,9 @@ public static int getAliquotSum(int n) { } // 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 (root == (int) root) { + sum -= root; + } return sum; } } diff --git a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java index 560ce3aabd1a..03c8a8989bb2 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -22,7 +22,9 @@ private 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; long numberOfdigits = 0; @@ -42,7 +44,9 @@ 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)); } @@ -56,7 +60,9 @@ 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/HarshadNumber.java b/src/main/java/com/thealgorithms/maths/HarshadNumber.java index 0b1ba1285c4d..5792e925a8aa 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -14,7 +14,9 @@ private HarshadNumber() { * {@code false} */ public static boolean isHarshad(long n) { - if (n <= 0) return false; + if (n <= 0) { + return false; + } long t = n; long sumOfDigits = 0; @@ -35,7 +37,9 @@ public static boolean isHarshad(long n) { */ public static boolean isHarshad(String s) { final 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/KaprekarNumbers.java b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java index f025f86682a2..eb9750f9ce08 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -16,11 +16,15 @@ private KaprekarNumbers() { // Provides a list of kaprekarNumber in a range public static List kaprekarNumberInRange(long start, long end) throws Exception { long n = end - start; - if (n < 0) throw new Exception("Invalid range"); + if (n < 0) { + throw new Exception("Invalid range"); + } ArrayList list = new ArrayList<>(); for (long i = start; i <= end; i++) { - if (isKaprekarNumber(i)) list.add(i); + if (isKaprekarNumber(i)) { + list.add(i); + } } return list; diff --git a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java index e25836f713a9..f889213abfcb 100644 --- a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java +++ b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java @@ -20,7 +20,9 @@ private MillerRabinPrimalityCheck() { */ public static boolean millerRabin(long n, int k) { // returns true if n is probably prime, else returns false. - if (n < 4) return n == 2 || n == 3; + if (n < 4) { + return n == 2 || n == 3; + } int s = 0; long d = n - 1; @@ -31,13 +33,17 @@ public static boolean millerRabin(long n, int k) { // returns true if n is proba Random rnd = new Random(); for (int i = 0; i < k; i++) { long a = 2 + rnd.nextLong(n) % (n - 3); - if (checkComposite(n, a, d, s)) return false; + if (checkComposite(n, a, d, s)) { + return false; + } } return true; } public static boolean deterministicMillerRabin(long n) { // returns true if n is prime, else returns false. - if (n < 2) return false; + if (n < 2) { + return false; + } int r = 0; long d = n - 1; @@ -47,8 +53,12 @@ public static boolean deterministicMillerRabin(long n) { // returns true if n is } for (int a : new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) { - if (n == a) return true; - if (checkComposite(n, a, d, r)) return false; + if (n == a) { + return true; + } + if (checkComposite(n, a, d, r)) { + return false; + } } return true; } @@ -66,10 +76,14 @@ public static boolean deterministicMillerRabin(long n) { // returns true if n is */ private static boolean checkComposite(long n, long a, long d, int s) { long x = powerModP(a, d, n); - if (x == 1 || x == n - 1) return false; + if (x == 1 || x == n - 1) { + return false; + } for (int r = 1; r < s; r++) { x = powerModP(x, 2, n); - if (x == n - 1) return false; + if (x == n - 1) { + return false; + } } return true; } @@ -79,11 +93,14 @@ private static long powerModP(long x, long y, long p) { x = x % p; // Update x if it is more than or equal to p - if (x == 0) return 0; // In case x is divisible by p; - + if (x == 0) { + return 0; // In case x is divisible by p; + } while (y > 0) { // If y is odd, multiply x with result - if ((y & 1) == 1) res = multiplyModP(res, x, p); + if ((y & 1) == 1) { + res = multiplyModP(res, x, p); + } // y must be even now y = y >> 1; // y = y/2 diff --git a/src/main/java/com/thealgorithms/maths/PascalTriangle.java b/src/main/java/com/thealgorithms/maths/PascalTriangle.java index ef6aa41d6e53..95f92fbe1b49 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -52,10 +52,11 @@ public static int[][] pascal(int n) { */ for (int i = 0; i <= line; i++) { // 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 + if (line == i || i == 0) { + arr[line][i] = 1; + } else { arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; + } } } diff --git a/src/main/java/com/thealgorithms/maths/PerfectNumber.java b/src/main/java/com/thealgorithms/maths/PerfectNumber.java index 49afd23f91bf..2a935b067094 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -19,7 +19,9 @@ private 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) { @@ -37,7 +39,9 @@ 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); @@ -58,7 +62,9 @@ public static boolean isPerfectNumber2(int n) { // 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 (root == (int) root) { + sum -= root; + } return sum == n; } diff --git a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java index 8bc1afbe8771..5369182a0a94 100644 --- a/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java +++ b/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java @@ -12,7 +12,9 @@ public class SumWithoutArithmeticOperators { */ public int getSum(int a, int b) { - if (b == 0) return a; + 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/others/CRC16.java b/src/main/java/com/thealgorithms/others/CRC16.java index 85e5cd2c13ae..847ce8edab0a 100644 --- a/src/main/java/com/thealgorithms/others/CRC16.java +++ b/src/main/java/com/thealgorithms/others/CRC16.java @@ -21,7 +21,9 @@ public static String crc16(String message) { boolean bit = ((b >> (7 - i) & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1); crc <<= 1; - if (c15 ^ bit) crc ^= polynomial; + if (c15 ^ bit) { + crc ^= polynomial; + } } } crc &= 0xffff; diff --git a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java index 0bafc435aa75..5aa25812dcc2 100644 --- a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java +++ b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java @@ -24,7 +24,9 @@ private MaximumSumOfDistinctSubarraysWithLengthK() { * @return the maximum sum of distinct subarray of size K. */ public static long maximumSubarraySum(int k, int... nums) { - if (nums.length < k) return 0; + if (nums.length < k) { + return 0; + } long max = 0; // this will store the max sum which will be our result long s = 0; // this will store the sum of every k elements which can be used to compare with // max diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java index 991c9a4f6148..110c97416a42 100644 --- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java @@ -79,7 +79,9 @@ private void evaluateTurnAroundTime() { // If the current process has burst time remaining, push the process into the queue // again. - if (remainingBurstTime[index] > 0) queue.add(index); + 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()) { diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index 40b3cd0c20e3..53f5d7c8434e 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -29,47 +29,57 @@ static int[] binarySearch(int[][] arr, int target) { if (arr[midRow][midCol] == target) { return new int[] {midRow, midCol}; - } else if (arr[midRow][midCol] < target) + } else if (arr[midRow][midCol] < target) { startRow = midRow; - else + } 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 (arr[startRow][midCol] == target) + 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]) + if (target <= arr[endRow][midCol - 1]) { return binarySearch(arr, target, endRow, 0, midCol - 1); - else + } else { return binarySearch(arr, target, endRow, midCol + 1, colCount - 1); + } } 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) + if (arr[row][midIndex] == target) { return new int[] { row, midIndex, }; - else if (arr[row][midIndex] < target) + } else if (arr[row][midIndex] < target) { colStart = midIndex + 1; - else + } else { colEnd = midIndex - 1; + } } return new int[] {-1, -1}; diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java index 3648a4b08b86..8bf2754ff8f7 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -32,10 +32,11 @@ 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) + if (j != 0) { j = lps[j - 1]; - else + } else { i = i + 1; + } } } System.out.println("No pattern found"); diff --git a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java index cdd256150871..d85cb37c4427 100644 --- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java @@ -24,22 +24,23 @@ static int binSearchAlgo(int[] arr, int start, int end, int target) { 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 (arr[middle] == target) { + return middle; // returns the index of the middle element + } if (ascOrd) { - if (arr[middle] < target) + // Ascending order + if (arr[middle] < target) { start = middle + 1; - else + } else { end = middle - 1; - } - - // Descending order - else { - if (arr[middle] > target) + } + } else { + // Descending order + if (arr[middle] > target) { start = middle + 1; - else + } else { end = middle - 1; + } } } // Element is not present diff --git a/src/main/java/com/thealgorithms/searches/QuickSelect.java b/src/main/java/com/thealgorithms/searches/QuickSelect.java index 97eab4bb4046..c89abb00e9da 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -56,7 +56,9 @@ private static > int selectIndex(List list, int n) { private static > int selectIndex(List list, int left, int right, int n) { while (true) { - if (left == right) return left; + if (left == right) { + return left; + } int pivotIndex = pivot(list, left, right); pivotIndex = partition(list, left, right, pivotIndex, n); if (n == pivotIndex) { diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java index cc8387f6c4f3..81e16dbbbf07 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -18,7 +18,9 @@ public static int search(String pattern, String text, int primeNumber) { int h = 1; // The value of h would be "pow(d, patternLength-1)%primeNumber" - for (int i = 0; i < patternLength - 1; i++) h = (h * ALPHABET_SIZE) % primeNumber; + for (int i = 0; i < patternLength - 1; i++) { + h = (h * ALPHABET_SIZE) % primeNumber; + } // Calculate the hash value of pattern and first // window of text @@ -37,7 +39,9 @@ public static int search(String pattern, String text, int primeNumber) { if (hashForPattern == hashForText) { /* Check for characters one by one */ for (j = 0; j < patternLength; j++) { - if (text.charAt(i + j) != pattern.charAt(j)) break; + if (text.charAt(i + j) != pattern.charAt(j)) { + break; + } } // if hashForPattern == hashForText and pattern[0...patternLength-1] = text[i, i+1, ...i+patternLength-1] @@ -53,7 +57,9 @@ public static int search(String pattern, String text, int primeNumber) { hashForText = (ALPHABET_SIZE * (hashForText - text.charAt(i) * h) + text.charAt(i + patternLength)) % primeNumber; // handling negative hashForText - if (hashForText < 0) hashForText = (hashForText + primeNumber); + if (hashForText < 0) { + hashForText = (hashForText + primeNumber); + } } } return index; // return -1 if pattern does not found diff --git a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java index 6c6284e28019..daf0c12c0978 100644 --- a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java @@ -67,10 +67,11 @@ public static void main(String[] args) { RecursiveBinarySearch searcher = new RecursiveBinarySearch<>(); int res = searcher.find(a, t); - if (res == -1) + if (res == -1) { System.out.println("Element not found in the array."); - else + } else { System.out.println("Element found at index " + res); + } } } } diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java index 60cb5aa7aa69..5a6ba256521f 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -44,7 +44,9 @@ private static > void dualPivotQuicksort(T[] array, int * @param right The last index of an array Finds the partition index of an array */ private static > 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]; @@ -61,11 +63,15 @@ private static > 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++; diff --git a/src/main/java/com/thealgorithms/sorts/InsertionSort.java b/src/main/java/com/thealgorithms/sorts/InsertionSort.java index 3b8c286515bc..36aba615ba94 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -38,12 +38,17 @@ public > T[] sort(T[] array, int lo, int hi) { public > 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 (SortUtils.less(array[i], array[minElemIndex])) minElemIndex = i; + for (int i = 1; i < n; i++) { + if (SortUtils.less(array[i], array[minElemIndex])) { + minElemIndex = i; + } + } SortUtils.swap(array, 0, minElemIndex); for (int i = 2; i < n; i++) { diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java index fdbfe3130e41..c9000f7e3778 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -30,10 +30,11 @@ public static boolean isSorted(int[] p, int option) { // 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) + if (start == null) { start = fresh; - else + } else { prev.next = fresh; + } prev = fresh; } start = nm.sortByMergeSort(start); @@ -58,10 +59,11 @@ public static boolean isSorted(int[] p, int option) { // 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) + if (start1 == null) { start1 = fresh1; - else + } else { prev1.next = fresh1; + } prev1 = fresh1; } Task1 kk = new Task1(); @@ -87,10 +89,11 @@ public static boolean isSorted(int[] p, int option) { // 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) + if (start2 == null) { start2 = fresh2; - else + } else { prev2.next = fresh2; + } prev2 = fresh2; } start2 = mm.sortByHeapSort(start2); @@ -116,7 +119,9 @@ 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 @@ -147,7 +152,9 @@ class Task { private 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 @@ -193,10 +200,11 @@ void task1(int[] n, int s, int m, int e) { int j = m + 1; int[] b = new int[e - s + 1]; while (i <= m && j <= e) { - if (n[j] >= n[i]) + if (n[j] >= n[i]) { b[k++] = n[i++]; - else + } else { b[k++] = n[j++]; + } } // Smallest number is stored after checking from both the arrays while (i <= m) { @@ -215,7 +223,9 @@ 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 @@ -257,7 +267,9 @@ class Task2 { private 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 @@ -304,8 +316,12 @@ 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/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java index 9c0ab45b6a3c..42fd026b117b 100644 --- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -12,7 +12,9 @@ public class PigeonholeSort { void sort(Integer[] array) { int maxElement = array[0]; for (int element : array) { - if (element > maxElement) maxElement = element; + if (element > maxElement) { + maxElement = element; + } } int numOfPigeonholes = 1 + maxElement; diff --git a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java index b048d0245b64..ed2f538f4d89 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java @@ -22,7 +22,9 @@ private 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; } diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 7e2251d70640..51600812bbb1 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -9,7 +9,9 @@ private StrandSort() { // note: the input list is destroyed public static > LinkedList strandSort(LinkedList list) { - if (list.size() <= 1) return list; + if (list.size() <= 1) { + return list; + } LinkedList result = new LinkedList(); while (list.size() > 0) { @@ -31,10 +33,11 @@ private static > LinkedList merge(LinkedList< LinkedList result = new LinkedList(); 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) + if (left.peek().compareTo(right.peek()) <= 0) { result.add(left.remove()); - else + } else { result.add(right.remove()); + } } result.addAll(left); result.addAll(right); diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java index dd3a763bb197..e4ed240a9947 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -69,7 +69,9 @@ 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); + } } } diff --git a/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java b/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java index 4d37da0e7c31..6eae06ad7efc 100644 --- a/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java +++ b/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java @@ -51,7 +51,9 @@ public static int[] findNextSmallerElements(int[] array) { Arrays.fill(result, -1); for (int i = 0; i < array.length; i++) { - while (!stack.empty() && stack.peek() >= array[i]) stack.pop(); + while (!stack.empty() && stack.peek() >= array[i]) { + stack.pop(); + } if (stack.empty()) { result[i] = -1; } else { diff --git a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java index c69a511c2c17..118a3df381c9 100644 --- a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java @@ -35,11 +35,17 @@ public static boolean isOperator(char token) { public static boolean isValidPostfixExpression(String postfix) { /* Postfix expression length should NOT be less than 3 */ - if (postfix.length() < 3) return false; + if (postfix.length() < 3) { + return false; + } /* First two characters should NOT be operators */ - if (isOperator(postfix.charAt(0))) return false; - if (isOperator(postfix.charAt(1))) return false; + if (isOperator(postfix.charAt(0))) { + return false; + } + if (isOperator(postfix.charAt(1))) { + return false; + } int operandCount = 0; int operatorCount = 0; @@ -51,14 +57,18 @@ public static boolean isValidPostfixExpression(String postfix) { if (isOperator(token)) { operatorCount++; - if (operatorCount >= operandCount) return false; + if (operatorCount >= operandCount) { + return false; + } } else { if (operatorCount == 0) { operandCount++; continue; } - if (operandCount != operatorCount + 1) return false; + if (operandCount != operatorCount + 1) { + return false; + } /* Operand count is set to 2 because:- * @@ -80,7 +90,9 @@ public static boolean isValidPostfixExpression(String postfix) { public static String getPostfixToInfix(String postfix) { String infix = ""; - if (postfix.isEmpty()) return infix; + if (postfix.isEmpty()) { + return infix; + } /* Validate Postfix expression before proceeding with the Infix conversion */ if (!isValidPostfixExpression(postfix)) { diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java index 352d2308c5ea..106be5e1a596 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -96,7 +96,9 @@ boolean approach3(String s, String t) { b[t.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { - if (a[i] != b[i]) return false; + if (a[i] != b[i]) { + return false; + } } return true; } diff --git a/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java index 140e668fc841..cc99a16facc3 100644 --- a/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java @@ -16,20 +16,21 @@ public static int lengthOfLongestSubstring(String s) { char temp = s.charAt(i); // 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) + if (!map.containsKey(temp)) { + map.put(temp, 0); + } 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(); + } else if (s.charAt(i - 1) == temp) { + if (max < map.size()) { + max = map.size(); + } map = new HashMap<>(); start = i; i--; - } - // last possible place where dublicate value can be is between start and i - else { - if (max < map.size()) max = map.size(); + } else { + if (max < map.size()) { + max = map.size(); + } while (s.charAt(start) != temp) { map.remove(s.charAt(start)); start++; @@ -39,7 +40,9 @@ else if (s.charAt(i - 1) == temp) { i++; } - if (max < map.size()) max = map.size(); + if (max < map.size()) { + max = map.size(); + } return max; } } diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java index 0aed13f936a7..f58ab1acf8c5 100644 --- a/src/main/java/com/thealgorithms/strings/MyAtoi.java +++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java @@ -25,7 +25,9 @@ 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; diff --git a/src/main/java/com/thealgorithms/strings/Pangram.java b/src/main/java/com/thealgorithms/strings/Pangram.java index e0989ce86715..01307b28f6c6 100644 --- a/src/main/java/com/thealgorithms/strings/Pangram.java +++ b/src/main/java/com/thealgorithms/strings/Pangram.java @@ -29,8 +29,11 @@ public static void main(String[] args) { public static boolean isPangramUsingSet(String s) { HashSet alpha = new HashSet<>(); s = s.trim().toLowerCase(); - for (int i = 0; i < s.length(); i++) - if (s.charAt(i) != ' ') alpha.add(s.charAt(i)); + for (int i = 0; i < s.length(); i++) { + if (s.charAt(i) != ' ') { + alpha.add(s.charAt(i)); + } + } return alpha.size() == 26; } diff --git a/src/main/java/com/thealgorithms/strings/ValidParentheses.java b/src/main/java/com/thealgorithms/strings/ValidParentheses.java index 947a39da4bde..f4f3761b0495 100644 --- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java @@ -18,13 +18,19 @@ public static boolean isValid(String s) { stack[head++] = c; break; case '}': - if (head == 0 || stack[--head] != '{') return false; + if (head == 0 || stack[--head] != '{') { + return false; + } break; case ')': - if (head == 0 || stack[--head] != '(') return false; + if (head == 0 || stack[--head] != '(') { + return false; + } break; case ']': - if (head == 0 || stack[--head] != '[') return false; + if (head == 0 || stack[--head] != '[') { + return false; + } break; default: throw new IllegalArgumentException("Unexpected character: " + c); diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java index 3337f6eeff71..3f33fc17b9b0 100644 --- a/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java +++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java @@ -5,7 +5,9 @@ private ZigZagPattern() { } public static String encode(String s, int numRows) { - if (numRows < 2 || s.length() < numRows) return s; + if (numRows < 2 || s.length() < numRows) { + return s; + } int start = 0; int index = 0; int height = 1; @@ -18,11 +20,11 @@ public static String encode(String s, int numRows) { boolean bool = true; while (pointer < s.length()) { zigZagedArray[index++] = s.charAt(pointer); - if (heightSpace == 0) + if (heightSpace == 0) { pointer += depthSpace; - else if (depthSpace == 0) + } else if (depthSpace == 0) { pointer += heightSpace; - else if (bool) { + } else if (bool) { pointer += depthSpace; bool = false; } else { diff --git a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java index 9bc3b89ced9e..be98fde484fa 100644 --- a/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java +++ b/src/test/java/com/thealgorithms/datastructures/buffers/CircularBufferTest.java @@ -40,21 +40,29 @@ 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())); } @@ -74,7 +82,9 @@ void concurrentTest() throws InterruptedException { while (producerCountDownLatch.getCount() > 0) { int count = (int) producerCountDownLatch.getCount(); boolean put = buffer.put(count); - while (!put) put = buffer.put(count); + while (!put) { + put = buffer.put(count); + } producerCountDownLatch.countDown(); } }); @@ -85,7 +95,9 @@ void concurrentTest() throws InterruptedException { while (consumerCountDownLatch.getCount() > 0) { int count = (int) consumerCountDownLatch.getCount(); Integer item = buffer.get(); - while (item == null) item = buffer.get(); + while (item == null) { + item = buffer.get(); + } resultAtomicArray.set(count - 1, item); consumerCountDownLatch.countDown(); } @@ -111,7 +123,9 @@ private int generateInt() { private void shutDownExecutorSafely(ExecutorService executorService) { try { - if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) executorService.shutdownNow(); + if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) { + executorService.shutdownNow(); + } } catch (InterruptedException e) { executorService.shutdownNow(); } @@ -120,7 +134,9 @@ private void shutDownExecutorSafely(ExecutorService executorService) { public List getSortedListFrom(AtomicIntegerArray atomicArray) { int length = atomicArray.length(); ArrayList 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/queues/LinkedQueueTest.java b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java index faa0d0e952f9..7bebf13e9620 100644 --- a/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java @@ -8,7 +8,9 @@ class LinkedQueueTest { @Test public void testQue() { LinkedQueue queue = new LinkedQueue<>(); - for (int i = 1; i < 5; i++) queue.enqueue(i); + for (int i = 1; i < 5; i++) { + queue.enqueue(i); + } assertEquals(queue.peekRear(), 4); assertEquals(queue.peek(2), 2); @@ -20,7 +22,9 @@ public void testQue() { // iterates over all the elements present // as in the form of nodes queue.forEach(integer -> { - if (element[0]++ != integer) throw new AssertionError(); + if (element[0]++ != integer) { + throw new AssertionError(); + } }); } } diff --git a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java index e8294a323463..7daf8c6313cd 100644 --- a/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java +++ b/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java @@ -49,12 +49,13 @@ void updateAndGet() { 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 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/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java index baccf319d15e..891c3066058e 100644 --- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java +++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java @@ -54,7 +54,9 @@ public void testMixes() throws IOException { assertEquals(reader.read(), 'l'); // third letter assertEquals(reader.peek(1), 'o'); // fourth letter - for (int i = 0; i < 6; i++) reader.read(); + for (int i = 0; i < 6; i++) { + reader.read(); + } try { System.out.println((char) reader.peek(4)); } catch (Exception ignored) { diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java index 90910d511ca0..6307b8e19b5d 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -117,7 +117,9 @@ public void testWithLargeValues() { @Test public void testWithLargeCountOfValues() { var stream = new MedianOfRunningArrayInteger(); - for (int i = 1; i <= 1000; i++) stream.insert(i); + for (int i = 1; i <= 1000; i++) { + stream.insert(i); + } assertEquals(500, stream.median()); }