From 87b17e05714d011fee82b35f11833bf12ec175cb Mon Sep 17 00:00:00 2001 From: Samuel Facchinello <4256795+samuelfac@users.noreply.github.com> Date: Thu, 13 Jun 2024 21:00:16 +0200 Subject: [PATCH] style: enable `NeedBraces` in checkstyle (#5227) * enable style NeedBraces * style: enable NeedBraces in checkstyle --------- Co-authored-by: Samuel Facchinello --- checkstyle.xml | 2 +- .../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 | 27 +++-- .../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 +- 68 files changed, 629 insertions(+), 261 deletions(-) diff --git a/checkstyle.xml b/checkstyle.xml index b65291b8f..48c8a4f1f 100644 --- a/checkstyle.xml +++ b/checkstyle.xml @@ -155,7 +155,7 @@ - + diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java index 80c11ce73..bf2a672a0 100644 --- a/src/main/java/com/thealgorithms/backtracking/Combination.java +++ b/src/main/java/com/thealgorithms/backtracking/Combination.java @@ -43,7 +43,9 @@ public final class Combination { * @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 20c42e59e..f069e46cc 100644 --- a/src/main/java/com/thealgorithms/backtracking/MColoring.java +++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java @@ -59,7 +59,9 @@ public final class MColoring { // 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 4ab81bfd7..f3a5b0433 100644 --- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java +++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java @@ -51,7 +51,9 @@ public class WordSearch { 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 class WordSearch { 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 a8fa6fc56..f6a0a3753 100644 --- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java +++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java @@ -1104,7 +1104,9 @@ public class Blowfish { 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 @@ public class Blowfish { a = hexToBin(a); b = hexToBin(b); String ans = ""; - for (int i = 0; i < a.length(); i++) ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); + for (int i = 0; i < a.length(); i++) { + ans += (char) (((a.charAt(i) - '0') ^ (b.charAt(i) - '0')) + '0'); + } ans = binToHex(ans); return ans; } @@ -1202,7 +1206,9 @@ public class Blowfish { // 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 @@ public class Blowfish { // 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 2e9249805..0b17a685b 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 class A5KeyStreamGenerator extends CompositeLFSR { } 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 3cac55823..f96946c39 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 abstract class CompositeLFSR implements BaseLFSR { 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 63295b83a..15e9a0956 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 class CircularBuffer { } public Item get() { - if (isEmpty()) return null; + if (isEmpty()) { + return null; + } Item item = buffer[getPointer.getAndIncrement()]; size.decrementAndGet(); @@ -32,7 +34,9 @@ public class CircularBuffer { } public boolean put(Item item) { - if (isFull()) return false; + if (isFull()) { + return false; + } buffer[putPointer.getAndIncrement()] = item; size.incrementAndGet(); @@ -49,7 +53,9 @@ public class CircularBuffer { } 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 c24046f51..7c0c0b2be 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 class Kosaraju { 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 @@ public class Kosaraju { 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 987e73a2a..336e375f7 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 class TarjansAlgorithm { Stack st = new Stack(); for (int i = 0; i < v; i++) { - if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph); + if (insertionTime[i] == -1) { + stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph); + } } return sccList; 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 ad273deaf..e0b394b12 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 @@ public class HashMap { 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 b48502b51..a67968d7e 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 class HashMapCuckooHashing { 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 4aa7db195..4734483b5 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 @@ public class FibonacciHeap { 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 59cb9dfab..ca18673c6 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 class LeftistHeap { // 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 class LeftistHeap { // 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 class LeftistHeap { // 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 9a584da04..067aae738 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 class MaxHeap implements Heap { @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 f7ff0ec5a..6e972205a 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 class MinHeap implements Heap { @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 cd3761bdc..48d9ffe9a 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 class CircularQueue { 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 171f24e09..5fba2ff6a 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 class LinkedQueue implements Iterable { */ public T peek(int pos) { - if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); + if (pos > size) { + throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos)); + } Node node = front; - while (pos-- > 0) node = node.next; + while (pos-- > 0) { + node = node.next; + } return node.data; } @@ -170,14 +174,18 @@ public class LinkedQueue implements Iterable { * 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 16a0c1673..a5ca48670 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 @@ class PriorityQueue { 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 052da616f..e0309122c 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 @@ public class AVLSimple { 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 class AVLSimple { 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 @@ public class AVLSimple { } 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 3bae17ed1..5a001ff9a 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 final class InorderTraversal { 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 e5528c392..5190e82f7 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 class KDTree { 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 class KDTree { * @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 class KDTree { * @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 class KDTree { * @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 @@ public class KDTree { * */ public void insert(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension"); + if (point.getDimension() != k) { + throw new IllegalArgumentException("Point has wrong dimension"); + } root = insert(root, point, 0); } @@ -240,11 +260,14 @@ public class KDTree { */ 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 @@ public class KDTree { * @return The Node corresponding to the specified point */ public Optional search(Point point) { - if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension"); + if (point.getDimension() != k) { + throw new IllegalArgumentException("Point has wrong dimension"); + } return search(root, point); } @@ -270,8 +295,12 @@ public class KDTree { * @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 class KDTree { * @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 class KDTree { * @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 class KDTree { * @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 @@ public class KDTree { 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 class KDTree { * @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 1d8febff4..e7a8e23d6 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 class LazySegmentTree { * 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 class LazySegmentTree { * @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 class LazySegmentTree { * @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 @@ public class LazySegmentTree { 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 @@ public class LazySegmentTree { * @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 6a0eef369..3aceac4d1 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 final class PreOrderTraversal { 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 883eadd18..cff27c12f 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 final class SameTreesCheck { 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 de7512604..9962cca21 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java @@ -18,7 +18,9 @@ public final class KadaneAlgorithm { // 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 0840e08c5..e31bb7309 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java @@ -69,19 +69,19 @@ public class OptimalJobScheduling { */ 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 @@ public class OptimalJobScheduling { 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 af31294f7..cbe3ccae4 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java @@ -29,12 +29,16 @@ public final class SubsetCount { 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 final class SubsetCount { 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 407566f48..3ff6cc620 100644 --- a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java +++ b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java @@ -15,8 +15,12 @@ public final class 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 4f4aebaed..2773d03b4 100644 --- a/src/main/java/com/thealgorithms/geometry/GrahamScan.java +++ b/src/main/java/com/thealgorithms/geometry/GrahamScan.java @@ -32,13 +32,21 @@ public class GrahamScan { // 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 class GrahamScan { */ 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 class GrahamScan { */ 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 class GrahamScan { 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 fa0237a48..66673fe28 100644 --- a/src/main/java/com/thealgorithms/io/BufferedReader.java +++ b/src/main/java/com/thealgorithms/io/BufferedReader.java @@ -44,7 +44,9 @@ public class BufferedReader { public BufferedReader(InputStream input, int bufferSize) throws IOException { this.input = input; - if (input.available() == -1) throw new IOException("Empty or already closed stream provided"); + if (input.available() == -1) { + throw new IOException("Empty or already closed stream provided"); + } this.bufferSize = bufferSize; buffer = new byte[bufferSize]; @@ -55,7 +57,9 @@ public class BufferedReader { */ 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 class BufferedReader { 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 class BufferedReader { public int peek(int n) throws IOException { int available = available(); - if (n >= available) throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n)); + if (n >= available) { + throw new IOException("Out of range, available %d, but trying with %d".formatted(available, n)); + } pushRefreshData(); - if (n >= bufferSize) throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + if (n >= bufferSize) { + throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)".formatted(n, bufferSize)); + } return buffer[n]; } @@ -105,7 +114,9 @@ public class BufferedReader { */ 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 class BufferedReader { 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 @@ public class BufferedReader { } 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 5a5555777..0dbc58bed 100644 --- a/src/main/java/com/thealgorithms/maths/AliquotSum.java +++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java @@ -34,7 +34,9 @@ public final class AliquotSum { * @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 final class AliquotSum { } // 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 560ce3aab..03c8a8989 100644 --- a/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java +++ b/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java @@ -22,7 +22,9 @@ public final 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; long numberOfdigits = 0; @@ -42,7 +44,9 @@ public final class AutomorphicNumber { * {@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 final class AutomorphicNumber { */ 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 0b1ba1285..5792e925a 100644 --- a/src/main/java/com/thealgorithms/maths/HarshadNumber.java +++ b/src/main/java/com/thealgorithms/maths/HarshadNumber.java @@ -14,7 +14,9 @@ public final class 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 final class HarshadNumber { */ 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 f025f8668..eb9750f9c 100644 --- a/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java +++ b/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java @@ -16,11 +16,15 @@ public final class 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 e25836f71..f889213ab 100644 --- a/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java +++ b/src/main/java/com/thealgorithms/maths/MillerRabinPrimalityCheck.java @@ -20,7 +20,9 @@ public final class 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 final class MillerRabinPrimalityCheck { 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 final class MillerRabinPrimalityCheck { } 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 final class MillerRabinPrimalityCheck { */ 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 @@ public final class MillerRabinPrimalityCheck { 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 ef6aa41d6..95f92fbe1 100644 --- a/src/main/java/com/thealgorithms/maths/PascalTriangle.java +++ b/src/main/java/com/thealgorithms/maths/PascalTriangle.java @@ -52,10 +52,11 @@ public final class PascalTriangle { */ 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 49afd23f9..2a935b067 100644 --- a/src/main/java/com/thealgorithms/maths/PerfectNumber.java +++ b/src/main/java/com/thealgorithms/maths/PerfectNumber.java @@ -19,7 +19,9 @@ public final 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) { @@ -37,7 +39,9 @@ public final class PerfectNumber { * @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 final class PerfectNumber { // 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 8bc1afbe8..5369182a0 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 85e5cd2c1..847ce8eda 100644 --- a/src/main/java/com/thealgorithms/others/CRC16.java +++ b/src/main/java/com/thealgorithms/others/CRC16.java @@ -21,7 +21,9 @@ public final class CRC16 { 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 0bafc435a..5aa25812d 100644 --- a/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java +++ b/src/main/java/com/thealgorithms/others/MaximumSumOfDistinctSubarraysWithLengthK.java @@ -24,7 +24,9 @@ public final class 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 991c9a4f6..110c97416 100644 --- a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java +++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java @@ -79,7 +79,9 @@ public class RRScheduling { // 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 40b3cd0c2..53f5d7c84 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -29,47 +29,57 @@ public final class BinarySearch2dArray { 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 3648a4b08..8bf2754ff 100644 --- a/src/main/java/com/thealgorithms/searches/KMPSearch.java +++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java @@ -32,10 +32,11 @@ class KMPSearch { 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 cdd256150..d85cb37c4 100644 --- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java @@ -24,22 +24,23 @@ public final class OrderAgnosticBinarySearch { 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; + if (arr[middle] == target) { + return middle; // returns the index of the middle element } - - // Descending order - else { - if (arr[middle] > target) + if (ascOrd) { + // Ascending order + if (arr[middle] < target) { start = middle + 1; - else + } else { end = middle - 1; + } + } else { + // Descending order + if (arr[middle] > target) { + start = middle + 1; + } 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 97eab4bb4..c89abb00e 100644 --- a/src/main/java/com/thealgorithms/searches/QuickSelect.java +++ b/src/main/java/com/thealgorithms/searches/QuickSelect.java @@ -56,7 +56,9 @@ public final class QuickSelect { 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 cc8387f6c..81e16dbbb 100644 --- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java +++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java @@ -18,7 +18,9 @@ public final class RabinKarpAlgorithm { 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 final class RabinKarpAlgorithm { 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 final class RabinKarpAlgorithm { 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 6c6284e28..daf0c12c0 100644 --- a/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RecursiveBinarySearch.java @@ -67,10 +67,11 @@ public class RecursiveBinarySearch> extends SearchAlgori 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 60cb5aa7a..5a6ba2565 100644 --- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java +++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java @@ -44,7 +44,9 @@ public class DualPivotQuickSort implements SortAlgorithm { * @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 @@ public class DualPivotQuickSort implements SortAlgorithm { // 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 3b8c28651..36aba615b 100644 --- a/src/main/java/com/thealgorithms/sorts/InsertionSort.java +++ b/src/main/java/com/thealgorithms/sorts/InsertionSort.java @@ -38,12 +38,17 @@ class InsertionSort implements SortAlgorithm { 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 fdbfe3130..c9000f7e3 100644 --- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java +++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java @@ -30,10 +30,11 @@ public class LinkListSort { // 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 class LinkListSort { // 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 class LinkListSort { // 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 class LinkListSort { 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 @@ class Task { 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 @@ class Task { 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 @@ class Task2 { 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 9c0ab45b6..42fd026b1 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 b048d0245..ed2f538f4 100644 --- a/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java +++ b/src/main/java/com/thealgorithms/sorts/SortUtilsRandomGenerator.java @@ -22,7 +22,9 @@ public final 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; } diff --git a/src/main/java/com/thealgorithms/sorts/StrandSort.java b/src/main/java/com/thealgorithms/sorts/StrandSort.java index 7e2251d70..51600812b 100644 --- a/src/main/java/com/thealgorithms/sorts/StrandSort.java +++ b/src/main/java/com/thealgorithms/sorts/StrandSort.java @@ -9,7 +9,9 @@ public final class 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 @@ public final class StrandSort { 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 dd3a763bb..e4ed240a9 100644 --- a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java +++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java @@ -69,7 +69,9 @@ public final class TopologicalSort { * */ 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 4d37da0e7..6eae06ad7 100644 --- a/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java +++ b/src/main/java/com/thealgorithms/stacks/NextSmallerElement.java @@ -51,7 +51,9 @@ public final class NextSmallerElement { 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 c69a511c2..118a3df38 100644 --- a/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java +++ b/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java @@ -35,11 +35,17 @@ public final class PostfixToInfix { 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 final class PostfixToInfix { 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 final class PostfixToInfix { 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 352d2308c..106be5e1a 100644 --- a/src/main/java/com/thealgorithms/strings/Anagrams.java +++ b/src/main/java/com/thealgorithms/strings/Anagrams.java @@ -96,7 +96,9 @@ public class Anagrams { 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 140e668fc..cc99a16fa 100644 --- a/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java +++ b/src/main/java/com/thealgorithms/strings/LongestNonRepeativeSubstring.java @@ -16,20 +16,21 @@ final class LongestNonRepeativeSubstring { 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 @@ final class LongestNonRepeativeSubstring { 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 0aed13f93..f58ab1acf 100644 --- a/src/main/java/com/thealgorithms/strings/MyAtoi.java +++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java @@ -25,7 +25,9 @@ public final class MyAtoi { 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 e0989ce86..01307b28f 100644 --- a/src/main/java/com/thealgorithms/strings/Pangram.java +++ b/src/main/java/com/thealgorithms/strings/Pangram.java @@ -29,8 +29,11 @@ public final class Pangram { 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 947a39da4..f4f3761b0 100644 --- a/src/main/java/com/thealgorithms/strings/ValidParentheses.java +++ b/src/main/java/com/thealgorithms/strings/ValidParentheses.java @@ -18,13 +18,19 @@ public final class ValidParentheses { 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 3337f6eef..3f33fc17b 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 @@ final class 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 @@ final class ZigZagPattern { 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 9bc3b89ce..be98fde48 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 @@ class CircularBufferTest { 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 @@ class CircularBufferTest { 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 @@ class CircularBufferTest { 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 @@ class CircularBufferTest { private void shutDownExecutorSafely(ExecutorService executorService) { try { - if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) executorService.shutdownNow(); + if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) { + executorService.shutdownNow(); + } } catch (InterruptedException e) { executorService.shutdownNow(); } @@ -120,7 +134,9 @@ class CircularBufferTest { 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 faa0d0e95..7bebf13e9 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 @@ class LinkedQueueTest { // 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 e8294a323..7daf8c631 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 @@ public class LazySegmentTreeTest { 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 baccf319d..891c30660 100644 --- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java +++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java @@ -54,7 +54,9 @@ class BufferedReaderTest { 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 90910d511..6307b8e19 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -117,7 +117,9 @@ public class MedianOfRunningArrayTest { @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()); }