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="AvoidNestedBlocks"/> -->
<!-- TODO <module name="EmptyBlock"/> --> <!-- TODO <module name="EmptyBlock"/> -->
<!-- TODO <module name="LeftCurly"/> --> <!-- TODO <module name="LeftCurly"/> -->
<!-- TODO <module name="NeedBraces"/> --> <module name="NeedBraces"/>
<!-- TODO <module name="RightCurly"/> --> <!-- TODO <module name="RightCurly"/> -->
<!-- Checks for common coding problems --> <!-- Checks for common coding problems -->

View File

@ -43,7 +43,9 @@ public final class Combination {
* @param <T> the type of elements in the array. * @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) { 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()) { if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) { for (int i = index; i < arr.length; i++) {
currSet.add(arr[i]); currSet.add(arr[i]);

View File

@ -59,7 +59,9 @@ public final class MColoring {
// If number of colors used exceeds m, // If number of colors used exceeds m,
// return 0 // return 0
maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color)); 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, // If the adjacent node is not visited,
// mark it visited and push it in queue // mark it visited and push it in queue

View File

@ -51,7 +51,9 @@ public class WordSearch {
int yi = y + dy[i]; int yi = y + dy[i];
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) { if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
boolean exists = doDFS(xi, yi, nextIdx + 1); boolean exists = doDFS(xi, yi, nextIdx + 1);
if (exists) return true; if (exists) {
return true;
}
} }
} }
visited[x][y] = false; visited[x][y] = false;
@ -66,7 +68,9 @@ public class WordSearch {
if (board[i][j] == word.charAt(0)) { if (board[i][j] == word.charAt(0)) {
visited = new boolean[board.length][board[0].length]; visited = new boolean[board.length][board[0].length];
boolean exists = doDFS(i, j, 1); 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) { private String binToHex(String binary) {
long num = Long.parseUnsignedLong(binary, 2); long num = Long.parseUnsignedLong(binary, 2);
String hex = Long.toHexString(num); 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; return hex;
} }
@ -1120,7 +1122,9 @@ public class Blowfish {
a = hexToBin(a); a = hexToBin(a);
b = hexToBin(b); b = hexToBin(b);
String ans = ""; 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); ans = binToHex(ans);
return ans; return ans;
} }
@ -1202,7 +1206,9 @@ public class Blowfish {
// generating key // generating key
keyGenerate(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 // postprocessing
String right = plainText.substring(0, 8); String right = plainText.substring(0, 8);
@ -1224,7 +1230,9 @@ public class Blowfish {
// generating key // generating key
keyGenerate(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 // postprocessing
String right = cipherText.substring(0, 8); String right = cipherText.substring(0, 8);

View File

@ -31,7 +31,9 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
} }
public BitSet getNextKeyStream() { 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); BitSet result = new BitSet(KEY_STREAM_LENGTH);
for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) { for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {

View File

@ -19,7 +19,9 @@ public abstract class CompositeLFSR implements BaseLFSR {
boolean result = false; boolean result = false;
for (var register : registers) { for (var register : registers) {
result ^= register.getLastBit(); result ^= register.getLastBit();
if (register.getClockBit() == majorityBit) register.clock(); if (register.getClockBit() == majorityBit) {
register.clock();
}
} }
return result; return result;
} }

View File

@ -24,7 +24,9 @@ public class CircularBuffer<Item> {
} }
public Item get() { public Item get() {
if (isEmpty()) return null; if (isEmpty()) {
return null;
}
Item item = buffer[getPointer.getAndIncrement()]; Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet(); size.decrementAndGet();
@ -32,7 +34,9 @@ public class CircularBuffer<Item> {
} }
public boolean put(Item item) { public boolean put(Item item) {
if (isFull()) return false; if (isFull()) {
return false;
}
buffer[putPointer.getAndIncrement()] = item; buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet(); size.incrementAndGet();
@ -49,7 +53,9 @@ public class CircularBuffer<Item> {
} }
public int getAndIncrement() { public int getAndIncrement() {
if (pointer == max) pointer = 0; if (pointer == max) {
pointer = 0;
}
int tmp = pointer; int tmp = pointer;
pointer++; pointer++;
return tmp; return tmp;

View File

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

View File

@ -82,7 +82,9 @@ public class TarjansAlgorithm {
Stack<Integer> st = new Stack<Integer>(); Stack<Integer> st = new Stack<Integer>();
for (int i = 0; i < v; i++) { 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; return sccList;

View File

@ -68,10 +68,14 @@ public class HashMap {
public Node findKey(int key) { public Node findKey(int key) {
if (!isEmpty()) { if (!isEmpty()) {
Node temp = first; Node temp = first;
if (temp.getKey() == key) return temp; if (temp.getKey() == key) {
return temp;
}
while ((temp = temp.getNext()) != null) { while ((temp = temp.getNext()) != null) {
if (temp.getKey() == key) return temp; if (temp.getKey() == key) {
return temp;
}
} }
} }
return null; return null;

View File

@ -188,12 +188,14 @@ public class HashMapCuckooHashing {
throw new IllegalArgumentException("Table is empty"); 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); hash = hashFunction2(key);
if (!Objects.equals(buckets[hash], wrappedInt)) if (!Objects.equals(buckets[hash], wrappedInt)) {
throw new IllegalArgumentException("Key " + key + " not found in table"); throw new IllegalArgumentException("Key " + key + " not found in table");
else { } else {
return hash; return hash;
} }
} }

View File

@ -231,7 +231,9 @@ public class FibonacciHeap {
private void cascadingCuts(HeapNode curr) { private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion if (!curr.isMarked()) { // stop the recursion
curr.mark(); curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++; if (!curr.isRoot()) {
this.markedHeapNoodesCounter++;
}
} else { } else {
if (curr.isRoot()) { if (curr.isRoot()) {
return; return;

View File

@ -56,9 +56,13 @@ public class LeftistHeap {
// Function merge with two Nodes a and b // Function merge with two Nodes a and b
public Node merge(Node a, Node 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 // Violates leftist property, so must do a swap
if (a.element > b.element) { if (a.element > b.element) {
@ -93,7 +97,9 @@ public class LeftistHeap {
// Returns and removes the minimum element in the heap // Returns and removes the minimum element in the heap
public int extractMin() { public int extractMin() {
// If is empty return -1 // If is empty return -1
if (isEmpty()) return -1; if (isEmpty()) {
return -1;
}
int min = root.element; int min = root.element;
root = merge(root.left, root.right); root = merge(root.left, root.right);
@ -109,7 +115,9 @@ public class LeftistHeap {
// Auxiliary function for in_order // Auxiliary function for in_order
private void inOrderAux(Node n, ArrayList<Integer> lst) { private void inOrderAux(Node n, ArrayList<Integer> lst) {
if (n == null) return; if (n == null) {
return;
}
inOrderAux(n.left, lst); inOrderAux(n.left, lst);
lst.add(n.element); lst.add(n.element);
inOrderAux(n.right, lst); inOrderAux(n.right, lst);

View File

@ -98,11 +98,13 @@ public class MaxHeap implements Heap {
@Override @Override
public void deleteElement(int elementIndex) { 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"); throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) { } catch (EmptyHeapException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) { if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range"); throw new IndexOutOfBoundsException("Index out of heap range");
} }

View File

@ -92,11 +92,13 @@ public class MinHeap implements Heap {
@Override @Override
public void deleteElement(int elementIndex) { 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"); throw new EmptyHeapException("Attempt to delete an element from an empty heap");
} catch (EmptyHeapException e) { } catch (EmptyHeapException e) {
e.printStackTrace(); e.printStackTrace();
} }
}
if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) { if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index out of heap range"); throw new IndexOutOfBoundsException("Index out of heap range");
} }

View File

@ -23,8 +23,9 @@ public class CircularQueue {
public boolean isFull() { public boolean isFull() {
if (topOfQueue + 1 == beginningOfQueue) { if (topOfQueue + 1 == beginningOfQueue) {
return true; return true;
} else } else {
return topOfQueue == size - 1 && beginningOfQueue == 0; return topOfQueue == size - 1 && beginningOfQueue == 0;
}
} }
public void enQueue(int value) { public void enQueue(int value) {

View File

@ -125,9 +125,13 @@ public class LinkedQueue<T> implements Iterable<T> {
*/ */
public T peek(int pos) { 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; Node<T> node = front;
while (pos-- > 0) node = node.next; while (pos-- > 0) {
node = node.next;
}
return node.data; return node.data;
} }
@ -170,14 +174,18 @@ public class LinkedQueue<T> implements Iterable<T> {
* Clear all nodes in queue * Clear all nodes in queue
*/ */
public void clear() { public void clear() {
while (size > 0) dequeue(); while (size > 0) {
dequeue();
}
} }
@Override @Override
public String toString() { public String toString() {
StringJoiner join = new StringJoiner(", "); // separator of ', ' StringJoiner join = new StringJoiner(", "); // separator of ', '
Node<T> travel = front; 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() + ']'; return '[' + join.toString() + ']';
} }

View File

@ -87,9 +87,13 @@ class PriorityQueue {
while (2 * pos <= nItems) { while (2 * pos <= nItems) {
int current = 2 * pos; // Jump to the positon of child node int current = 2 * pos; // Jump to the positon of child node
// Compare both the children for the greater one // 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 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 // If not exchange the value of parent with child
int temp = queueArray[pos]; int temp = queueArray[pos];

View File

@ -60,9 +60,13 @@ public class AVLSimple {
node.height = Math.max(height(node.left), height(node.right)) + 1; node.height = Math.max(height(node.left), height(node.right)) + 1;
int bf = bf(node); int bf = bf(node);
// LL case // LL case
if (bf > 1 && item < node.left.data) return rightRotate(node); if (bf > 1 && item < node.left.data) {
return rightRotate(node);
}
// RR case // RR case
if (bf < -1 && item > node.right.data) return leftRotate(node); if (bf < -1 && item > node.right.data) {
return leftRotate(node);
}
// RL case // RL case
if (bf < -1 && item < node.right.data) { if (bf < -1 && item < node.right.data) {
node.right = rightRotate(node.right); node.right = rightRotate(node.right);
@ -84,18 +88,24 @@ public class AVLSimple {
private void display(Node node) { private void display(Node node) {
String str = ""; String str = "";
if (node.left != null) if (node.left != null) {
str += node.left.data + "=>"; str += node.left.data + "=>";
else } else {
str += "END=>"; str += "END=>";
}
str += node.data + ""; str += node.data + "";
if (node.right != null) if (node.right != null) {
str += "<=" + node.right.data; str += "<=" + node.right.data;
else } else {
str += "<=END"; str += "<=END";
}
System.out.println(str); System.out.println(str);
if (node.left != null) display(node.left); if (node.left != null) {
if (node.right != null) display(node.right); display(node.left);
}
if (node.right != null) {
display(node.right);
}
} }
private int height(Node node) { private int height(Node node) {
@ -106,7 +116,9 @@ public class AVLSimple {
} }
private int bf(Node node) { private int bf(Node node) {
if (node == null) return 0; if (node == null) {
return 0;
}
return height(node.left) - height(node.right); 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) { public static List<Integer> iterativeInorder(BinaryTree.Node root) {
List<Integer> result = new ArrayList<>(); List<Integer> result = new ArrayList<>();
if (root == null) return result; if (root == null) {
return result;
}
Deque<BinaryTree.Node> stack = new ArrayDeque<>(); Deque<BinaryTree.Node> stack = new ArrayDeque<>();
while (!stack.isEmpty() || root != null) { while (!stack.isEmpty() || root != null) {

View File

@ -34,10 +34,15 @@ public class KDTree {
* @param points Array of initial points * @param points Array of initial points
*/ */
KDTree(Point[] 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(); this.k = points[0].getDimension();
for (Point point : points) for (Point point : points) {
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension"); if (point.getDimension() != k) {
throw new IllegalArgumentException("Points must have the same dimension");
}
}
this.root = build(points, 0); this.root = build(points, 0);
} }
@ -48,11 +53,16 @@ public class KDTree {
* *
*/ */
KDTree(int[][] pointsCoordinates) { 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; this.k = pointsCoordinates[0].length;
Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new); Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
for (Point point : points) for (Point point : points) {
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension"); if (point.getDimension() != k) {
throw new IllegalArgumentException("Points must have the same dimension");
}
}
this.root = build(points, 0); this.root = build(points, 0);
} }
@ -119,7 +129,9 @@ public class KDTree {
public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
int distance = 0; int distance = 0;
for (int i = 0; i < p1.getDimension(); i++) { for (int i = 0; i < p1.getDimension(); i++) {
if (i == axis) continue; if (i == axis) {
continue;
}
int t = p1.getCoordinate(i) - p2.getCoordinate(i); int t = p1.getCoordinate(i) - p2.getCoordinate(i);
distance += t * t; distance += t * t;
} }
@ -164,10 +176,11 @@ public class KDTree {
* @return The nearest child Node * @return The nearest child Node
*/ */
public Node getNearChild(Point point) { public Node getNearChild(Point point) {
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return left; return left;
else } else {
return right; return right;
}
} }
/** /**
@ -178,10 +191,11 @@ public class KDTree {
* @return The farthest child Node * @return The farthest child Node
*/ */
public Node getFarChild(Point point) { public Node getFarChild(Point point) {
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return right; return right;
else } else {
return left; return left;
}
} }
/** /**
@ -207,9 +221,13 @@ public class KDTree {
* @return The root of the KDTree * @return The root of the KDTree
*/ */
private Node build(Point[] points, int depth) { private Node build(Point[] points, int depth) {
if (points.length == 0) return null; if (points.length == 0) {
return null;
}
int axis = depth % k; 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))); Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis)));
int median = points.length >> 1; int median = points.length >> 1;
Node node = new Node(points[median], axis); Node node = new Node(points[median], axis);
@ -225,7 +243,9 @@ public class KDTree {
* *
*/ */
public void insert(Point point) { 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); root = insert(root, point, 0);
} }
@ -240,11 +260,14 @@ public class KDTree {
*/ */
private Node insert(Node root, Point point, int depth) { private Node insert(Node root, Point point, int depth) {
int axis = depth % k; int axis = depth % k;
if (root == null) return new Node(point, axis); if (root == null) {
if (point.getCoordinate(axis) < root.getAxisCoordinate()) return new Node(point, axis);
}
if (point.getCoordinate(axis) < root.getAxisCoordinate()) {
root.left = insert(root.left, point, depth + 1); root.left = insert(root.left, point, depth + 1);
else } else {
root.right = insert(root.right, point, depth + 1); root.right = insert(root.right, point, depth + 1);
}
return root; return root;
} }
@ -257,7 +280,9 @@ public class KDTree {
* @return The Node corresponding to the specified point * @return The Node corresponding to the specified point
*/ */
public Optional<Node> search(Point 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); return search(root, point);
} }
@ -270,8 +295,12 @@ public class KDTree {
* @return The Node corresponding to the specified point * @return The Node corresponding to the specified point
*/ */
public Optional<Node> search(Node root, Point point) { public Optional<Node> search(Node root, Point point) {
if (root == null) return Optional.empty(); if (root == null) {
if (root.point.equals(point)) return Optional.of(root); return Optional.empty();
}
if (root.point.equals(point)) {
return Optional.of(root);
}
return search(root.getNearChild(point), point); 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 * @return The Node with minimum value in the specified axis of the point
*/ */
public Node findMin(Node root, int axis) { public Node findMin(Node root, int axis) {
if (root == null) return null; if (root == null) {
return null;
}
if (root.getAxis() == axis) { if (root.getAxis() == axis) {
if (root.left == null) return root; if (root.left == null) {
return root;
}
return findMin(root.left, axis); return findMin(root.left, axis);
} else { } else {
Node left = findMin(root.left, axis); 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 * @return The Node with maximum value in the specified axis of the point
*/ */
public Node findMax(Node root, int axis) { public Node findMax(Node root, int axis) {
if (root == null) return null; if (root == null) {
return null;
}
if (root.getAxis() == axis) { if (root.getAxis() == axis) {
if (root.right == null) return root; if (root.right == null) {
return root;
}
return findMax(root.right, axis); return findMax(root.right, axis);
} else { } else {
Node left = findMax(root.left, axis); Node left = findMax(root.left, axis);
@ -358,7 +395,9 @@ public class KDTree {
* @return The new root of the subtree * @return The new root of the subtree
*/ */
private Node delete(Node root, Node node) { private Node delete(Node root, Node node) {
if (root == null) return null; if (root == null) {
return null;
}
if (root.equals(node)) { if (root.equals(node)) {
if (root.right != null) { if (root.right != null) {
Node min = findMin(root.right, root.getAxis()); Node min = findMin(root.right, root.getAxis());
@ -368,13 +407,15 @@ public class KDTree {
Node min = findMin(root.left, root.getAxis()); Node min = findMin(root.left, root.getAxis());
root.point = min.point; root.point = min.point;
root.left = delete(root.left, min); root.left = delete(root.left, min);
} else } else {
return null; return null;
}
} }
if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) {
root.left = delete(root.left, node); root.left = delete(root.left, node);
else } else {
root.right = delete(root.right, node); root.right = delete(root.right, node);
}
return root; return root;
} }
@ -395,13 +436,21 @@ public class KDTree {
* @param nearest The nearest neighbor found so far. * @param nearest The nearest neighbor found so far.
* */ * */
private Node findNearest(Node root, Point point, Node nearest) { private Node findNearest(Node root, Point point, Node nearest) {
if (root == null) return nearest; if (root == null) {
if (root.point.equals(point)) return root; return nearest;
}
if (root.point.equals(point)) {
return root;
}
int distance = Point.comparableDistance(root.point, point); int distance = Point.comparableDistance(root.point, point);
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis()); int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
if (distance < Point.comparableDistance(nearest.point, point)) nearest = root; if (distance < Point.comparableDistance(nearest.point, point)) {
nearest = root;
}
nearest = findNearest(root.getNearChild(point), point, nearest); 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; return nearest;
} }
} }

View File

@ -40,11 +40,19 @@ public class LazySegmentTree {
* Shift the lazy value of this node to its children. * Shift the lazy value of this node to its children.
*/ */
public void shift() { public void shift() {
if (lazy == 0) return; if (lazy == 0) {
if (this.left == null && this.right == null) return; return;
}
if (this.left == null && this.right == null) {
return;
}
this.value += this.lazy; this.value += this.lazy;
if (this.left != null) this.left.applyUpdate(this.lazy); if (this.left != null) {
if (this.right != null) this.right.applyUpdate(this.lazy); this.left.applyUpdate(this.lazy);
}
if (this.right != null) {
this.right.applyUpdate(this.lazy);
}
this.lazy = 0; this.lazy = 0;
} }
@ -56,8 +64,12 @@ public class LazySegmentTree {
* @return The new Node. * @return The new Node.
*/ */
static Node merge(Node left, Node right) { static Node merge(Node left, Node right) {
if (left == null) return right; if (left == null) {
if (right == null) return left; return right;
}
if (right == null) {
return left;
}
Node result = new Node(left.start, right.end, left.value + right.value); Node result = new Node(left.start, right.end, left.value + right.value);
result.left = left; result.left = left;
result.right = right; result.right = right;
@ -97,7 +109,9 @@ public class LazySegmentTree {
* @return The root of the new LazySegmentTree. * @return The root of the new LazySegmentTree.
*/ */
private Node buildTree(int[] array, int start, int end) { 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; int mid = (start + end) >> 1;
Node left = buildTree(array, start, mid); Node left = buildTree(array, start, mid);
Node right = buildTree(array, mid, end); Node right = buildTree(array, mid, end);
@ -117,7 +131,9 @@ public class LazySegmentTree {
curr.applyUpdate(diff); curr.applyUpdate(diff);
return; return;
} }
if (left >= curr.end || right <= curr.start) return; if (left >= curr.end || right <= curr.start) {
return;
}
curr.shift(); curr.shift();
updateRange(left, right, diff, curr.left); updateRange(left, right, diff, curr.left);
updateRange(left, right, diff, curr.right); updateRange(left, right, diff, curr.right);
@ -133,8 +149,12 @@ public class LazySegmentTree {
* @return The Node representing the sum of the given range. * @return The Node representing the sum of the given range.
*/ */
private Node getRange(int left, int right, Node curr) { private Node getRange(int left, int right, Node curr) {
if (left <= curr.start && curr.end <= right) return curr; if (left <= curr.start && curr.end <= right) {
if (left >= curr.end || right <= curr.start) return null; return curr;
}
if (left >= curr.end || right <= curr.start) {
return null;
}
curr.shift(); curr.shift();
return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right)); return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right));
} }

View File

@ -36,15 +36,21 @@ public final class PreOrderTraversal {
public static List<Integer> iterativePreOrder(BinaryTree.Node root) { public static List<Integer> iterativePreOrder(BinaryTree.Node root) {
List<Integer> result = new ArrayList<>(); List<Integer> result = new ArrayList<>();
if (root == null) return result; if (root == null) {
return result;
}
Deque<BinaryTree.Node> stack = new LinkedList<>(); Deque<BinaryTree.Node> stack = new LinkedList<>();
stack.push(root); stack.push(root);
while (!stack.isEmpty()) { while (!stack.isEmpty()) {
BinaryTree.Node node = stack.pop(); BinaryTree.Node node = stack.pop();
result.add(node.data); result.add(node.data);
if (node.right != null) stack.push(node.right); if (node.right != null) {
if (node.left != null) stack.push(node.left); stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
} }
return result; return result;

View File

@ -52,16 +52,22 @@ public final class SameTreesCheck {
BinaryTree.Node second = q2.poll(); BinaryTree.Node second = q2.poll();
// check that some node can be null // check that some node can be null
// if the check is true: both nodes are null or both nodes are not 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 (first != null) {
if (!equalNodes(first.left, second.left)) return false; if (!equalNodes(first.left, second.left)) {
return false;
}
if (first.left != null) { if (first.left != null) {
q1.add(first.left); q1.add(first.left);
q2.add(second.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) { if (first.right != null) {
q1.add(first.right); q1.add(first.right);
q2.add(second.right); q2.add(second.right);

View File

@ -18,7 +18,9 @@ public final class KadaneAlgorithm {
// running sum of all the indexs are stored // running sum of all the indexs are stored
sum = Math.max(sum, runningSum); sum = Math.max(sum, runningSum);
// the max is stored inorder to the get the maximum sum // 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 // 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 // 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) { private int runningCost(int process, int machine) {
if (process == 0) // refers to the first process,which does not require for a previous one if (process == 0) { // refers to the first process,which does not require for a previous one
// to have been executed // to have been executed
return run[process][machine]; return run[process][machine];
else { } else {
int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on 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 for (int k = 0; k < numberMachines; k++) { // computes the cost of executing the previous
// process to each and every Machine // 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 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 return findMin(runningCosts); // returns the minimum running cost
} }
} }
@ -98,7 +98,9 @@ public class OptimalJobScheduling {
for (int i = 1; i < costArr.length; i++) { 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]; return costArr[min];
} }

View File

@ -29,12 +29,16 @@ public final class SubsetCount {
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
dp[i][0] = 1; 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 t = 1; t <= target; t++) {
for (int idx = 1; idx < n; idx++) { for (int idx = 1; idx < n; idx++) {
int notpick = dp[idx - 1][t]; int notpick = dp[idx - 1][t];
int pick = 0; 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; dp[idx][target] = pick + notpick;
} }
} }
@ -52,14 +56,18 @@ public final class SubsetCount {
int n = arr.length; int n = arr.length;
int[] prev = new int[target + 1]; int[] prev = new int[target + 1];
prev[0] = 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++) { for (int ind = 1; ind < n; ind++) {
int[] cur = new int[target + 1]; int[] cur = new int[target + 1];
cur[0] = 1; cur[0] = 1;
for (int t = 1; t <= target; t++) { for (int t = 1; t <= target; t++) {
int notTaken = prev[t]; int notTaken = prev[t];
int taken = 0; 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; cur[t] = notTaken + taken;
} }
prev = cur; prev = cur;

View File

@ -15,8 +15,12 @@ public final class Tribonacci {
* @return the n-th Tribonacci number * @return the n-th Tribonacci number
*/ */
public static int compute(int n) { public static int compute(int n) {
if (n == 0) return 0; if (n == 0) {
if (n == 1 || n == 2) return 1; return 0;
}
if (n == 1 || n == 2) {
return 1;
}
int first = 0; int first = 0;
int second = 1; 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 // find index of first point not equal to a[0] (indexPoint1) and the first point that's not
// collinear with either (indexPoint2). // collinear with either (indexPoint2).
int indexPoint1; int indexPoint1;
for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) for (indexPoint1 = 1; indexPoint1 < points.length; indexPoint1++) {
if (!points[0].equals(points[indexPoint1])) break; if (!points[0].equals(points[indexPoint1])) {
if (indexPoint1 == points.length) return; break;
}
}
if (indexPoint1 == points.length) {
return;
}
int indexPoint2; int indexPoint2;
for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) for (indexPoint2 = indexPoint1 + 1; indexPoint2 < points.length; indexPoint2++) {
if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) break; if (Point.orientation(points[0], points[indexPoint1], points[indexPoint2]) != 0) {
break;
}
}
hull.push(points[indexPoint2 - 1]); hull.push(points[indexPoint2 - 1]);
// Now we simply add the point to the stack based on the orientation. // Now we simply add the point to the stack based on the orientation.
@ -57,7 +65,9 @@ public class GrahamScan {
*/ */
public Iterable<Point> hull() { public Iterable<Point> hull() {
Stack<Point> s = new Stack<>(); Stack<Point> s = new Stack<>();
for (Point p : hull) s.push(p); for (Point p : hull) {
s.push(p);
}
return s; return s;
} }
@ -112,7 +122,9 @@ public class GrahamScan {
*/ */
public int compareTo(Point p2) { public int compareTo(Point p2) {
int res = Integer.compare(this.y, p2.y); 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; return res;
} }
@ -133,19 +145,21 @@ public class GrahamScan {
int dx2 = p2.x - x; int dx2 = p2.x - x;
int dy2 = p2.y - y; int dy2 = p2.y - y;
if (dy1 >= 0 && dy2 < 0) if (dy1 >= 0 && dy2 < 0) {
return -1; // q1 above; q2 below return -1; // q1 above; q2 below
else if (dy2 >= 0 && dy1 < 0) } else if (dy2 >= 0 && dy1 < 0) {
return +1; // q1 below; q2 above return +1; // q1 below; q2 above
else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal } else if (dy1 == 0 && dy2 == 0) { // 3-collinear and horizontal
if (dx1 >= 0 && dx2 < 0) if (dx1 >= 0 && dx2 < 0) {
return -1; return -1;
else if (dx2 >= 0 && dx1 < 0) } else if (dx2 >= 0 && dx1 < 0) {
return +1; return +1;
else } else {
return 0; return 0;
} else }
} else {
return -orientation(Point.this, p1, p2); // both above or below 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 { public BufferedReader(InputStream input, int bufferSize) throws IOException {
this.input = input; 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; this.bufferSize = bufferSize;
buffer = new byte[bufferSize]; buffer = new byte[bufferSize];
@ -55,7 +57,9 @@ public class BufferedReader {
*/ */
public int read() throws IOException { public int read() throws IOException {
if (needsRefill()) { if (needsRefill()) {
if (foundEof) return -1; if (foundEof) {
return -1;
}
// the buffer is empty, or the buffer has // the buffer is empty, or the buffer has
// been completely read and needs to be refilled // been completely read and needs to be refilled
refill(); refill();
@ -69,10 +73,11 @@ public class BufferedReader {
public int available() throws IOException { public int available() throws IOException {
int available = input.available(); int available = input.available();
if (needsRefill()) if (needsRefill()) {
// since the block is already empty, // since the block is already empty,
// we have no responsibility yet // we have no responsibility yet
return available; return available;
}
return bufferPos - posRead + available; return bufferPos - posRead + available;
} }
@ -90,10 +95,14 @@ public class BufferedReader {
public int peek(int n) throws IOException { public int peek(int n) throws IOException {
int available = available(); 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(); 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]; return buffer[n];
} }
@ -105,7 +114,9 @@ public class BufferedReader {
*/ */
private void pushRefreshData() throws IOException { private void pushRefreshData() throws IOException {
for (int i = posRead, j = 0; i < bufferSize; i++, j++) buffer[j] = buffer[i]; for (int i = posRead, j = 0; i < bufferSize; i++, j++) {
buffer[j] = buffer[i];
}
bufferPos -= posRead; bufferPos -= posRead;
posRead = 0; posRead = 0;
@ -127,11 +138,12 @@ public class BufferedReader {
byte[] cloned = new byte[bufferSize]; byte[] cloned = new byte[bufferSize];
// arraycopy() function is better than clone() // arraycopy() function is better than clone()
if (bufferPos >= 0) if (bufferPos >= 0) {
System.arraycopy(buffer, 0, cloned, 0, System.arraycopy(buffer, 0, cloned, 0,
// important to note that, bufferSize does not stay constant // important to note that, bufferSize does not stay constant
// once the class is defined. See justRefill() function // once the class is defined. See justRefill() function
bufferSize); bufferSize);
}
// we assume that already a chunk // we assume that already a chunk
// has been read // has been read
refill(); refill();
@ -168,7 +180,9 @@ public class BufferedReader {
} }
private void assertStreamOpen() { 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 { public void close() throws IOException {

View File

@ -34,7 +34,9 @@ public final class AliquotSum {
* @return aliquot sum of given {@code number} * @return aliquot sum of given {@code number}
*/ */
public static int getAliquotSum(int n) { public static int getAliquotSum(int n) {
if (n <= 0) return -1; if (n <= 0) {
return -1;
}
int sum = 1; int sum = 1;
double root = Math.sqrt(n); 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 // if n is a perfect square then its root was added twice in above loop, so subtracting root
// from sum // from sum
if (root == (int) root) sum -= root; if (root == (int) root) {
sum -= root;
}
return sum; return sum;
} }
} }

View File

@ -22,7 +22,9 @@ public final class AutomorphicNumber {
* {@code false} * {@code false}
*/ */
public static boolean isAutomorphic(long n) { 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 square = n * n; // Calculating square of the number
long t = n; long t = n;
long numberOfdigits = 0; long numberOfdigits = 0;
@ -42,7 +44,9 @@ public final class AutomorphicNumber {
* {@code false} * {@code false}
*/ */
public static boolean isAutomorphic2(long n) { 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 long square = n * n; // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n)); return String.valueOf(square).endsWith(String.valueOf(n));
} }
@ -56,7 +60,9 @@ public final class AutomorphicNumber {
*/ */
public static boolean isAutomorphic3(String s) { public static boolean isAutomorphic3(String s) {
BigInteger n = new BigInteger(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 BigInteger square = n.multiply(n); // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n)); return String.valueOf(square).endsWith(String.valueOf(n));
} }

View File

@ -14,7 +14,9 @@ public final class HarshadNumber {
* {@code false} * {@code false}
*/ */
public static boolean isHarshad(long n) { public static boolean isHarshad(long n) {
if (n <= 0) return false; if (n <= 0) {
return false;
}
long t = n; long t = n;
long sumOfDigits = 0; long sumOfDigits = 0;
@ -35,7 +37,9 @@ public final class HarshadNumber {
*/ */
public static boolean isHarshad(String s) { public static boolean isHarshad(String s) {
final Long n = Long.valueOf(s); final Long n = Long.valueOf(s);
if (n <= 0) return false; if (n <= 0) {
return false;
}
int sumOfDigits = 0; int sumOfDigits = 0;
for (char ch : s.toCharArray()) { for (char ch : s.toCharArray()) {

View File

@ -16,11 +16,15 @@ public final class KaprekarNumbers {
// Provides a list of kaprekarNumber in a range // Provides a list of kaprekarNumber in a range
public static List<Long> kaprekarNumberInRange(long start, long end) throws Exception { public static List<Long> kaprekarNumberInRange(long start, long end) throws Exception {
long n = end - start; 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<>(); ArrayList<Long> list = new ArrayList<>();
for (long i = start; i <= end; i++) { for (long i = start; i <= end; i++) {
if (isKaprekarNumber(i)) list.add(i); if (isKaprekarNumber(i)) {
list.add(i);
}
} }
return list; 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. 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; int s = 0;
long d = n - 1; long d = n - 1;
@ -31,13 +33,17 @@ public final class MillerRabinPrimalityCheck {
Random rnd = new Random(); Random rnd = new Random();
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
long a = 2 + rnd.nextLong(n) % (n - 3); 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; return true;
} }
public static boolean deterministicMillerRabin(long n) { // returns true if n is prime, else returns false. 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; int r = 0;
long d = n - 1; 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}) { for (int a : new int[] {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) {
if (n == a) return true; if (n == a) {
if (checkComposite(n, a, d, r)) return false; return true;
}
if (checkComposite(n, a, d, r)) {
return false;
}
} }
return true; return true;
} }
@ -66,10 +76,14 @@ public final class MillerRabinPrimalityCheck {
*/ */
private static boolean checkComposite(long n, long a, long d, int s) { private static boolean checkComposite(long n, long a, long d, int s) {
long x = powerModP(a, d, n); 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++) { for (int r = 1; r < s; r++) {
x = powerModP(x, 2, n); x = powerModP(x, 2, n);
if (x == n - 1) return false; if (x == n - 1) {
return false;
}
} }
return true; return true;
} }
@ -79,11 +93,14 @@ public final class MillerRabinPrimalityCheck {
x = x % p; // Update x if it is more than or equal to p x = x % p; // Update x if it is more than or equal to p
if (x == 0) return 0; // In case x is divisible by p; if (x == 0) {
return 0; // In case x is divisible by p;
}
while (y > 0) { while (y > 0) {
// If y is odd, multiply x with result // 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 must be even now
y = y >> 1; // y = y/2 y = y >> 1; // y = y/2

View File

@ -52,10 +52,11 @@ public final class PascalTriangle {
*/ */
for (int i = 0; i <= line; i++) { for (int i = 0; i <= line; i++) {
// First and last values in every row are 1 // First and last values in every row are 1
if (line == i || i == 0) arr[line][i] = 1; if (line == i || i == 0) {
// The rest elements are sum of values just above and left of above arr[line][i] = 1;
else } else {
arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; 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 * @return {@code true} if {@code number} is perfect number, otherwise false
*/ */
public static boolean isPerfectNumber(int number) { public static boolean isPerfectNumber(int number) {
if (number <= 0) return false; if (number <= 0) {
return false;
}
int sum = 0; int sum = 0;
/* sum of its positive divisors */ /* sum of its positive divisors */
for (int i = 1; i < number; ++i) { 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 * @return {@code true} if {@code number} is perfect number, otherwise false
*/ */
public static boolean isPerfectNumber2(int n) { public static boolean isPerfectNumber2(int n) {
if (n <= 0) return false; if (n <= 0) {
return false;
}
int sum = 1; int sum = 1;
double root = Math.sqrt(n); 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 // if n is a perfect square then its root was added twice in above loop, so subtracting root
// from sum // from sum
if (root == (int) root) sum -= root; if (root == (int) root) {
sum -= root;
}
return sum == n; return sum == n;
} }

View File

@ -12,7 +12,9 @@ public class SumWithoutArithmeticOperators {
*/ */
public int getSum(int a, int b) { public int getSum(int a, int b) {
if (b == 0) return a; if (b == 0) {
return a;
}
int sum = a ^ b; int sum = a ^ b;
int carry = (a & b) << 1; int carry = (a & b) << 1;
return getSum(sum, carry); return getSum(sum, carry);

View File

@ -21,7 +21,9 @@ public final class CRC16 {
boolean bit = ((b >> (7 - i) & 1) == 1); boolean bit = ((b >> (7 - i) & 1) == 1);
boolean c15 = ((crc >> 15 & 1) == 1); boolean c15 = ((crc >> 15 & 1) == 1);
crc <<= 1; crc <<= 1;
if (c15 ^ bit) crc ^= polynomial; if (c15 ^ bit) {
crc ^= polynomial;
}
} }
} }
crc &= 0xffff; crc &= 0xffff;

View File

@ -24,7 +24,9 @@ public final class MaximumSumOfDistinctSubarraysWithLengthK {
* @return the maximum sum of distinct subarray of size K. * @return the maximum sum of distinct subarray of size K.
*/ */
public static long maximumSubarraySum(int k, int... nums) { 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 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 long s = 0; // this will store the sum of every k elements which can be used to compare with
// max // max

View File

@ -79,7 +79,9 @@ public class RRScheduling {
// If the current process has burst time remaining, push the process into the queue // If the current process has burst time remaining, push the process into the queue
// again. // 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 the queue is empty, pick the first process from the list that is not completed.
if (queue.isEmpty()) { if (queue.isEmpty()) {

View File

@ -29,47 +29,57 @@ public final class BinarySearch2dArray {
if (arr[midRow][midCol] == target) { if (arr[midRow][midCol] == target) {
return new int[] {midRow, midCol}; return new int[] {midRow, midCol};
} else if (arr[midRow][midCol] < target) } else if (arr[midRow][midCol] < target) {
startRow = midRow; startRow = midRow;
else } else {
endRow = midRow; endRow = midRow;
}
} }
/* /*
if the above search fails to find the target element, these conditions will be used to 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 find the target element, which further uses the binary search algorithm in the places
which were left unexplored. which were left unexplored.
*/ */
if (arr[startRow][midCol] == target) if (arr[startRow][midCol] == target) {
return new int[] { return new int[] {
startRow, startRow,
midCol, 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); return binarySearch(arr, target, endRow, 0, midCol - 1);
else } else {
return binarySearch(arr, target, endRow, midCol + 1, colCount - 1); return binarySearch(arr, target, endRow, midCol + 1, colCount - 1);
}
} }
static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) { static int[] binarySearch(int[][] arr, int target, int row, int colStart, int colEnd) {
while (colStart <= colEnd) { while (colStart <= colEnd) {
int midIndex = colStart + (colEnd - colStart) / 2; int midIndex = colStart + (colEnd - colStart) / 2;
if (arr[row][midIndex] == target) if (arr[row][midIndex] == target) {
return new int[] { return new int[] {
row, row,
midIndex, midIndex,
}; };
else if (arr[row][midIndex] < target) } else if (arr[row][midIndex] < target) {
colStart = midIndex + 1; colStart = midIndex + 1;
else } else {
colEnd = midIndex - 1; colEnd = midIndex - 1;
}
} }
return new int[] {-1, -1}; return new int[] {-1, -1};

View File

@ -32,10 +32,11 @@ class KMPSearch {
else if (i < n && pat.charAt(j) != txt.charAt(i)) { else if (i < n && pat.charAt(j) != txt.charAt(i)) {
// Do not match lps[0..lps[j-1]] characters, // Do not match lps[0..lps[j-1]] characters,
// they will match anyway // they will match anyway
if (j != 0) if (j != 0) {
j = lps[j - 1]; j = lps[j - 1];
else } else {
i = i + 1; i = i + 1;
}
} }
} }
System.out.println("No pattern found"); System.out.println("No pattern found");

View File

@ -24,22 +24,23 @@ public final class OrderAgnosticBinarySearch {
int middle = start + (end - start) / 2; int middle = start + (end - start) / 2;
// Check if the desired element is present at the middle position // Check if the desired element is present at the middle position
if (arr[middle] == target) return middle; // returns the index of the middle element 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 (ascOrd) {
// Descending order // Ascending order
else { if (arr[middle] < target) {
if (arr[middle] > target)
start = middle + 1; start = middle + 1;
else } else {
end = middle - 1; end = middle - 1;
}
} else {
// Descending order
if (arr[middle] > target) {
start = middle + 1;
} else {
end = middle - 1;
}
} }
} }
// Element is not present // 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) { private static <T extends Comparable<T>> int selectIndex(List<T> list, int left, int right, int n) {
while (true) { while (true) {
if (left == right) return left; if (left == right) {
return left;
}
int pivotIndex = pivot(list, left, right); int pivotIndex = pivot(list, left, right);
pivotIndex = partition(list, left, right, pivotIndex, n); pivotIndex = partition(list, left, right, pivotIndex, n);
if (n == pivotIndex) { if (n == pivotIndex) {

View File

@ -18,7 +18,9 @@ public final class RabinKarpAlgorithm {
int h = 1; int h = 1;
// The value of h would be "pow(d, patternLength-1)%primeNumber" // 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 // Calculate the hash value of pattern and first
// window of text // window of text
@ -37,7 +39,9 @@ public final class RabinKarpAlgorithm {
if (hashForPattern == hashForText) { if (hashForPattern == hashForText) {
/* Check for characters one by one */ /* Check for characters one by one */
for (j = 0; j < patternLength; j++) { 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] // 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; hashForText = (ALPHABET_SIZE * (hashForText - text.charAt(i) * h) + text.charAt(i + patternLength)) % primeNumber;
// handling negative hashForText // handling negative hashForText
if (hashForText < 0) hashForText = (hashForText + primeNumber); if (hashForText < 0) {
hashForText = (hashForText + primeNumber);
}
} }
} }
return index; // return -1 if pattern does not found 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<>(); RecursiveBinarySearch<Integer> searcher = new RecursiveBinarySearch<>();
int res = searcher.find(a, t); int res = searcher.find(a, t);
if (res == -1) if (res == -1) {
System.out.println("Element not found in the array."); System.out.println("Element not found in the array.");
else } else {
System.out.println("Element found at index " + res); 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 * @param right The last index of an array Finds the partition index of an array
*/ */
private static <T extends Comparable<T>> int[] partition(T[] array, int left, int right) { private static <T extends Comparable<T>> int[] partition(T[] array, int left, int right) {
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 pivot1 = array[left];
T pivot2 = array[right]; T pivot2 = array[right];
@ -61,11 +63,15 @@ public class DualPivotQuickSort implements SortAlgorithm {
// If element is greater or equal to pivot2 // If element is greater or equal to pivot2
else if (array[less].compareTo(pivot2) >= 0) { 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--); 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++; less++;

View File

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

View File

@ -30,10 +30,11 @@ public class LinkListSort {
// New nodes are created and values are added // New nodes are created and values are added
fresh = new Node(); // Node class is called fresh = new Node(); // Node class is called
fresh.val = a[i]; // Node val is stored fresh.val = a[i]; // Node val is stored
if (start == null) if (start == null) {
start = fresh; start = fresh;
else } else {
prev.next = fresh; prev.next = fresh;
}
prev = fresh; prev = fresh;
} }
start = nm.sortByMergeSort(start); start = nm.sortByMergeSort(start);
@ -58,10 +59,11 @@ public class LinkListSort {
// New nodes are created and values are added // New nodes are created and values are added
fresh1 = new Node(); // New node is created fresh1 = new Node(); // New node is created
fresh1.val = a[i1]; // Value is stored in the value part of the node fresh1.val = a[i1]; // Value is stored in the value part of the node
if (start1 == null) if (start1 == null) {
start1 = fresh1; start1 = fresh1;
else } else {
prev1.next = fresh1; prev1.next = fresh1;
}
prev1 = fresh1; prev1 = fresh1;
} }
Task1 kk = new Task1(); Task1 kk = new Task1();
@ -87,10 +89,11 @@ public class LinkListSort {
// New nodes are created and values are added // New nodes are created and values are added
fresh2 = new Node(); // Node class is created fresh2 = new Node(); // Node class is created
fresh2.val = a[i2]; // Value is stored in the value part of the Node fresh2.val = a[i2]; // Value is stored in the value part of the Node
if (start2 == null) if (start2 == null) {
start2 = fresh2; start2 = fresh2;
else } else {
prev2.next = fresh2; prev2.next = fresh2;
}
prev2 = fresh2; prev2 = fresh2;
} }
start2 = mm.sortByHeapSort(start2); start2 = mm.sortByHeapSort(start2);
@ -116,7 +119,9 @@ public class LinkListSort {
boolean compare(int[] a, int[] b) { boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false; if (a[i] != b[i]) {
return false;
}
} }
return true; return true;
// Both the arrays are checked for equalness. If both are equal then true is // Both the arrays are checked for equalness. If both are equal then true is
@ -147,7 +152,9 @@ class Task {
private int[] a; private int[] a;
public Node sortByMergeSort(Node head) { 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); int c = count(head);
a = new int[c]; a = new int[c];
// Array of size c is created // Array of size c is created
@ -193,10 +200,11 @@ class Task {
int j = m + 1; int j = m + 1;
int[] b = new int[e - s + 1]; int[] b = new int[e - s + 1];
while (i <= m && j <= e) { while (i <= m && j <= e) {
if (n[j] >= n[i]) if (n[j] >= n[i]) {
b[k++] = n[i++]; b[k++] = n[i++];
else } else {
b[k++] = n[j++]; b[k++] = n[j++];
}
} }
// Smallest number is stored after checking from both the arrays // Smallest number is stored after checking from both the arrays
while (i <= m) { while (i <= m) {
@ -215,7 +223,9 @@ class Task {
class Task1 { class Task1 {
public Node sortByInsertionSort(Node head) { 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 c = count(head);
int[] a = new int[c]; int[] a = new int[c];
// Array of size c is created // Array of size c is created
@ -257,7 +267,9 @@ class Task2 {
private int[] a; private int[] a;
public Node sortByHeapSort(Node head) { 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); int c = count(head);
a = new int[c]; a = new int[c];
// Array of size c is created // Array of size c is created
@ -304,8 +316,12 @@ class Task2 {
int p = i; int p = i;
int l = 2 * i + 1; int l = 2 * i + 1;
int r = 2 * i + 2; int r = 2 * i + 2;
if (l < k && n[l] > n[p]) p = l; if (l < k && n[l] > n[p]) {
if (r < k && n[r] > n[p]) p = r; p = l;
}
if (r < k && n[r] > n[p]) {
p = r;
}
if (p != i) { if (p != i) {
int d = n[p]; int d = n[p];
n[p] = n[i]; n[p] = n[i];

View File

@ -12,7 +12,9 @@ public class PigeonholeSort {
void sort(Integer[] array) { void sort(Integer[] array) {
int maxElement = array[0]; int maxElement = array[0];
for (int element : array) { for (int element : array) {
if (element > maxElement) maxElement = element; if (element > maxElement) {
maxElement = element;
}
} }
int numOfPigeonholes = 1 + maxElement; int numOfPigeonholes = 1 + maxElement;

View File

@ -22,7 +22,9 @@ public final class SortUtilsRandomGenerator {
*/ */
public static Double[] generateArray(int size) { public static Double[] generateArray(int size) {
Double[] arr = new Double[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; return arr;
} }

View File

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

View File

@ -69,7 +69,9 @@ public final class TopologicalSort {
* */ * */
public void addEdge(String label, String... next) { public void addEdge(String label, String... next) {
adj.put(label, new Vertex(label)); 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); Arrays.fill(result, -1);
for (int i = 0; i < array.length; i++) { 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()) { if (stack.empty()) {
result[i] = -1; result[i] = -1;
} else { } else {

View File

@ -35,11 +35,17 @@ public final class PostfixToInfix {
public static boolean isValidPostfixExpression(String postfix) { public static boolean isValidPostfixExpression(String postfix) {
/* Postfix expression length should NOT be less than 3 */ /* 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 */ /* First two characters should NOT be operators */
if (isOperator(postfix.charAt(0))) return false; if (isOperator(postfix.charAt(0))) {
if (isOperator(postfix.charAt(1))) return false; return false;
}
if (isOperator(postfix.charAt(1))) {
return false;
}
int operandCount = 0; int operandCount = 0;
int operatorCount = 0; int operatorCount = 0;
@ -51,14 +57,18 @@ public final class PostfixToInfix {
if (isOperator(token)) { if (isOperator(token)) {
operatorCount++; operatorCount++;
if (operatorCount >= operandCount) return false; if (operatorCount >= operandCount) {
return false;
}
} else { } else {
if (operatorCount == 0) { if (operatorCount == 0) {
operandCount++; operandCount++;
continue; continue;
} }
if (operandCount != operatorCount + 1) return false; if (operandCount != operatorCount + 1) {
return false;
}
/* Operand count is set to 2 because:- /* Operand count is set to 2 because:-
* *
@ -80,7 +90,9 @@ public final class PostfixToInfix {
public static String getPostfixToInfix(String postfix) { public static String getPostfixToInfix(String postfix) {
String infix = ""; String infix = "";
if (postfix.isEmpty()) return infix; if (postfix.isEmpty()) {
return infix;
}
/* Validate Postfix expression before proceeding with the Infix conversion */ /* Validate Postfix expression before proceeding with the Infix conversion */
if (!isValidPostfixExpression(postfix)) { if (!isValidPostfixExpression(postfix)) {

View File

@ -96,7 +96,9 @@ public class Anagrams {
b[t.charAt(i) - 'a']++; b[t.charAt(i) - 'a']++;
} }
for (int i = 0; i < 26; i++) { for (int i = 0; i < 26; i++) {
if (a[i] != b[i]) return false; if (a[i] != b[i]) {
return false;
}
} }
return true; return true;
} }

View File

@ -16,20 +16,21 @@ final class LongestNonRepeativeSubstring {
char temp = s.charAt(i); char temp = s.charAt(i);
// adding key to map if not present // adding key to map if not present
if (!map.containsKey(temp)) map.put(temp, 0); if (!map.containsKey(temp)) {
// checking if the first value is the dublicate value map.put(temp, 0);
else if (s.charAt(start) == temp) } else if (s.charAt(start) == temp) {
start++; start++;
// checking if the previous value is dublicate value } else if (s.charAt(i - 1) == temp) {
else if (s.charAt(i - 1) == temp) { if (max < map.size()) {
if (max < map.size()) max = map.size(); max = map.size();
}
map = new HashMap<>(); map = new HashMap<>();
start = i; start = i;
i--; i--;
} } else {
// last possible place where dublicate value can be is between start and i if (max < map.size()) {
else { max = map.size();
if (max < map.size()) max = map.size(); }
while (s.charAt(start) != temp) { while (s.charAt(start) != temp) {
map.remove(s.charAt(start)); map.remove(s.charAt(start));
start++; start++;
@ -39,7 +40,9 @@ final class LongestNonRepeativeSubstring {
i++; i++;
} }
if (max < map.size()) max = map.size(); if (max < map.size()) {
max = map.size();
}
return max; return max;
} }
} }

View File

@ -25,7 +25,9 @@ public final class MyAtoi {
number = "0"; number = "0";
break; break;
} }
if (ch >= '0' && ch <= '9') number += ch; if (ch >= '0' && ch <= '9') {
number += ch;
}
} else if (ch == '-' && !isDigit) { } else if (ch == '-' && !isDigit) {
number += "0"; number += "0";
negative = true; negative = true;

View File

@ -29,8 +29,11 @@ public final class Pangram {
public static boolean isPangramUsingSet(String s) { public static boolean isPangramUsingSet(String s) {
HashSet<Character> alpha = new HashSet<>(); HashSet<Character> alpha = new HashSet<>();
s = s.trim().toLowerCase(); s = s.trim().toLowerCase();
for (int i = 0; i < s.length(); i++) for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ') alpha.add(s.charAt(i)); if (s.charAt(i) != ' ') {
alpha.add(s.charAt(i));
}
}
return alpha.size() == 26; return alpha.size() == 26;
} }

View File

@ -18,13 +18,19 @@ public final class ValidParentheses {
stack[head++] = c; stack[head++] = c;
break; break;
case '}': case '}':
if (head == 0 || stack[--head] != '{') return false; if (head == 0 || stack[--head] != '{') {
return false;
}
break; break;
case ')': case ')':
if (head == 0 || stack[--head] != '(') return false; if (head == 0 || stack[--head] != '(') {
return false;
}
break; break;
case ']': case ']':
if (head == 0 || stack[--head] != '[') return false; if (head == 0 || stack[--head] != '[') {
return false;
}
break; break;
default: default:
throw new IllegalArgumentException("Unexpected character: " + c); throw new IllegalArgumentException("Unexpected character: " + c);

View File

@ -5,7 +5,9 @@ final class ZigZagPattern {
} }
public static String encode(String s, int numRows) { 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 start = 0;
int index = 0; int index = 0;
int height = 1; int height = 1;
@ -18,11 +20,11 @@ final class ZigZagPattern {
boolean bool = true; boolean bool = true;
while (pointer < s.length()) { while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer); zigZagedArray[index++] = s.charAt(pointer);
if (heightSpace == 0) if (heightSpace == 0) {
pointer += depthSpace; pointer += depthSpace;
else if (depthSpace == 0) } else if (depthSpace == 0) {
pointer += heightSpace; pointer += heightSpace;
else if (bool) { } else if (bool) {
pointer += depthSpace; pointer += depthSpace;
bool = false; bool = false;
} else { } else {

View File

@ -40,21 +40,29 @@ class CircularBufferTest {
buffer.put(generateInt()); buffer.put(generateInt());
assertFalse(buffer.isFull()); 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()); assertTrue(buffer.isFull());
} }
@Test @Test
void get() { void get() {
assertNull(buffer.get()); assertNull(buffer.get());
for (int i = 0; i < 100; i++) buffer.put(i); for (int i = 0; i < 100; i++) {
for (int i = 0; i < BUFFER_SIZE; i++) assertEquals(i, buffer.get()); buffer.put(i);
}
for (int i = 0; i < BUFFER_SIZE; i++) {
assertEquals(i, buffer.get());
}
assertNull(buffer.get()); assertNull(buffer.get());
} }
@Test @Test
void put() { 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())); assertFalse(buffer.put(generateInt()));
} }
@ -74,7 +82,9 @@ class CircularBufferTest {
while (producerCountDownLatch.getCount() > 0) { while (producerCountDownLatch.getCount() > 0) {
int count = (int) producerCountDownLatch.getCount(); int count = (int) producerCountDownLatch.getCount();
boolean put = buffer.put(count); boolean put = buffer.put(count);
while (!put) put = buffer.put(count); while (!put) {
put = buffer.put(count);
}
producerCountDownLatch.countDown(); producerCountDownLatch.countDown();
} }
}); });
@ -85,7 +95,9 @@ class CircularBufferTest {
while (consumerCountDownLatch.getCount() > 0) { while (consumerCountDownLatch.getCount() > 0) {
int count = (int) consumerCountDownLatch.getCount(); int count = (int) consumerCountDownLatch.getCount();
Integer item = buffer.get(); Integer item = buffer.get();
while (item == null) item = buffer.get(); while (item == null) {
item = buffer.get();
}
resultAtomicArray.set(count - 1, item); resultAtomicArray.set(count - 1, item);
consumerCountDownLatch.countDown(); consumerCountDownLatch.countDown();
} }
@ -111,7 +123,9 @@ class CircularBufferTest {
private void shutDownExecutorSafely(ExecutorService executorService) { private void shutDownExecutorSafely(ExecutorService executorService) {
try { try {
if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) executorService.shutdownNow(); if (!executorService.awaitTermination(1_000, TimeUnit.MILLISECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException e) { } catch (InterruptedException e) {
executorService.shutdownNow(); executorService.shutdownNow();
} }
@ -120,7 +134,9 @@ class CircularBufferTest {
public List<Integer> getSortedListFrom(AtomicIntegerArray atomicArray) { public List<Integer> getSortedListFrom(AtomicIntegerArray atomicArray) {
int length = atomicArray.length(); int length = atomicArray.length();
ArrayList<Integer> result = new ArrayList<>(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)); result.sort(Comparator.comparingInt(o -> o));
return result; return result;
} }

View File

@ -8,7 +8,9 @@ class LinkedQueueTest {
@Test @Test
public void testQue() { public void testQue() {
LinkedQueue<Integer> queue = new LinkedQueue<>(); 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.peekRear(), 4);
assertEquals(queue.peek(2), 2); assertEquals(queue.peek(2), 2);
@ -20,7 +22,9 @@ class LinkedQueueTest {
// iterates over all the elements present // iterates over all the elements present
// as in the form of nodes // as in the form of nodes
queue.forEach(integer -> { 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}; int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
LazySegmentTree lazySegmentTree = new LazySegmentTree(arr); 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++) { for (int j = i + 1; j < 10; j++) {
lazySegmentTree.updateRange(i, j, 1); lazySegmentTree.updateRange(i, j, 1);
assertEquals(j - i, lazySegmentTree.getRange(i, j)); assertEquals(j - i, lazySegmentTree.getRange(i, j));
lazySegmentTree.updateRange(i, j, -1); lazySegmentTree.updateRange(i, j, -1);
assertEquals(0, lazySegmentTree.getRange(i, j)); assertEquals(0, lazySegmentTree.getRange(i, j));
} }
}
} }
} }

View File

@ -54,7 +54,9 @@ class BufferedReaderTest {
assertEquals(reader.read(), 'l'); // third letter assertEquals(reader.read(), 'l'); // third letter
assertEquals(reader.peek(1), 'o'); // fourth 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 { try {
System.out.println((char) reader.peek(4)); System.out.println((char) reader.peek(4));
} catch (Exception ignored) { } catch (Exception ignored) {

View File

@ -117,7 +117,9 @@ public class MedianOfRunningArrayTest {
@Test @Test
public void testWithLargeCountOfValues() { public void testWithLargeCountOfValues() {
var stream = new MedianOfRunningArrayInteger(); 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()); assertEquals(500, stream.median());
} }