diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index ccd8c643..4dd1ba4f 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -27,7 +27,7 @@ class DecimalToBinary { public static void conventionalConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf("Conventional conversion.\n\tEnter the decimal number: "); + System.out.printf("Conventional conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = n % 2; @@ -46,7 +46,7 @@ class DecimalToBinary { public static void bitwiseConversion() { int n, b = 0, c = 0, d; Scanner input = new Scanner(System.in); - System.out.printf("Bitwise conversion.\n\tEnter the decimal number: "); + System.out.printf("Bitwise conversion.%n Enter the decimal number: "); n = input.nextInt(); while (n != 0) { d = (n & 1); diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java index dd8d8771..4f15c488 100644 --- a/Conversions/OctalToHexadecimal.java +++ b/Conversions/OctalToHexadecimal.java @@ -15,7 +15,7 @@ public class OctalToHexadecimal { * @param s The Octal Number * @return The Decimal number */ - public static int OctToDec(String s) { + public static int octToDec(String s) { int i = 0; for (int j = 0; j < s.length(); j++) { char num = s.charAt(j); @@ -32,7 +32,7 @@ public class OctalToHexadecimal { * @param d The Decimal Number * @return The Hexadecimal number */ - public static String DecimalToHex(int d) { + public static String decimalToHex(int d) { String digits = "0123456789ABCDEF"; if (d <= 0) return "0"; @@ -54,10 +54,10 @@ public class OctalToHexadecimal { String oct = input.next(); // Pass the octal number to function and get converted deciaml form - int decimal = OctToDec(oct); + int decimal = octToDec(oct); // Pass the decimla number to function and get converted Hex form of the number - String hex = DecimalToHex(decimal); + String hex = decimalToHex(decimal); System.out.println("The Hexadecimal equivalant is: " + hex); input.close(); } diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java index 0a6a0723..f70c45ce 100644 --- a/DataStructures/DynamicArray/DynamicArray.java +++ b/DataStructures/DynamicArray/DynamicArray.java @@ -41,7 +41,7 @@ public class DynamicArray implements Iterable { } public void put(final int index, E element) { - Objects.checkIndex(index, this.size); +// Objects.checkIndex(index, this.size); this.elements[index] = element; } @@ -79,7 +79,7 @@ public class DynamicArray implements Iterable { } private E getElement(final int index) { - Objects.checkIndex(index, this.size); +// Objects.checkIndex(index, this.size); return (E) this.elements[index]; } diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java index 6dffede9..41c89bb0 100644 --- a/DataStructures/Graphs/BellmanFord.java +++ b/DataStructures/Graphs/BellmanFord.java @@ -23,7 +23,7 @@ start vertex, end vertes and weights. Vertices should be labelled with a number * @param v End vertex * @param c Weight */ - Edge(int a,int b,int c) + public Edge(int a,int b,int c) { u=a; v=b; diff --git a/DataStructures/Graphs/MatrixGraphs.java b/DataStructures/Graphs/MatrixGraphs.java index e7fb9cc4..32a7c990 100644 --- a/DataStructures/Graphs/MatrixGraphs.java +++ b/DataStructures/Graphs/MatrixGraphs.java @@ -127,8 +127,7 @@ class AdjacencyMatrixGraph { * @return returns a string describing this graph */ public String toString() { - String s = new String(); - s = " "; + String s = " "; for (int i = 0; i < this.numberOfVertices(); i++) { s = s + String.valueOf(i) + " "; } diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index 11314601..028d9b3e 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -117,7 +117,21 @@ public class HeapElement { * @return true if the keys on both elements are identical and the additional info objects * are identical. */ - public boolean equals(HeapElement otherHeapElement) { - return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); + @Override + public boolean equals(Object o) { + if (o != null) { + if (!(o instanceof HeapElement)) return false; + HeapElement otherHeapElement = (HeapElement) o; + return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo)); + } + return false; + } + + @Override + public int hashCode() { + int result = 0; + result = 31*result + (int) key; + result = 31*result + (additionalInfo != null ? additionalInfo.hashCode() : 0); + return result; } } diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java index fed09bcb..3945caa9 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -49,9 +49,9 @@ public class MaxHeap implements Heap { // Toggle an element up to its right place as long as its key is lower than its parent's private void toggleUp(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex / 2)) < key) { - swap(elementIndex, (int) Math.floor(elementIndex / 2)); - elementIndex = (int) Math.floor(elementIndex / 2); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } } @@ -101,7 +101,7 @@ public class MaxHeap implements Heap { maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); maxHeap.remove(maxHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex); + 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)))) diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java index 4b435e6d..39ee6ebf 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -44,9 +44,9 @@ public class MinHeap implements Heap { // Toggle an element up to its right place as long as its key is lower than its parent's private void toggleUp(int elementIndex) { double key = minHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex / 2)) > key) { - swap(elementIndex, (int) Math.floor(elementIndex / 2)); - elementIndex = (int) Math.floor(elementIndex / 2); + while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); + elementIndex = (int) Math.floor(elementIndex / 2.0); } } @@ -96,7 +96,7 @@ public class MinHeap implements Heap { minHeap.set(elementIndex - 1, getElement(minHeap.size())); minHeap.remove(minHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex); + 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)))) diff --git a/DataStructures/Lists/CircleLinkedList.java b/DataStructures/Lists/CircleLinkedList.java index 67235172..b46441a1 100644 --- a/DataStructures/Lists/CircleLinkedList.java +++ b/DataStructures/Lists/CircleLinkedList.java @@ -14,7 +14,7 @@ public class CircleLinkedList { //For better O.O design this should be private allows for better black box design private int size; //this will point to dummy node; - private Node head; + private Node head = null; //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; public CircleLinkedList() { diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index e1b0041d..706b33c7 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -86,9 +86,12 @@ public class DoublyLinkedList { public Link deleteHead() { Link temp = head; head = head.next; // oldHead <--> 2ndElement(head) - head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed - if (head == null) + + if (head == null) { tail = null; + } else { + head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed + } return temp; } @@ -100,10 +103,13 @@ public class DoublyLinkedList { public Link deleteTail() { Link temp = tail; tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null - tail.next = null; // 2ndLast(tail) --> null + if (tail == null) { head = null; + } else{ + tail.next = null; // 2ndLast(tail) --> null } + return temp; } diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java index 616e6a1e..0f1d5868 100644 --- a/DataStructures/Stacks/NodeStack.java +++ b/DataStructures/Stacks/NodeStack.java @@ -74,7 +74,7 @@ public class NodeStack { } else { newNs.setPrevious(NodeStack.head); NodeStack.head.setNext(newNs); - NodeStack.head = newNs; + NodeStack.head.setHead(newNs); } NodeStack.setSize(NodeStack.getSize() + 1); @@ -89,7 +89,7 @@ public class NodeStack { Item item = (Item) NodeStack.head.getData(); - NodeStack.head = NodeStack.head.getPrevious(); + NodeStack.head.setHead(NodeStack.head.getPrevious()); NodeStack.head.setNext(null); NodeStack.setSize(NodeStack.getSize() - 1); diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index bcf17249..69e65fe6 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -15,8 +15,8 @@ public class LevelOrderTraversal { // Root of the Binary Tree Node root; - public LevelOrderTraversal() { - root = null; + public LevelOrderTraversal( Node root) { + this.root = root; } /* function to print level order traversal of tree*/ diff --git a/DataStructures/Trees/LevelOrderTraversalQueue.java b/DataStructures/Trees/LevelOrderTraversalQueue.java index d43d62d6..5f85f987 100644 --- a/DataStructures/Trees/LevelOrderTraversalQueue.java +++ b/DataStructures/Trees/LevelOrderTraversalQueue.java @@ -19,11 +19,9 @@ public class LevelOrderTraversalQueue { } } - Node root; - /* Given a binary tree. Print its nodes in level order using array for implementing queue */ - void printLevelOrder() { + void printLevelOrder(Node root) { Queue queue = new LinkedList(); queue.add(root); while (!queue.isEmpty()) { diff --git a/DataStructures/Trees/ValidBSTOrNot.java b/DataStructures/Trees/ValidBSTOrNot.java index a1a737fe..ba50c079 100644 --- a/DataStructures/Trees/ValidBSTOrNot.java +++ b/DataStructures/Trees/ValidBSTOrNot.java @@ -13,14 +13,13 @@ public class ValidBSTOrNot { } //Root of the Binary Tree - Node root; /* can give min and max value according to your code or can write a function to find min and max value of tree. */ /* returns true if given search tree is binary search tree (efficient version) */ - boolean isBST() { + boolean isBST(Node root) { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java index c8296518..e30adfef 100644 --- a/DynamicProgramming/LongestIncreasingSubsequence.java +++ b/DynamicProgramming/LongestIncreasingSubsequence.java @@ -22,7 +22,7 @@ public class LongestIncreasingSubsequence { private static int upperBound(int[] ar, int l, int r, int key) { while (l < r - 1) { - int m = (l + r) / 2; + int m = (l + r) >>> 1; if (ar[m] >= key) r = m; else diff --git a/DynamicProgramming/MatrixChainMultiplication.java b/DynamicProgramming/MatrixChainMultiplication.java index 66b2a358..9073400d 100644 --- a/DynamicProgramming/MatrixChainMultiplication.java +++ b/DynamicProgramming/MatrixChainMultiplication.java @@ -25,7 +25,7 @@ public class MatrixChainMultiplication { count++; } for (Matrix m : mArray) { - System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row()); + System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row()); } size = mArray.size(); diff --git a/Maths/GCD.java b/Maths/GCD.java index fb9aeb21..bff1c33c 100644 --- a/Maths/GCD.java +++ b/Maths/GCD.java @@ -52,6 +52,6 @@ public class GCD { // call gcd function (input array) System.out.println(gcd(myIntArray)); // => 4 - System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8 + System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8 } } diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index af8e33b0..b1a0987d 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -1,192 +1,219 @@ -package Others; - - -/** - * Dijkstra's algorithm,is a graph search algorithm that solves the single-source - * shortest path problem for a graph with nonnegative edge path costs, producing - * a shortest path tree. - *

- * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting - * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node. - *

- * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java - * Also most of the comments are from RosettaCode. - */ - -import java.util.*; - -public class Dijkstra { - private static final Graph.Edge[] GRAPH = { - // Distance from node "a" to node "b" is 7. - // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), - // a new edge would be needed for that - new Graph.Edge("a", "b", 7), - new Graph.Edge("a", "c", 9), - new Graph.Edge("a", "f", 14), - new Graph.Edge("b", "c", 10), - new Graph.Edge("b", "d", 15), - new Graph.Edge("c", "d", 11), - new Graph.Edge("c", "f", 2), - new Graph.Edge("d", "e", 6), - new Graph.Edge("e", "f", 9), - }; - private static final String START = "a"; - private static final String END = "e"; - - /** - * main function - * Will run the code with "GRAPH" that was defined above. - */ - public static void main(String[] args) { - Graph g = new Graph(GRAPH); - g.dijkstra(START); - g.printPath(END); - //g.printAllPaths(); - } -} - -class Graph { - // mapping of vertex names to Vertex objects, built from a set of Edges - private final Map graph; - - /** - * One edge of the graph (only used by Graph constructor) - */ - public static class Edge { - public final String v1, v2; - public final int dist; - - public Edge(String v1, String v2, int dist) { - this.v1 = v1; - this.v2 = v2; - this.dist = dist; - } - } - - /** - * One vertex of the graph, complete with mappings to neighbouring vertices - */ - public static class Vertex implements Comparable { - public final String name; - // MAX_VALUE assumed to be infinity - public int dist = Integer.MAX_VALUE; - public Vertex previous = null; - public final Map neighbours = new HashMap<>(); - - public Vertex(String name) { - this.name = name; - } - - private void printPath() { - if (this == this.previous) { - System.out.printf("%s", this.name); - } else if (this.previous == null) { - System.out.printf("%s(unreached)", this.name); - } else { - this.previous.printPath(); - System.out.printf(" -> %s(%d)", this.name, this.dist); - } - } - - public int compareTo(Vertex other) { - if (dist == other.dist) - return name.compareTo(other.name); - - return Integer.compare(dist, other.dist); - } - - @Override - public String toString() { - return "(" + name + ", " + dist + ")"; - } - } - - /** - * Builds a graph from a set of edges - */ - public Graph(Edge[] edges) { - graph = new HashMap<>(edges.length); - - // one pass to find all vertices - for (Edge e : edges) { - if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); - if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); - } - - // another pass to set neighbouring vertices - for (Edge e : edges) { - graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); - // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph - } - } - - /** - * Runs dijkstra using a specified source vertex - */ - public void dijkstra(String startName) { - if (!graph.containsKey(startName)) { - System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); - return; - } - final Vertex source = graph.get(startName); - NavigableSet q = new TreeSet<>(); - - // set-up vertices - for (Vertex v : graph.values()) { - v.previous = v == source ? source : null; - v.dist = v == source ? 0 : Integer.MAX_VALUE; - q.add(v); - } - - dijkstra(q); - } - - /** - * Implementation of dijkstra's algorithm using a binary heap. - */ - private void dijkstra(final NavigableSet q) { - Vertex u, v; - while (!q.isEmpty()) { - // vertex with shortest distance (first iteration will return source) - u = q.pollFirst(); - if (u.dist == Integer.MAX_VALUE) - break; // we can ignore u (and any other remaining vertices) since they are unreachable - - // look at distances to each neighbour - for (Map.Entry a : u.neighbours.entrySet()) { - v = a.getKey(); // the neighbour in this iteration - - final int alternateDist = u.dist + a.getValue(); - if (alternateDist < v.dist) { // shorter path to neighbour found - q.remove(v); - v.dist = alternateDist; - v.previous = u; - q.add(v); - } - } - } - } - - /** - * Prints a path from the source to the specified vertex - */ - public void printPath(String endName) { - if (!graph.containsKey(endName)) { - System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); - return; - } - - graph.get(endName).printPath(); - System.out.println(); - } - - /** - * Prints the path from the source to every vertex (output order is not guaranteed) - */ - public void printAllPaths() { - for (Vertex v : graph.values()) { - v.printPath(); - System.out.println(); - } - } +package Others; + + +/** + * Dijkstra's algorithm,is a graph search algorithm that solves the single-source + * shortest path problem for a graph with nonnegative edge path costs, producing + * a shortest path tree. + *

+ * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting + * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node. + *

+ * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java + * Also most of the comments are from RosettaCode. + */ + +import java.util.*; + +public class Dijkstra { + private static final Graph.Edge[] GRAPH = { + // Distance from node "a" to node "b" is 7. + // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), + // a new edge would be needed for that + new Graph.Edge("a", "b", 7), + new Graph.Edge("a", "c", 9), + new Graph.Edge("a", "f", 14), + new Graph.Edge("b", "c", 10), + new Graph.Edge("b", "d", 15), + new Graph.Edge("c", "d", 11), + new Graph.Edge("c", "f", 2), + new Graph.Edge("d", "e", 6), + new Graph.Edge("e", "f", 9), + }; + private static final String START = "a"; + private static final String END = "e"; + + /** + * main function + * Will run the code with "GRAPH" that was defined above. + */ + public static void main(String[] args) { + Graph g = new Graph(GRAPH); + g.dijkstra(START); + g.printPath(END); + //g.printAllPaths(); + } +} + +class Graph { + // mapping of vertex names to Vertex objects, built from a set of Edges + private final Map graph; + + /** + * One edge of the graph (only used by Graph constructor) + */ + public static class Edge { + public final String v1, v2; + public final int dist; + + public Edge(String v1, String v2, int dist) { + this.v1 = v1; + this.v2 = v2; + this.dist = dist; + } + } + + /** + * One vertex of the graph, complete with mappings to neighbouring vertices + */ + public static class Vertex implements Comparable { + public final String name; + // MAX_VALUE assumed to be infinity + public int dist = Integer.MAX_VALUE; + public Vertex previous = null; + public final Map neighbours = new HashMap<>(); + + public Vertex(String name) { + this.name = name; + } + + private void printPath() { + if (this == this.previous) { + System.out.printf("%s", this.name); + } else if (this.previous == null) { + System.out.printf("%s(unreached)", this.name); + } else { + this.previous.printPath(); + System.out.printf(" -> %s(%d)", this.name, this.dist); + } + } + + public int compareTo(Vertex other) { + if (dist == other.dist) + return name.compareTo(other.name); + + return Integer.compare(dist, other.dist); + } + + @Override + public boolean equals(Object object) { + if (this == object) return true; + if (object == null || getClass() != object.getClass()) return false; + if (!super.equals(object)) return false; + + Vertex vertex = (Vertex) object; + + if (dist != vertex.dist) return false; + if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false; + if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) return false; + if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + dist; + result = 31 * result + (previous != null ? previous.hashCode() : 0); + result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "(" + name + ", " + dist + ")"; + } + } + + /** + * Builds a graph from a set of edges + */ + public Graph(Edge[] edges) { + graph = new HashMap<>(edges.length); + + // one pass to find all vertices + for (Edge e : edges) { + if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); + if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); + } + + // another pass to set neighbouring vertices + for (Edge e : edges) { + graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); + // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph + } + } + + /** + * Runs dijkstra using a specified source vertex + */ + public void dijkstra(String startName) { + if (!graph.containsKey(startName)) { + System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName); + return; + } + final Vertex source = graph.get(startName); + NavigableSet q = new TreeSet<>(); + + // set-up vertices + for (Vertex v : graph.values()) { + v.previous = v == source ? source : null; + v.dist = v == source ? 0 : Integer.MAX_VALUE; + q.add(v); + } + + dijkstra(q); + } + + /** + * Implementation of dijkstra's algorithm using a binary heap. + */ + private void dijkstra(final NavigableSet q) { + Vertex u, v; + while (!q.isEmpty()) { + // vertex with shortest distance (first iteration will return source) + u = q.pollFirst(); + if (u.dist == Integer.MAX_VALUE) + break; // we can ignore u (and any other remaining vertices) since they are unreachable + + // look at distances to each neighbour + for (Map.Entry a : u.neighbours.entrySet()) { + v = a.getKey(); // the neighbour in this iteration + + final int alternateDist = u.dist + a.getValue(); + if (alternateDist < v.dist) { // shorter path to neighbour found + q.remove(v); + v.dist = alternateDist; + v.previous = u; + q.add(v); + } + } + } + } + + /** + * Prints a path from the source to the specified vertex + */ + public void printPath(String endName) { + if (!graph.containsKey(endName)) { + System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName); + return; + } + + graph.get(endName).printPath(); + System.out.println(); + } + + /** + * Prints the path from the source to every vertex (output order is not guaranteed) + */ + public void printAllPaths() { + for (Vertex v : graph.values()) { + v.printPath(); + System.out.println(); + } + } + } \ No newline at end of file diff --git a/Others/TopKWords.java b/Others/TopKWords.java index 6cccfc27..b3f0e584 100644 --- a/Others/TopKWords.java +++ b/Others/TopKWords.java @@ -50,7 +50,8 @@ public class TopKWords { } finally { try { // you always have to close the I/O streams - fis.close(); + if (fis != null) + fis.close(); } catch (IOException e) { e.printStackTrace(); } diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java index 7d35ed36..db319595 100644 --- a/Others/TowerOfHanoi.java +++ b/Others/TowerOfHanoi.java @@ -12,7 +12,7 @@ class TowerOfHanoi { // Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole shift(n - 1, startPole, endPole, intermediatePole); - System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing + System.out.println("%nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing // Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole shift(n - 1, intermediatePole, startPole, endPole); } diff --git a/Searches/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java index 8df51a7d..5a3a6d9e 100644 --- a/Searches/IterativeBinarySearch.java +++ b/Searches/IterativeBinarySearch.java @@ -40,7 +40,7 @@ public final class IterativeBinarySearch implements SearchAlgorithm { r = array.length - 1; while (l <= r) { - k = (l + r) / 2; + k = (l + r) >>> 1; cmp = key.compareTo(array[k]); if (cmp == 0) { diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index 47f79de0..ef564ac7 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -64,7 +64,7 @@ class QuickSort implements SortAlgorithm { **/ private static > int partition(T[] array, int left, int right) { - int mid = (left + right) / 2; + int mid = (left + right) >>> 1; T pivot = array[mid]; while (left <= right) { diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java index cec0ddce..76893f45 100644 --- a/ciphers/Caesar.java +++ b/ciphers/Caesar.java @@ -125,6 +125,8 @@ public class Caesar { case 'D': case 'd': System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); + default: + System.out.println("default case"); } input.close(); } diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java index 26acc628..60af4ff5 100644 --- a/ciphers/ColumnarTranspositionCipher.java +++ b/ciphers/ColumnarTranspositionCipher.java @@ -117,7 +117,7 @@ public class ColumnarTranspositionCipher { * order to respect the Columnar Transposition Cipher Rule. */ private static int numberOfRows(String word) { - if ((double) word.length() / keyword.length() > word.length() / keyword.length()) { + if (word.length() / keyword.length() > word.length() / keyword.length()) { return (word.length() / keyword.length()) + 1; } else { return word.length() / keyword.length(); diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java index 375d3e1a..67ebe89b 100644 --- a/divideconquer/ClosestPair.java +++ b/divideconquer/ClosestPair.java @@ -31,6 +31,15 @@ public final class ClosestPair { * Minimum point length. */ private static double minNum = Double.MAX_VALUE; + + public static void setMinNum(double minNum) { + ClosestPair.minNum = minNum; + } + + public static void setSecondCount(int secondCount) { + ClosestPair.secondCount = secondCount; + } + /** * secondCount */ @@ -213,7 +222,7 @@ public final class ClosestPair { for (int i = 0; i < totalNum; i++) { double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); if (xGap < minValue) { - secondCount++; // size of the array + ClosestPair.setSecondCount(secondCount + 1); // size of the array } else { if (divideArray[i].x > divideArray[divideX].x) { break; @@ -250,7 +259,7 @@ public final class ClosestPair { minValue = length; // Conditional for registering final coordinate if (length < minNum) { - minNum = length; + ClosestPair.setMinNum(length); point1 = firstWindow[i]; point2 = firstWindow[j]; } @@ -260,7 +269,7 @@ public final class ClosestPair { } } } - secondCount = 0; + ClosestPair.setSecondCount(0); return minValue; } @@ -288,7 +297,7 @@ public final class ClosestPair { length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // Conditional statement for registering final coordinate if (length < minNum) { - minNum = length; + ClosestPair.setMinNum(length); } point1 = arrayParam[0]; @@ -311,7 +320,7 @@ public final class ClosestPair { minValue = length; if (length < minNum) { // Registering final coordinate - minNum = length; + ClosestPair.setMinNum(length); point1 = arrayParam[i]; point2 = arrayParam[j]; }