style: enable NeedBraces in checkstyle (#5227)

* enable style NeedBraces

* style: enable NeedBraces in checkstyle

---------

Co-authored-by: Samuel Facchinello <samuel.facchinello@piksel.com>
This commit is contained in:
Samuel Facchinello 2024-06-13 21:00:16 +02:00 committed by GitHub
parent 51fcc66345
commit 87b17e0571
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
68 changed files with 629 additions and 261 deletions

View File

@ -155,7 +155,7 @@
<!-- TODO <module name="AvoidNestedBlocks"/> -->
<!-- TODO <module name="EmptyBlock"/> -->
<!-- TODO <module name="LeftCurly"/> -->
<!-- TODO <module name="NeedBraces"/> -->
<module name="NeedBraces"/>
<!-- TODO <module name="RightCurly"/> -->
<!-- Checks for common coding problems -->

View File

@ -43,7 +43,9 @@ public final class Combination {
* @param <T> the type of elements in the array.
*/
private static <T> void backtracking(T[] arr, int index, TreeSet<T> currSet, List<TreeSet<T>> result) {
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]);

View File

@ -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

View File

@ -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;
}
}
}
}

View File

@ -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);

View File

@ -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) {

View File

@ -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;
}

View File

@ -24,7 +24,9 @@ public class CircularBuffer<Item> {
}
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<Item> {
}
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<Item> {
}
public int getAndIncrement() {
if (pointer == max) pointer = 0;
if (pointer == max) {
pointer = 0;
}
int tmp = pointer;
pointer++;
return tmp;

View File

@ -127,7 +127,9 @@ public class Kosaraju {
private void dfs(int node, int[] vis, List<List<Integer>> list) {
vis[node] = 1;
for (Integer neighbour : list.get(node)) {
if (vis[neighbour] == 0) dfs(neighbour, vis, list);
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<Integer>> 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);
}

View File

@ -82,7 +82,9 @@ public class TarjansAlgorithm {
Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < v; i++) {
if (insertionTime[i] == -1) stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
if (insertionTime[i] == -1) {
stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph);
}
}
return sccList;

View File

@ -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;

View File

@ -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;
}
}

View File

@ -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;

View File

@ -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<Integer> lst) {
if (n == null) return;
if (n == null) {
return;
}
inOrderAux(n.left, lst);
lst.add(n.element);
inOrderAux(n.right, lst);

View File

@ -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");
}

View File

@ -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");
}

View File

@ -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) {

View File

@ -125,9 +125,13 @@ public class LinkedQueue<T> implements Iterable<T> {
*/
public T peek(int pos) {
if (pos > size) throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
if (pos > size) {
throw new IndexOutOfBoundsException("Position %s out of range!".formatted(pos));
}
Node<T> node = front;
while (pos-- > 0) node = node.next;
while (pos-- > 0) {
node = node.next;
}
return node.data;
}
@ -170,14 +174,18 @@ public class LinkedQueue<T> implements Iterable<T> {
* Clear all nodes in queue
*/
public void clear() {
while (size > 0) dequeue();
while (size > 0) {
dequeue();
}
}
@Override
public String toString() {
StringJoiner join = new StringJoiner(", "); // separator of ', '
Node<T> travel = front;
while ((travel = travel.next) != null) join.add(String.valueOf(travel.data));
while ((travel = travel.next) != null) {
join.add(String.valueOf(travel.data));
}
return '[' + join.toString() + ']';
}

View File

@ -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];

View File

@ -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);
}

View File

@ -36,7 +36,9 @@ public final class InorderTraversal {
public static List<Integer> iterativeInorder(BinaryTree.Node root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
if (root == null) {
return result;
}
Deque<BinaryTree.Node> stack = new ArrayDeque<>();
while (!stack.isEmpty() || root != null) {

View File

@ -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<Node> search(Point point) {
if (point.getDimension() != k) throw new IllegalArgumentException("Point has wrong dimension");
if (point.getDimension() != k) {
throw new IllegalArgumentException("Point has wrong dimension");
}
return search(root, point);
}
@ -270,8 +295,12 @@ public class KDTree {
* @return The Node corresponding to the specified point
*/
public Optional<Node> 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;
}
}

View File

@ -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));
}

View File

@ -36,15 +36,21 @@ public final class PreOrderTraversal {
public static List<Integer> iterativePreOrder(BinaryTree.Node root) {
List<Integer> result = new ArrayList<>();
if (root == null) return result;
if (root == null) {
return result;
}
Deque<BinaryTree.Node> 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;

View File

@ -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);

View File

@ -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

View File

@ -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];
}

View File

@ -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;

View File

@ -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;

View File

@ -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<Point> hull() {
Stack<Point> 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
}
}
}

View File

@ -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 {

View File

@ -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;
}
}

View File

@ -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));
}

View File

@ -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()) {

View File

@ -16,11 +16,15 @@ public final class KaprekarNumbers {
// Provides a list of kaprekarNumber in a range
public static List<Long> 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<Long> list = new ArrayList<>();
for (long i = start; i <= end; i++) {
if (isKaprekarNumber(i)) list.add(i);
if (isKaprekarNumber(i)) {
list.add(i);
}
}
return list;

View File

@ -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

View File

@ -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];
}
}
}

View File

@ -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;
}

View File

@ -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);

View File

@ -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;

View File

@ -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

View File

@ -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()) {

View File

@ -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};

View File

@ -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");

View File

@ -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

View File

@ -56,7 +56,9 @@ public final class QuickSelect {
private static <T extends Comparable<T>> int selectIndex(List<T> 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) {

View File

@ -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

View File

@ -67,10 +67,11 @@ public class RecursiveBinarySearch<T extends Comparable<T>> extends SearchAlgori
RecursiveBinarySearch<Integer> 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);
}
}
}
}

View File

@ -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 <T extends Comparable<T>> int[] partition(T[] array, int left, int right) {
if (array[left].compareTo(array[right]) > 0) swap(array, left, right);
if (array[left].compareTo(array[right]) > 0) {
swap(array, left, right);
}
T pivot1 = array[left];
T pivot2 = array[right];
@ -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++;

View File

@ -38,12 +38,17 @@ class InsertionSort implements SortAlgorithm {
public <T extends Comparable<T>> T[] sentinelSort(T[] array) {
int minElemIndex = 0;
int n = array.length;
if (n < 1) return array;
if (n < 1) {
return array;
}
// put the smallest element to the 0 position as a sentinel, which will allow us to avoid
// redundant comparisons like `j > 0` further
for (int i = 1; i < n; i++)
if (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++) {

View File

@ -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];

View File

@ -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;

View File

@ -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;
}

View File

@ -9,7 +9,9 @@ public final class StrandSort {
// note: the input list is destroyed
public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list) {
if (list.size() <= 1) return list;
if (list.size() <= 1) {
return list;
}
LinkedList<E> result = new LinkedList<E>();
while (list.size() > 0) {
@ -31,10 +33,11 @@ public final class StrandSort {
LinkedList<E> result = new LinkedList<E>();
while (!left.isEmpty() && !right.isEmpty()) {
// change the direction of this comparison to change the direction of the sort
if (left.peek().compareTo(right.peek()) <= 0)
if (left.peek().compareTo(right.peek()) <= 0) {
result.add(left.remove());
else
} else {
result.add(right.remove());
}
}
result.addAll(left);
result.addAll(right);

View File

@ -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);
}
}
}

View File

@ -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 {

View File

@ -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)) {

View File

@ -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;
}

View File

@ -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;
}
}

View File

@ -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;

View File

@ -29,8 +29,11 @@ public final class Pangram {
public static boolean isPangramUsingSet(String s) {
HashSet<Character> 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;
}

View File

@ -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);

View File

@ -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 {

View File

@ -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<Integer> getSortedListFrom(AtomicIntegerArray atomicArray) {
int length = atomicArray.length();
ArrayList<Integer> result = new ArrayList<>(length);
for (int i = 0; i < length; i++) result.add(atomicArray.get(i));
for (int i = 0; i < length; i++) {
result.add(atomicArray.get(i));
}
result.sort(Comparator.comparingInt(o -> o));
return result;
}

View File

@ -8,7 +8,9 @@ class LinkedQueueTest {
@Test
public void testQue() {
LinkedQueue<Integer> 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();
}
});
}
}

View File

@ -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));
}
}
}
}

View File

@ -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) {

View File

@ -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());
}