Add automatic linter (#4214)

This commit is contained in:
acbin
2023-06-09 20:05:14 +08:00
committed by GitHub
parent 00282efd8b
commit 415a04ea7f
188 changed files with 661 additions and 1133 deletions

View File

@ -27,10 +27,8 @@ public class A_Star {
// Graph is bidirectional, for just one direction remove second instruction of this method.
private void addEdge(Edge edge) {
this.graph.get(edge.getFrom())
.add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
this.graph.get(edge.getTo())
.add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight()));
this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight()));
}
}
@ -64,8 +62,7 @@ public class A_Star {
private int distance; // distance advanced so far.
private ArrayList<Integer> path; // list of visited nodes in this path.
private int
estimated; // heuristic value associated to the last node od the path (current node).
private int estimated; // heuristic value associated to the last node od the path (current node).
public PathAndDistance(int distance, ArrayList<Integer> path, int estimated) {
this.distance = distance;
@ -153,12 +150,8 @@ public class A_Star {
};
Graph graph = new Graph(20);
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140,
null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10,
70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6,
115, null, 15, 14, 80, null, 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1,
101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18,
142, null, 18, 8, 92, null, 8, 11, 87));
ArrayList<Integer> graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140, null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10, 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6, 115, null, 15, 14, 80, null,
15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1, 101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18, 142, null, 18, 8, 92, null, 8, 11, 87));
initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic);
@ -169,8 +162,7 @@ public class A_Star {
// nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value
// given by the heuristic function to reach the destination point from the current point.
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(
Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
@ -179,19 +171,16 @@ public class A_Star {
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring.
int currentPosition
= currentData.getPath().get(currentData.getPath().size() - 1); // current node.
int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) {
solutionFound = true;
} else {
for (Edge edge : graph.getNeighbours(currentPosition)) {
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath());
updatedPath.add(
edge.getTo()); // Add the new node to the path, update the distance,
updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path.
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(),
updatedPath, heuristic[edge.getTo()]));
queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), updatedPath, heuristic[edge.getTo()]));
}
}
}

View File

@ -77,8 +77,7 @@ number between 0 and total number of vertices-1,both inclusive*/
p[0] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if (dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@ -128,8 +127,7 @@ number between 0 and total number of vertices-1,both inclusive*/
p[source] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@ -137,8 +135,7 @@ number between 0 and total number of vertices-1,both inclusive*/
}
// Final cycle for negative checking
for (j = 0; j < e; j++) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE
&& dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;

View File

@ -16,8 +16,7 @@ import java.util.Arrays;
*/
public class BipartiteGrapfDFS {
private static boolean bipartite(
int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
private static boolean bipartite(int V, ArrayList<ArrayList<Integer>> adj, int[] color, int node) {
if (color[node] == -1) {
color[node] = 1;
}

View File

@ -45,8 +45,7 @@ class dijkstras {
Set[u] = true;
for (int v = 0; v < k; v++) {
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][v] < dist[v]) {
if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}

View File

@ -9,15 +9,13 @@ public class FloydWarshall {
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
DistanceMatrix = new int[numberofvertices + 1][numberofvertices
+ 1]; // stores the value of distance from all the possible path form the source
DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex
// The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices;
}
public void floydwarshall(
int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
@ -26,15 +24,11 @@ public class FloydWarshall {
for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) {
for (int destination = 1; destination <= numberofvertices; destination++) {
if (DistanceMatrix[source][intermediate]
+ DistanceMatrix[intermediate][destination]
< DistanceMatrix[source]
[destination]) { // calculated distance it get replaced as
// new shortest distance // if the new
// distance calculated is less then the
// earlier shortest
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
+ DistanceMatrix[intermediate][destination];
if (DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination] < DistanceMatrix[source][destination]) { // calculated distance it get replaced as
// new shortest distance // if the new
// distance calculated is less then the
// earlier shortest
DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate] + DistanceMatrix[intermediate][destination];
}
}
}

View File

@ -1,7 +1,9 @@
package com.thealgorithms.datastructures.graphs;
/**
* Java program for Hamiltonian Cycle (https://en.wikipedia.org/wiki/Hamiltonian_path)
* Java program for Hamiltonian Cycle
* (https://en.wikipedia.org/wiki/Hamiltonian_path)
*
* @author Akshay Dubey (https://github.com/itsAkshayDubey)
*/
public class HamiltonianCycle {
@ -12,10 +14,11 @@ public class HamiltonianCycle {
/**
* Find hamiltonian cycle for given graph G(V,E)
*
* @param graph Adjacency matrix of a graph G(V, E)
* for which hamiltonian path is to be found
* for which hamiltonian path is to be found
* @return Array containing hamiltonian cycle
* else returns 1D array with value -1.
* else returns 1D array with value -1.
*/
public int[] findHamiltonianCycle(int[][] graph) {
this.V = graph.length;
@ -44,12 +47,12 @@ public class HamiltonianCycle {
/**
* function to find paths recursively
* Find paths recursively from given vertex
*
* @param vertex Vertex from which path is to be found
* @returns true if path is found false otherwise
*/
public boolean isPathFound(int vertex) {
boolean isLastVertexConnectedToStart
= this.graph[vertex][0] == 1 && this.pathCount == this.V;
boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
if (isLastVertexConnectedToStart) {
return true;
}
@ -69,7 +72,7 @@ public class HamiltonianCycle {
this.graph[vertex][v] = 0;
this.graph[v][vertex] = 0;
/** if vertex not already selected solve recursively **/
/** if vertex not already selected solve recursively **/
if (!isPresent(v)) {
return isPathFound(v);
}
@ -88,6 +91,7 @@ public class HamiltonianCycle {
/**
* function to check if path is already selected
* Check if path is already selected
*
* @param vertex Starting vertex
*/
public boolean isPresent(int vertex) {

View File

@ -74,8 +74,7 @@ public class Kruskal {
// captain of i, stores the set with all the connected nodes to i
HashSet<Integer>[] connectedGroups = new HashSet[nodes];
HashSet<Edge>[] minGraph = new HashSet[nodes];
PriorityQueue<Edge> edges
= new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
PriorityQueue<Edge> edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight)));
for (int i = 0; i < nodes; i++) {
minGraph[i] = new HashSet<>();
connectedGroups[i] = new HashSet<>();
@ -88,8 +87,7 @@ public class Kruskal {
while (connectedElements != nodes && !edges.isEmpty()) {
Edge edge = edges.poll();
// This if avoids cycles
if (!connectedGroups[captain[edge.from]].contains(edge.to)
&& !connectedGroups[captain[edge.to]].contains(edge.from)) {
if (!connectedGroups[captain[edge.from]].contains(edge.to) && !connectedGroups[captain[edge.to]].contains(edge.from)) {
// merge sets of the captains of each point connected by the edge
connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]);
// update captains of the elements merged

View File

@ -258,9 +258,8 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for this vertex
int[] adjacent = _adjacency[currentVertex];
for (int i = 0; i < adjacent.length;
i++) { // we are considering exploring, recurse on it // If an edge exists between the
// currentVertex and the vertex
for (int i = 0; i < adjacent.length; i++) { // we are considering exploring, recurse on it // If an edge exists between the
// currentVertex and the vertex
if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) {
depthFirstOrder(i, visited, orderList);
}
@ -309,9 +308,8 @@ class AdjacencyMatrixGraph {
// Get the adjacency array for the currentVertex and
// check each node
int[] adjacent = _adjacency[currentVertex];
for (int vertex = 0; vertex < adjacent.length;
vertex++) { // vertex we are considering exploring, we add it to the queue // If an
// edge exists between the current vertex and the
for (int vertex = 0; vertex < adjacent.length; vertex++) { // vertex we are considering exploring, we add it to the queue // If an
// edge exists between the current vertex and the
if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) {
queue.add(vertex);
}

View File

@ -70,10 +70,9 @@ class PrimMST {
// Update key value and parent index of the adjacent
// vertices of the picked vertex. Consider only those
// vertices which are not yet included in MST
for (int v = 0; v < V;
v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is
// false for vertices not yet included in MST // graph[u][v] is non zero only
// for adjacent vertices of m
for (int v = 0; v < V; v++) // Update the key only if graph[u][v] is smaller than key[v] // mstSet[v] is
// false for vertices not yet included in MST // graph[u][v] is non zero only
// for adjacent vertices of m
{
if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;

View File

@ -83,15 +83,13 @@ 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;
}
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) {
// Initialize insertion time and lowTime value of current node
insertionTime[u] = Time;

View File

@ -204,8 +204,7 @@ public class HashMapCuckooHashing {
* @return int the index where the key is located
*/
public boolean checkTableContainsKey(int key) {
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key))
|| (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)] == key));
}
/**

View File

@ -143,8 +143,7 @@ public class FibonacciHeap {
if (this.empty()) {
return new int[0]; /// return an empty array
}
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO))
+ 1]; // creates the array
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
rankArray[this.min.rank]++;
HeapNode curr = this.min.next;
while (curr != this.min) {
@ -284,8 +283,7 @@ public class FibonacciHeap {
*
*/
private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets
= new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null;
HeapNode tmpCurr;
while (curr != null) {

View File

@ -122,8 +122,7 @@ public class HeapElement {
return false;
}
HeapElement otherHeapElement = (HeapElement) o;
return ((this.key == otherHeapElement.key)
&& (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
return ((this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)));
}
return false;
}

View File

@ -70,20 +70,17 @@ public class MaxHeap implements Heap {
// than any of its children's
private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key < getElementKey(elementIndex * 2))
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
wrongOrder = (key < getElementKey(elementIndex * 2))
|| (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size())));
}
}
@ -116,10 +113,7 @@ public class MaxHeap implements Heap {
if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} // ... or down ?
else if (((2 * elementIndex <= maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < maxHeap.size())
&& (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex);
}
}

View File

@ -64,20 +64,17 @@ public class MinHeap implements Heap {
// than any of its children's
private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (key > getElementKey(elementIndex * 2))
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
boolean wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
while ((2 * elementIndex <= minHeap.size()) && wrongOrder) {
// Check whether it shall swap the element with its left child or its right one if any.
if ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
if ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) {
swap(elementIndex, 2 * elementIndex + 1);
elementIndex = 2 * elementIndex + 1;
} else {
swap(elementIndex, 2 * elementIndex);
elementIndex = 2 * elementIndex;
}
wrongOrder = (key > getElementKey(elementIndex * 2))
|| (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size())));
}
}
@ -110,10 +107,7 @@ public class MinHeap implements Heap {
if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} // ... or down ?
else if (((2 * elementIndex <= minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))
|| ((2 * elementIndex < minHeap.size())
&& (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) {
toggleDown(elementIndex);
}
}

View File

@ -217,8 +217,7 @@ class LinkOperations {
public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink -->
if (doublyLinkedList
.isEmpty()) { // Check if there are no elements in list then it adds first element
if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
tail = newLink;
head = tail;
} else {

View File

@ -203,9 +203,7 @@ public class SkipList<E extends Comparable<E>> {
return acc.toString();
})
.collect(Collectors.joining("\n"));
String positions = IntStream.range(0, sizeWithHeader - 1)
.mapToObj(i -> String.format("%3d", i))
.collect(Collectors.joining(" "));
String positions = IntStream.range(0, sizeWithHeader - 1).mapToObj(i -> String.format("%3d", i)).collect(Collectors.joining(" "));
return result + String.format("%n H %s%n", positions);
}
@ -296,8 +294,7 @@ public class SkipList<E extends Comparable<E>> {
public BernoulliHeightStrategy(double probability) {
if (probability <= 0 || probability >= 1) {
throw new IllegalArgumentException(
"Probability should be from 0 to 1. But was: " + probability);
throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability);
}
this.probability = probability;
}

View File

@ -123,8 +123,7 @@ 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;
return node.data;

View File

@ -23,8 +23,7 @@ public class DecimalToAnyUsingStack {
*/
private static String convert(int number, int radix) {
if (radix < 2 || radix > 16) {
throw new ArithmeticException(
String.format("Invalid input -> number:%d,radius:%d", number, radix));
throw new ArithmeticException(String.format("Invalid input -> number:%d,radius:%d", number, radix));
}
char[] tables = {
'0',

View File

@ -23,7 +23,6 @@ public class CheckBinaryTreeIsValidBST {
return false;
}
return (
isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max));
}
}

View File

@ -48,12 +48,10 @@ public class CheckTreeIsSymmetric {
return false;
}
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left)
&& isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
}
private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
return leftSubtreeRoot == null || rightSubtreeRoot == null
|| leftSubtreeRoot.data != rightSubtreeRoot.data;
return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
}
}

View File

@ -36,8 +36,7 @@ public class CreateBinaryTreeFromInorderPreorder {
return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length);
}
private static Node createTree(final Integer[] preorder, final Integer[] inorder,
final int preStart, final int inStart, final int size) {
private static Node createTree(final Integer[] preorder, final Integer[] inorder, final int preStart, final int inStart, final int size) {
if (size == 0) {
return null;
}
@ -50,14 +49,11 @@ public class CreateBinaryTreeFromInorderPreorder {
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
root.right
= createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root;
}
private static Node createTreeOptimized(final Integer[] preorder,
final Map<Integer, Integer> inorderMap, final int preStart, final int inStart,
final int size) {
private static Node createTreeOptimized(final Integer[] preorder, final Map<Integer, Integer> inorderMap, final int preStart, final int inStart, final int size) {
if (size == 0) {
return null;
}
@ -66,10 +62,8 @@ public class CreateBinaryTreeFromInorderPreorder {
int i = inorderMap.get(preorder[preStart]);
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left
= createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
root.right = createTreeOptimized(
preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
root.left = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount);
root.right = createTreeOptimized(preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount);
return root;
}
}

View File

@ -37,8 +37,7 @@ public class KDTree {
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");
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0);
}
@ -49,13 +48,11 @@ 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");
if (point.getDimension() != k) throw new IllegalArgumentException("Points must have the same dimension");
this.root = build(points, 0);
}
@ -224,8 +221,7 @@ 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);
}
@ -257,8 +253,7 @@ 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);
}
@ -304,10 +299,7 @@ public class KDTree {
Node left = findMin(root.left, axis);
Node right = findMin(root.right, axis);
Node[] candidates = {left, root, right};
return Arrays.stream(candidates)
.filter(Objects::nonNull)
.min(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
return Arrays.stream(candidates).filter(Objects::nonNull).min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
}
}
@ -339,10 +331,7 @@ public class KDTree {
Node left = findMax(root.left, axis);
Node right = findMax(root.right, axis);
Node[] candidates = {left, root, right};
return Arrays.stream(candidates)
.filter(Objects::nonNull)
.max(Comparator.comparingInt(a -> a.point.getCoordinate(axis)))
.orElse(null);
return Arrays.stream(candidates).filter(Objects::nonNull).max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
}
}
@ -352,8 +341,7 @@ public class KDTree {
* @param point the point to delete
* */
public void delete(Point point) {
Node node
= search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
root = delete(root, node);
}
@ -406,12 +394,10 @@ public class KDTree {
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());
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
if (distance < Point.comparableDistance(nearest.point, point)) nearest = root;
nearest = findNearest(root.getNearChild(point), point, nearest);
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point))
nearest = findNearest(root.getFarChild(point), point, nearest);
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) nearest = findNearest(root.getFarChild(point), point, nearest);
return nearest;
}
}

View File

@ -53,8 +53,7 @@ public class LCA {
* @param parent An array to store parents of all vertices
* @param depth An array to store depth of all vertices
*/
private static void dfs(
ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) {
for (int adjacent : adj.get(s)) {
if (adjacent != p) {
parent[adjacent] = s;

View File

@ -28,8 +28,7 @@ public class RedBlackBST {
return;
}
printTree(node.left);
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
+ " Parent: " + node.p.key + "\n");
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTree(node.right);
}
@ -37,8 +36,7 @@ public class RedBlackBST {
if (node == nil) {
return;
}
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key
+ " Parent: " + node.p.key + "\n");
System.out.print(((node.color == R) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n");
printTreepre(node.left);
printTreepre(node.right);
}

View File

@ -26,8 +26,7 @@ public class SegmentTree {
}
int mid = start + (end - start) / 2;
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1)
+ constructTree(arr, mid + 1, end, index * 2 + 2);
this.seg_t[index] = constructTree(arr, start, mid, index * 2 + 1) + constructTree(arr, mid + 1, end, index * 2 + 2);
return this.seg_t[index];
}
@ -69,8 +68,7 @@ public class SegmentTree {
}
int mid = start + (end - start) / 2;
return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1)
+ getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
return (getSumTree(start, mid, q_start, q_end, seg_index * 2 + 1) + getSumTree(mid + 1, end, q_start, q_end, seg_index * 2 + 2));
}
/* A function to query the sum of the subarray [start...end]*/