diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d502de24281c..92a2dbf3e104 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,2 +1,27 @@ -## Contribution Guidelines -Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute. +:+1::tada: Before guiding you through the contribution process TheAlgorithms/Java thank you for being one of us! :+1::tada: + +## How to contribute? + +#### **Did you find a bug?** + +* **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues). + +* Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request and it will be evaluated by project maintainers. + +* If you are unable to find an open issue refering to the same problem, depending on the type of issue follow the appropriate steps: + +#### **Do you want to contribute to the documentation?** + +* Please read the documentation in here [Contributing to the Documentation]() ,[open a new one issue](https://github.com/TheAlgorithms/Java/issues/new), make changes and then create a pull request, it will be put under review and accepted if it is approprite. + +#### **Do you want to add a new feature?** +* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new). Be sure to include a **title and a clear description** and a **test case** demonstrating the new feature that you want to add to the project. + +#### **Do you want to fix a bug?** +* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new).Be sure to include a **title and a clear description** and a **test case** demonstrating the expected behaviour that is not occuring. + +#### **Do you have questions about the source code?** + +* Ask any question about how to use the repository in the [TheAlgorithms room in GITTER](https://gitter.im/TheAlgorithms/community?source=orgpage#) or [open a new one issue](https://github.com/TheAlgorithms/Java/issues/new) + +:+1::tada: That's all you need to know about the process now it's your turn to help us improve the repository, thank you again! :+1::tada: diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java index ccd8c643fa9a..4dd1ba4f4414 100644 --- a/Conversions/DecimalToBinary.java +++ b/Conversions/DecimalToBinary.java @@ -27,7 +27,7 @@ public static void main(String args[]) { 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 @@ public static void conventionalConversion() { 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 dd8d877109b5..4f15c488237b 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 static int OctToDec(String s) { * @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 static void main(String args[]) { 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/DIRECTORY.md b/DIRECTORY.md index aee8eea6f2a2..e50e18eaf647 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -35,19 +35,19 @@ * DynamicArray * [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/DynamicArray/DynamicArray.java) * Graphs + * [A Star](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/A_Star.java) * [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/BellmanFord.java) * [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/ConnectedComponent.java) * [Cycles](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Cycles.java) * [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/FloydWarshall.java) * [Graphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Graphs.java) + * [Kruskal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Kruskal.java) * [MatrixGraphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/MatrixGraphs.java) * [PrimMST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/PrimMST.java) * HashMap * Hashing * [HashMap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/HashMap.java) - * [LinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/LinkedList.java) * [Main](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Main.java) - * [Node](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Node.java) * Heaps * [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/EmptyHeapException.java) * [Heap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/Heap.java) @@ -139,6 +139,7 @@ * [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/Misc/PalindromePrime.java) ## Others + * [3 sum](https://github.com/TheAlgorithms/Java/blob/master/Others/3%20sum.java) * [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java) * [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java) * [BestFit](https://github.com/TheAlgorithms/Java/blob/master/Others/BestFit.java) @@ -169,6 +170,7 @@ * [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java) * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseString.java) * [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/Others/RootPrecision.java) + * [Rotation of array without using extra space](https://github.com/TheAlgorithms/Java/blob/master/Others/Rotation%20of%20array%20without%20using%20extra%20space.java) * [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/Others/SieveOfEratosthenes.java) * [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java) * [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java) @@ -193,6 +195,7 @@ * [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BitonicSort.java) * [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java) * [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java) + * [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BucketSort.java) * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java) * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java) * [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CountingSort.java) diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java index 0a6a0723e2a1..f70c45cec815 100644 --- a/DataStructures/DynamicArray/DynamicArray.java +++ b/DataStructures/DynamicArray/DynamicArray.java @@ -41,7 +41,7 @@ public void add(final E element) { } 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 @@ private void fastRemove(final Object[] elements, final int index) { } 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/A_Star.java b/DataStructures/Graphs/A_Star.java new file mode 100644 index 000000000000..9fa92ce32118 --- /dev/null +++ b/DataStructures/Graphs/A_Star.java @@ -0,0 +1,159 @@ +/* + Time Complexity = O(E), where E is equal to the number of edges +*/ + +package A_Star; + +import java.util.*; + +public class A_Star { + + private static class Graph { + //Graph's structure can be changed only applying changes to this class. + private ArrayList [] graph; + + //Initialise ArrayLists in Constructor + public Graph(int size) { + this.graph = new ArrayList[size]; + for (int i = 0; i < size; i++) { + this.graph[i] = new ArrayList<>(); + } + } + + private ArrayList getNeighbours(int from) { return this.graph[from]; } + + //Graph is bidirectional, for just one direction remove second instruction of this method. + private void addEdge (Edge edge) { + this.graph[edge.getFrom()].add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); + this.graph[edge.getTo()].add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); + } + } + + private static class Edge { + private int from; + private int to; + private int weight; + + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } + + public int getFrom() { return from; } + + public int getTo() { return to; } + + public int getWeight() { return weight; } + } + + //class to iterate during the algorithm execution, and also used to return the solution. + private static class PathAndDistance { + private int distance; //distance advanced so far. + private ArrayList path; //list of visited nodes in this path. + private int estimated; //heuristic value associated to the last node od the path (current node). + + public PathAndDistance(int distance, ArrayList path, int estimated) { + this.distance = distance; + this.path = path; + this.estimated = estimated; + } + + public int getDistance() { return distance; } + + public ArrayList getPath() { return path; } + + public int getEstimated() { return estimated; } + + private void printSolution () { + if (this.path != null) + System.out.println("Optimal path: " + this.path.toString() + + ", distance: " + this.distance); + else + System.out.println("There is no path available to connect the points"); + } + } + + private static void initializeGraph(Graph graph, ArrayList data) { + for (int i = 0; i < data.size(); i+=4) { + graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); + } + /* + .x. node + (y) cost + - or | or / bidirectional connection + + ( 98)- .7. -(86)- .4. + | + ( 85)- .17. -(142)- .18. -(92)- .8. -(87)- .11. + | + . 1. -------------------- (160) + | \ | + (211) \ .6. + | \ | + . 5. (101)-.13. -(138) (115) + | | | / + ( 99) ( 97) | / + | | | / + .12. -(151)- .15. -(80)- .14. | / + | | | | / + ( 71) (140) (146)- .2. -(120) + | | | + .19. -( 75)- . 0. .10. -(75)- .3. + | | + (118) ( 70) + | | + .16. -(111)- .9. + */ + } + + public static void main(String[] args) { + //heuristic function optimistic values + int[] heuristic = {366, 0, 160, 242, 161, 178, 77, 151, 226, + 244, 241, 234, 380, 98, 193, 253, 329, 80, 199, 374}; + + Graph graph = new Graph(20); + ArrayList 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); + solution.printSolution(); + + } + + public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { + //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 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<>(Arrays.asList(from)), 0)); + + boolean solutionFound = false; + 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. + if (currentPosition == to) + solutionFound = true; + else + for (Edge edge : graph.getNeighbours(currentPosition)) + if (!currentData.getPath().contains(edge.getTo())) { //Avoid Cycles + ArrayList updatedPath = new ArrayList<>(currentData.getPath()); + 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()])); + } + } + return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1); + //Out of while loop, if there is a solution, the current Data stores the optimal path, and its distance + } +} diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java index 6dffede9e606..41c89bb020ee 100644 --- a/DataStructures/Graphs/BellmanFord.java +++ b/DataStructures/Graphs/BellmanFord.java @@ -23,7 +23,7 @@ class Edge * @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/GraphAlgos b/DataStructures/Graphs/GraphAlgos new file mode 100644 index 000000000000..19938c48f042 --- /dev/null +++ b/DataStructures/Graphs/GraphAlgos @@ -0,0 +1,487 @@ +package DataStructures.Graphs; +/* +Implementation of graph by using hashmap for vertices of class which contains hashmap for vertex and then algos like prims dijktsra ,depth for search and traversal ,breadth for search and traversal ,algo for cycle present or not ,connected or not ,if not connected then connect it +Test case +Graph gp=new Graph(); + gp.addVertex("A"); + gp.addVertex("B"); + gp.addVertex("C"); + gp.addVertex("D"); + gp.addVertex("E"); + gp.addVertex("F"); + gp.addVertex("G"); + gp.addEdge("A", "B", 2); + gp.addEdge("A", "D", 10); + gp.addEdge("B", "C", 3); + gp.addEdge("C", "D", 1); + gp.addEdge("D", "E", 8); + gp.addEdge("E", "F", 5); + gp.addEdge("E", "G", 6); + gp.addEdge("F", "G", 4); + +// gp.display(); +// System.out.println(gp.numVertex()); +// System.out.println(gp.numEdge()); +// System.out.println(gp.containsEdge("A", "C")); +// +// System.out.println(gp.containsEdge("E", "F")); +// gp.removeEdge("D", "E"); +// gp.display(); +// gp.removeVertex("F"); +// gp.addVertex("F"); +// gp.display(); +// System.out.println(gp.hasPath("A", "F", new HashMap<>())); +// System.out.println(gp.dfs("A", "F")); +// gp.bft(); +// gp.dft(); +// gp.removeEdge("B","C"); +// gp.removeEdge("F","G"); +// System.out.println(gp.isConnected()); +// System.out.println(gp.isCyclic()); +// System.out.println(gp.isTree()); +// System.out.println(gp.getConnectedComp()); +// gp.prims().display(); + System.out.println(gp.Dijktsra("A")); + + + +*/ + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import Heaps.GenericHeap; +public class Graph { + private class vertex{ + HashMap nbrs=new HashMap<>(); + } + HashMap vertcs; + public Graph(){ + vertcs=new HashMap<>(); + } + public int numVertex() { + return this.vertcs.size(); + } + public boolean containsVertex(String vname) { + return this.vertcs.containsKey(vname); + } + public void addVertex(String vname) { + + vertex vtx=new vertex(); + this.vertcs.put(vname,vtx); + } + public void removeVertex(String vname) { + vertex vtx=this.vertcs.get(vname); + ArrayList keys=new ArrayList<>(vtx.nbrs.keySet()); + for(String key:keys) { + vertex nbrvtx=this.vertcs.get(key); + nbrvtx.nbrs.remove(vname); + } + this.vertcs.remove(vname); + } + + public int numEdge() { + int count=0; + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + vertex vtx=this.vertcs.get(key); + count+=vtx.nbrs.size(); + } + return count/2; + } + public boolean containsEdge(String vname1,String vname2) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2)) + return false; + return true; + } + public void addEdge(String vname1,String vname2,int cost) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||vtx1.nbrs.containsKey(vname2)) + return; + vtx1.nbrs.put(vname2,cost); + vtx2.nbrs.put(vname1,cost); + } + public void removeEdge(String vname1,String vname2) { + vertex vtx1=this.vertcs.get(vname1); + vertex vtx2=this.vertcs.get(vname2); + if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2)) + return; + vtx1.nbrs.remove(vname2); + vtx2.nbrs.remove(vname1); + } + + public void display() { + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + vertex vtx=this.vertcs.get(key); + System.out.println(key+" := "+vtx.nbrs); + } + } + + public boolean hasPath(String source ,String dest,HashMap processed) { + processed.put(source, true); + if(containsEdge(source,dest)) { + return true; + } + vertex vtx=this.vertcs.get(source); + ArrayList keys=new ArrayList<>(vtx.nbrs.keySet()); + for(String key:keys) { + if(!processed.containsKey(key) && hasPath(key,dest,processed)) + return true; + } + return false; + + } + private class pair{ + String vname; + String psf; + } + public boolean bfs(String source,String dest) { // breadth first search + HashMap processed=new HashMap<>(); + + LinkedList queue=new LinkedList<>(); + pair sp=new pair(); + sp.vname=source; + sp.psf=source; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + if(containsEdge(rp.vname,dest)) { + System.out.println(rp.psf+dest); + return true; + } + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + return false; + } + public boolean dfs(String source,String dest) { //deapth first search + LinkedList stack=new LinkedList<>(); + HashMap processed=new HashMap<>(); + pair sp=new pair(); + sp.vname=source; + sp.psf=source; + stack.addFirst(sp); + while(!stack.isEmpty()) { + pair rp=stack.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + if(containsEdge(rp.vname,dest)) { + System.out.println(rp.psf+dest); + return true; + } + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + stack.addFirst(np); + } + } + + } + return false; + } + public void bft() { //breadth first traversal + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + System.out.println(rp.vname+" via "+rp.psf); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + } + public void dft() { //deapt first traversal + HashMap processed=new HashMap<>(); + LinkedList stack=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + stack.addFirst(sp); + + while(!stack.isEmpty()) { + pair rp=stack.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + System.out.println(rp.vname+" via "+rp.psf); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + stack.addFirst(np); + } + } + } + } + } + + + public boolean isCyclic() { + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + return true; + processed.put(rp.vname,true); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + return false; + } + public boolean isConnected() { + int flag=0; + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + flag++; + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + } + if(flag>=2) + return false; + else + return true; + } + public boolean isTree() { + return !isCyclic()&&isConnected(); + } + public ArrayList> getConnectedComp() { + ArrayList> ans=new ArrayList<>(); + HashMap processed=new HashMap<>(); + LinkedList queue=new LinkedList<>(); + ArrayList keys=new ArrayList<>(this.vertcs.keySet()); + for(String key:keys) { + if(processed.containsKey(key)) + continue; + ArrayList subans=new ArrayList<>(); + pair sp=new pair(); + sp.vname=key; + sp.psf=key; + queue.addLast(sp); + + while(!queue.isEmpty()) { + pair rp=queue.removeFirst(); + if(processed.containsKey(rp.vname)) + continue; + processed.put(rp.vname,true); + + subans.add(rp.vname); + + vertex vtx=this.vertcs.get(rp.vname); + ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet()); + for(String nbr:nbrs) { + if(!processed.containsKey(nbr)) { + pair np=new pair(); + np.vname=nbr; + np.psf=rp.psf+nbr; + queue.addLast(np); + } + } + } + ans.add(subans); + } + return ans; + } + private class PrimsPair implements Comparable{ + String vname; + String acqvname; + int cost; + public int compareTo(PrimsPair o) { + return o.cost-this.cost; + } + + } + public Graph prims() { + HashMap map=new HashMap<>(); + GenericHeap heap=new GenericHeap<>(); + Graph mst=new Graph(); + for(String vrtx:this.vertcs.keySet()) { + PrimsPair np=new PrimsPair(); + np.acqvname=null; + np.vname=vrtx; + np.cost=Integer.MAX_VALUE; + heap.add(np); + map.put(vrtx, np); + } + while(!heap.isEmpty()) { + PrimsPair rp=heap.remove(); + map.remove(rp.vname); + + if(rp.acqvname==null) { + mst.addVertex(rp.vname); + }else { + mst.addVertex(rp.vname); + mst.addEdge(rp.vname, rp.acqvname, rp.cost); + } + + for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) { + if(map.containsKey(nbr)) { + //old cost that is from diff path stored in map + int oc=map.get(nbr).cost; + // cost that present vname need cost to go to nbr + int nc=this.vertcs.get(rp.vname).nbrs.get(nbr); + if(nc{ + String vname; + String psf; + int cost; + public int compareTo(DijktsraPair o) { + return o.cost-this.cost; + } + + } + public HashMap Dijktsra(String source) { + HashMap map=new HashMap<>(); + GenericHeap heap=new GenericHeap<>(); + HashMap ans =new HashMap<>(); + for(String vrtx:this.vertcs.keySet()) { + DijktsraPair np=new DijktsraPair(); + np.psf=""; + np.vname=vrtx; + np.cost=Integer.MAX_VALUE; + if(vrtx==source) { + np.cost=0; + np.psf=source; + } + heap.add(np); + map.put(vrtx, np); + } + while(!heap.isEmpty()) { + DijktsraPair rp=heap.remove(); + map.remove(rp.vname); + + ans.put(rp.vname,rp.cost); + + for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) { + if(map.containsKey(nbr)) { + //old cost that is from diff path stored in map + int oc=map.get(nbr).cost; + // cost that present vname need cost to go to nbr + int nc=rp.cost+this.vertcs.get(rp.vname).nbrs.get(nbr); + if(nc Connect all the edges with the minimum cost. +//Possible Solution -> Kruskal Algorithm (KA), KA finds the minimum-spanning-tree, which means, the group of edges with the minimum sum of their weights that connect the whole graph. +//The graph needs to be connected, because if there are nodes impossible to reach, there are no edges that could connect every node in the graph. +//KA is a Greedy Algorithm, because edges are analysed based on their weights, that is why a Priority Queue is used, to take first those less weighted. +//This implementations below has some changes compared to conventional ones, but they are explained all along the code. + +import java.util.Comparator; +import java.util.HashSet; +import java.util.PriorityQueue; + +public class Kruskal { + + //Complexity: O(E log V) time, where E is the number of edges in the graph and V is the number of vertices + + private static class Edge{ + private int from; + private int to; + private int weight; + + public Edge(int from, int to, int weight) { + this.from = from; + this.to = to; + this.weight = weight; + } + } + + private static void addEdge (HashSet[] graph, int from, int to, int weight) { + graph[from].add(new Edge(from, to, weight)); + } + + public static void main(String[] args) { + HashSet[] graph = new HashSet[7]; + for (int i = 0; i < graph.length; i++) { + graph[i] = new HashSet<>(); + } + addEdge(graph,0, 1, 2); + addEdge(graph,0, 2, 3); + addEdge(graph,0, 3, 3); + addEdge(graph,1, 2, 4); + addEdge(graph,2, 3, 5); + addEdge(graph,1, 4, 3); + addEdge(graph,2, 4, 1); + addEdge(graph,3, 5, 7); + addEdge(graph,4, 5, 8); + addEdge(graph,5, 6, 9); + + System.out.println("Initial Graph: "); + for (int i = 0; i < graph.length; i++) { + for (Edge edge: graph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } + } + + Kruskal k = new Kruskal(); + HashSet[] solGraph = k.kruskal(graph); + + System.out.println("\nMinimal Graph: "); + for (int i = 0; i < solGraph.length; i++) { + for (Edge edge: solGraph[i]) { + System.out.println(i + " <-- weight " + edge.weight + " --> " + edge.to); + } + } + } + + public HashSet[] kruskal (HashSet[] graph) { + int nodes = graph.length; + int [] captain = new int [nodes]; + //captain of i, stores the set with all the connected nodes to i + HashSet[] connectedGroups = new HashSet[nodes]; + HashSet[] minGraph = new HashSet[nodes]; + PriorityQueue edges = new PriorityQueue<>((Comparator.comparingInt(edge -> edge.weight))); + for (int i = 0; i < nodes; i++) { + minGraph[i] = new HashSet<>(); + connectedGroups[i] = new HashSet<>(); + connectedGroups[i].add(i); + captain[i] = i; + edges.addAll(graph[i]); + } + int connectedElements = 0; + //as soon as two sets merge all the elements, the algorithm must stop + 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)) { + //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 + connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); + //add Edge to minimal graph + addEdge(minGraph, edge.from, edge.to, edge.weight); + //count how many elements have been merged + connectedElements = connectedGroups[captain[edge.from]].size(); + } + } + return minGraph; + } +} diff --git a/DataStructures/Graphs/MatrixGraphs.java b/DataStructures/Graphs/MatrixGraphs.java index e7fb9cc4fb2f..32a7c990e3ef 100644 --- a/DataStructures/Graphs/MatrixGraphs.java +++ b/DataStructures/Graphs/MatrixGraphs.java @@ -127,8 +127,7 @@ public boolean removeEdge(int from, int to) { * @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/HashMap/Hashing/Intersection b/DataStructures/HashMap/Hashing/Intersection new file mode 100644 index 000000000000..8b54eeae1a95 --- /dev/null +++ b/DataStructures/HashMap/Hashing/Intersection @@ -0,0 +1,64 @@ +package DataStructures.HashMap.Hashing; +/* +* this is algo which implies common mathematical set theory concept +* called intersection in which result is common values of both the sets +* here metaphor of sets is HashMap + + +Test Case: + Scanner scn=new Scanner(System.in); + int len =scn.nextInt(); + int arr[]=new int[len]; + int arr2[]=new int[len]; + + for(int i=0;i<2*len;i++) { + + if(i=len) { + arr2[i-len]=scn.nextInt(); + } + } + System.out.println(Main(arr,arr2)); + + + +*/ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; + +public class Intersection { + + public static ArrayList Main(int arr[],int arr2[]) { + HashMap hmap=new HashMap<>(); + HashMap hmap2=new HashMap<>(); + for(int i=0;i res=new ArrayList<>(); + for(int i=0;i0) { + int val=hmap.get(arr2[i]); + hmap.put(arr2[i],val-1); + res.add(arr2[i]); + } + + } + return res; + } + public Intersection() { + + } + + + +} diff --git a/DataStructures/HashMap/Hashing/LinkedList.java b/DataStructures/HashMap/Hashing/LinkedList.java deleted file mode 100644 index 4953551f7040..000000000000 --- a/DataStructures/HashMap/Hashing/LinkedList.java +++ /dev/null @@ -1,63 +0,0 @@ -package DataStructures.HashMap.Hashing; - -class LinkedList { - - private Node Head; - private int size; - - public LinkedList() { - Head = null; - size = 0; - } - - public void insert(int data) { - - Node newnode = new Node(data); - - size++; - - if(Head == null) { - Head = newnode; - } - else { - newnode.next = Head; - Head = newnode; - } - } - - public void delete(int data) { - if(size == 0) { - System.out.println("UnderFlow!"); - return; - } - - else { - Node curr = Head; - if (curr.data == data) { - Head = curr.next; - size--; - return; - } - else { - - while(curr.next.next != null) { - if(curr.next.data == data){ - curr.next = curr.next.next; - return; - } - } - - System.out.println("Key not Found"); - } - } - } - - public void display() { - Node temp = Head; - while(temp != null) { - System.out.printf("%d ",temp.data); - temp = temp.next; - } - System.out.println(); - } -} \ No newline at end of file diff --git a/DataStructures/HashMap/Hashing/Node.java b/DataStructures/HashMap/Hashing/Node.java deleted file mode 100644 index 74ab01f9d2a9..000000000000 --- a/DataStructures/HashMap/Hashing/Node.java +++ /dev/null @@ -1,11 +0,0 @@ -package DataStructures.HashMap.Hashing; - -class Node { - int data; - Node next; - - public Node(int data) { - this.data = data; - this.next = null; - } -} \ No newline at end of file diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index 113146012918..028d9b3e67de 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -117,7 +117,21 @@ public String toString() { * @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 fed09bcba045..3945caa97fde 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -49,9 +49,9 @@ private void swap(int index1, int index2) { // 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 void deleteElement(int elementIndex) { 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 4b435e6d81d7..39ee6ebf7b8f 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -44,9 +44,9 @@ private void swap(int index1, int index2) { // 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 void deleteElement(int elementIndex) { 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 67235172dfb7..b46441a1fa47 100644 --- a/DataStructures/Lists/CircleLinkedList.java +++ b/DataStructures/Lists/CircleLinkedList.java @@ -14,7 +14,7 @@ private Node(E value, Node next) { //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 e1b0041dda39..706b33c7e10d 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -86,9 +86,12 @@ public void insertTail(int x) { 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 Link deleteHead() { 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/Lists/ListAddnFun b/DataStructures/Lists/ListAddnFun new file mode 100644 index 000000000000..afbd2ae431d8 --- /dev/null +++ b/DataStructures/Lists/ListAddnFun @@ -0,0 +1,141 @@ +package DataStructures.Lists; + +/* + * This class implements a SinglyLinked List. + * A linked list is similar to an array, it hold values. + * However, links in a linked list do not have indexes. With + * a linked list you do not need to predetermine it's size as + * it grows and shrinks as it is edited. + *it has functions called mid that gives node at mid + * in addn to linked list there is algo that + * construct a linked list with alternate sums of linked list + * and added to new one and add mid value + * i.e sum of first and last value of inital list + + Test Case: + + + LinkedList LL1 = new LinkedList(); + Scanner scn=new Scanner(System.in); + int numNodes=scn.nextInt(); + for(int i=0;i<2*numNodes;i++) { + LL1.addLast(scn.nextInt()); + } + LL1.display(); + LinkedList LL2=new LinkedList(); + LL2.formLL2(LL1); + LL2.display(); + LinkedList LL3=new LinkedList(); + LL3.formLL3(LL1); + LL3.display(); + Node MID=LL1.midValue(); + System.out.println(MID.data); + LinkedList updLL1=new LinkedList(); + updLL1.formRes(LL1,LL2,LL3,MID); + updLL1.display(); + updLL1.Size(); + + */ + + + +import java.util.*; +import java.lang.*; +import java.io.*; +class LinkedList { + private class Node{ + int data; + Node next; + + Node(int data) { + this.data = data; + this.next = null; + } + } + public Node head = null; + public Node tail = null; + private int size=0; + + public void addLast(int data) { + Node newNode = new Node(data); + + if(this.head == null) { + this.head = newNode; + this.tail = newNode; + this.size++; + } + else { + this.tail.next = newNode; + this.tail = newNode; + this.size++; + } + } + + + public void display() { + Node current = this.head; + if(this.head == null) { + return; + } + while(current != null) { + System.out.print(current.data + " "); + current = current.next; + } + System.out.println(); + } + + public void formLL2(LinkedList LL1) { + Node current=LL1.head; + while(current.next!=null&¤t.next.next!=null) { + int sum=current.data+current.next.next.data; + this.addLast(sum); + current=current.next.next; + } + } + public void formLL3(LinkedList LL1) { + Node current=LL1.head.next; + while(current.next!=null&¤t.next.next!=null) { + int sum=current.data+current.next.next.data; + this.addLast(sum); + current=current.next.next; + } + } + public Node mid() { + Node slow=this.head; + Node fast=this.head; + while(fast.next!=null && fast.next.next!=null) { + slow=slow.next; + fast=fast.next.next; + } + return slow; + } + public Node midValue() { + int sum=this.head.data+this.tail.data; + Node mid=new Node(sum); + return mid; + } + public void formRes(LinkedList LL1,LinkedList LL2,LinkedList LL3,Node MID) { + Node LL1mid=LL1.mid(); + Node currentLL1=LL1.head; + Node currentLL2=LL2.head; + Node currentLL3=LL3.head; + while(currentLL1!=null) { + this.addLast(currentLL1.data); + + if(currentLL2!=null) { + this.addLast(currentLL2.data); + currentLL2=currentLL2.next; + }else if(currentLL1.equals(LL1mid)) { + this.addLast(MID.data); + } + else if(currentLL2==null&¤tLL3!=null) { + this.addLast(currentLL3.data); + currentLL3=currentLL3.next; + } + currentLL1=currentLL1.next; + } + } + public void Size() { + System.out.println(this.size); + } + } diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java index 616e6a1e1548..0f1d58686b0d 100644 --- a/DataStructures/Stacks/NodeStack.java +++ b/DataStructures/Stacks/NodeStack.java @@ -74,7 +74,7 @@ public void push(Item item) { } 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 Item pop() { 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/AVLSimple b/DataStructures/Trees/AVLSimple new file mode 100644 index 000000000000..ace0c46b9374 --- /dev/null +++ b/DataStructures/Trees/AVLSimple @@ -0,0 +1,137 @@ + +package DataStructures.Trees; + +/* +* Avl is algo that balance itself while adding new alues to tree +* by rotating branches of binary tree and make itself Binary seaarch tree +* there are four cases which has to tackle +* rotating - left right ,left left,right right,right left + +Test Case: + +AVLTree tree=new AVLTree(); + tree.insert(20); + tree.insert(25); + tree.insert(30); + tree.insert(10); + tree.insert(5); + tree.insert(15); + tree.insert(27); + tree.insert(19); + tree.insert(16); + + tree.display(); + + + + +*/ + + + +public class AVLTree { + private class Node{ + int data; + int height; + Node left; + Node right; + Node(int data){ + this.data=data; + this.height=1; + } + + } + private Node root; + public void insert(int data) { + this.root=insert(this.root,data); + } + private Node insert(Node node,int item) { + if(node==null) { + Node add=new Node(item); + return add; + } + if(node.data>item) { + node.left=insert(node.left,item); + } + if(node.data1&&itemnode.right.data) + return leftRotate(node); + //RL case + if(bf<-1&&item1&&item>node.left.data) { + node.left=leftRotate(node.left); + return rightRotate(node); + } + + return node; + } + public void display() { + this.display(this.root); + System.out.println(this.root.height); + } + private void display (Node node) { + String str=""; + if(node.left!=null) + str+=node.left.data+"=>"; + else + str+="END=>"; + str+=node.data+""; + if(node.right!=null) + str+="<="+node.right.data; + else + str+="<=END"; + System.out.println(str); + if(node.left!=null) + display(node.left); + if(node.right!=null) + display(node.right); + } + private int height(Node node) { + if(node==null) { + return 0; + } + return node.height; + + } + private int bf(Node node) { + if(node==null) + return 0; + return height(node.left)-height(node.right); + } + + private Node rightRotate(Node c) { + Node b=c.left; + Node T3=b.right; + + b.right=c; + c.left=T3; + c.height=Math.max(height(c.left),height(c.right))+1; + b.height=Math.max(height(b.left),height(b.right))+1; + return b; + + } + private Node leftRotate(Node c) { + Node b=c.right; + Node T3=b.left; + + b.left=c; + c.right=T3; + c.height=Math.max(height(c.left),height(c.right))+1; + b.height=Math.max(height(b.left),height(b.right))+1; + return b; + + } + +} diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index bcf172495d13..69e65fe64089 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -15,8 +15,8 @@ public Node(int item) { // 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 d43d62d68f5f..5f85f987d673 100644 --- a/DataStructures/Trees/LevelOrderTraversalQueue.java +++ b/DataStructures/Trees/LevelOrderTraversalQueue.java @@ -19,11 +19,9 @@ public Node(int item) { } } - 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 a1a737fe4fe9..ba50c079eac4 100644 --- a/DataStructures/Trees/ValidBSTOrNot.java +++ b/DataStructures/Trees/ValidBSTOrNot.java @@ -13,14 +13,13 @@ public Node(int item) { } //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/BoardPath b/DynamicProgramming/BoardPath new file mode 100644 index 000000000000..5ca14d1fab9b --- /dev/null +++ b/DynamicProgramming/BoardPath @@ -0,0 +1,77 @@ +package DynamicProgramming; +/* +* this is an important Algo in which +* we have starting and ending of board and we have to reach +* we have to count no. of ways +* that help to reach end point i.e number by rolling dice +* which have 1 to 6 digits + +Test Case: +here target is 10 + +int n=10; + startAlgo(); + System.out.println(bpR(0,n)); + System.out.println(endAlgo()+"ms"); + int[] strg=new int [n+1]; + startAlgo(); + System.out.println(bpRS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + startAlgo(); + System.out.println(bpIS(0,n,strg)); + System.out.println(endAlgo()+"ms"); + + + +*/ +public class BoardPath { + public static long startTime; + public static long endTime; + public static void startAlgo() { + startTime=System.currentTimeMillis(); + } + public static long endAlgo() { + endTime=System.currentTimeMillis(); + return endTime-startTime; + } + public static int bpR(int start,int end){ + if(start==end) { + return 1; + } + else if(start>end) + return 0; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpR(start+dice,end); + } + return count; + } + public static int bpRS(int curr,int end,int strg[]){ + if(curr==end) { + return 1; + } + else if(curr>end) + return 0; + if(strg[curr]!=0) + return strg[curr]; + int count=0; + for(int dice=1;dice<=6;dice++) { + count+=bpRS(curr+dice,end,strg); + } + strg[curr]=count; + return count; + } + public static int bpIS(int curr,int end,int[]strg){ + strg[end]=1; + for(int i=end-1;i>=0;i--) { + int count=0; + for(int dice=1;dice<=6&&dice+i>> 1; if (ar[m] >= key) r = m; else diff --git a/DynamicProgramming/MatrixChainMultiplication.java b/DynamicProgramming/MatrixChainMultiplication.java index 66b2a35824e2..9073400d3299 100644 --- a/DynamicProgramming/MatrixChainMultiplication.java +++ b/DynamicProgramming/MatrixChainMultiplication.java @@ -25,7 +25,7 @@ public static void main(String[] args) { 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/DynamicProgramming/Minimum sum partition b/DynamicProgramming/Minimum sum partition new file mode 100644 index 000000000000..3763d5bd68a8 --- /dev/null +++ b/DynamicProgramming/Minimum sum partition @@ -0,0 +1,78 @@ +// Partition a set into two subsets such that the difference of subset sums is minimum + +/* +Input: arr[] = {1, 6, 11, 5} +Output: 1 +Explanation: +Subset1 = {1, 5, 6}, sum of Subset1 = 12 +Subset2 = {11}, sum of Subset2 = 11 + +Input: arr[] = {36, 7, 46, 40} +Output: 23 +Explanation: +Subset1 = {7, 46} ; sum of Subset1 = 53 +Subset2 = {36, 40} ; sum of Subset2 = 76 + */ + +import java.util.*; +import java.lang.*; +import java.io.*; +class GFG + { + public static void main (String[] args) + { + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(); + while(t-->0) + { + int n=sc.nextInt(); + int arr[]=new int[n]; + int sum=0; + for(int i=0;i 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/Maths/ParseInteger.java b/Maths/ParseInteger.java index 91177bb49dd6..c9c11528c1dc 100644 --- a/Maths/ParseInteger.java +++ b/Maths/ParseInteger.java @@ -16,7 +16,7 @@ public static void main(String[] args) { * @throws NumberFormatException if the {@code string} does not contain a parsable integer. */ public static int parseInt(String s) { - if (s == null) { + if (s == null || s.length() == 0) { throw new NumberFormatException("null"); } boolean isNegative = s.charAt(0) == '-'; diff --git a/Others/3 sum.java b/Others/3 sum.java new file mode 100644 index 000000000000..5723ba49c34e --- /dev/null +++ b/Others/3 sum.java @@ -0,0 +1,60 @@ +package Others; + +import java.util.Scanner; +import java.util.Arrays; + +/** + * To find triplet equals to given sum in complexity O(n*log(n)) + * + * + * Array must be sorted + * + * @author Ujjawal Joshi + * @date 2020.05.18 + * + * Test Cases: + Input: + * 6 //Length of array + 12 3 4 1 6 9 + target=24 + * Output:3 9 12 + * Explanation: There is a triplet (12, 3 and 9) present + in the array whose sum is 24. + * + * + + */ + + +class threesum{ + public static void main(String args[]) + { + Scanner sc =new Scanner(System.in); + int n=sc.nextInt(); //Length of an array + + int a[]=new int[n]; + + for(int i=0;i - * 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/Rotation of array without using extra space.java b/Others/Rotation of array without using extra space.java new file mode 100644 index 000000000000..76380be37300 --- /dev/null +++ b/Others/Rotation of array without using extra space.java @@ -0,0 +1,75 @@ +package Others; + +import java.util.*; + +/** + * Rotation of array without using extra space + * + * + * @author Ujjawal Joshi + * @date 2020.05.18 + * + * Test Cases: + + Input: + 2 //Size of matrix + 1 2 + 3 4 + Output: + 3 1 + 4 2 + ------------------------------ + Input: + 3 //Size of matrix + 1 2 3 + 4 5 6 + 7 8 9 + Output: + 7 4 1 + 8 5 2 + 9 6 3 + * + */ + +class main{ + public static void main(String[] args) + { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int a[][]=new int[n][n]; + + for(int i=0;i getDictionary() { } 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 7d35ed36d54f..db31959558a3 100644 --- a/Others/TowerOfHanoi.java +++ b/Others/TowerOfHanoi.java @@ -12,7 +12,7 @@ public static void shift(int n, String startPole, String intermediatePole, Strin // 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/README.md b/README.md index 80b5888a5165..d2a467239faa 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # The Algorithms - Java [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/TheAlgorithms/100) +[![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)  NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we're trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info. diff --git a/Searches/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java index 8df51a7d789b..5a3a6d9e11cc 100644 --- a/Searches/IterativeBinarySearch.java +++ b/Searches/IterativeBinarySearch.java @@ -40,7 +40,7 @@ public > int find(T[] array, T key) { 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/BubbleSort.java b/Sorts/BubbleSort.java index 9d2f371786d8..7df1fae8a392 100644 --- a/Sorts/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -13,7 +13,7 @@ class BubbleSort implements SortAlgorithm { * This method implements the Generic Bubble Sort * * @param array The array to be sorted - * Sorts the array in increasing order + * Sorts the array in ascending order **/ @Override @@ -21,7 +21,7 @@ public > T[] sort(T[] array) { for (int i = 0, size = array.length; i < size - 1; ++i) { boolean swapped = false; for (int j = 0; j < size - 1 - i; ++j) { - if (less(array[j], array[j + 1])) { + if (greater(array[j], array[j + 1])) { swap(array, j, j + 1); swapped = true; } @@ -41,12 +41,12 @@ public static void main(String[] args) { BubbleSort bubbleSort = new BubbleSort(); bubbleSort.sort(integers); - // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1 + // Output => 1, 4, 6, 9, 12, 23, 54, 78, 231 print(integers); // String Input String[] strings = {"c", "a", "e", "b", "d"}; - //Output => e, d, c, b, a + //Output => a, b, c, d, e print(bubbleSort.sort(strings)); } diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java new file mode 100644 index 000000000000..1d2e94ff2d58 --- /dev/null +++ b/Sorts/BucketSort.java @@ -0,0 +1,72 @@ +package Sorts; + +import java.util.Random; + +public class BucketSort +{ + static int[] sort(int[] sequence, int maxValue) + { + // Bucket Sort + int[] Bucket = new int[maxValue + 1]; + int[] sorted_sequence = new int[sequence.length]; + + for (int i = 0; i < sequence.length; i++) + Bucket[sequence[i]]++; + + int outPos = 0; + for (int i = 0; i < Bucket.length; i++) + for (int j = 0; j < Bucket[i]; j++) + sorted_sequence[outPos++] = i; + + return sorted_sequence; + } + + static void printSequence(int[] sorted_sequence) + { + for (int i = 0; i < sorted_sequence.length; i++) + System.out.print(sorted_sequence[i] + " "); + } + + static int maxValue(int[] sequence) + { + int maxValue = 0; + for (int i = 0; i < sequence.length; i++) + if (sequence[i] > maxValue) + maxValue = sequence[i]; + return maxValue; + } + + public static void main(String args[]) + { + System.out.println("Sorting of randomly generated numbers using BUCKET SORT"); + Random random = new Random(); + int N = 20; + int[] sequence = new int[N]; + + for (int i = 0; i < N; i++) + sequence[i] = Math.abs(random.nextInt(100)); + + int maxValue = maxValue(sequence); + + System.out.println("\nOriginal Sequence: "); + printSequence(sequence); + + System.out.println("\nSorted Sequence: "); + printSequence(sort(sequence, maxValue)); + } +} + + +/* +#Output: + +$ javac Bucket_Sort.java +$ java Bucket_Sort + +Sorting of randomly generated numbers using BUCKET SORT + +Original Sequence: +95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66 +Sorted Sequence: +8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95 +*/ diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java index 47f79de0c35d..ef564ac722cb 100644 --- a/Sorts/QuickSort.java +++ b/Sorts/QuickSort.java @@ -64,7 +64,7 @@ private static > int randomPartition(T[] array, int left **/ 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/Sorts/SelectionSort.java b/Sorts/SelectionSort.java index e6b7c8833f43..31b16c5bb171 100644 --- a/Sorts/SelectionSort.java +++ b/Sorts/SelectionSort.java @@ -10,10 +10,12 @@ public class SelectionSort implements SortAlgorithm { /** * This method swaps the two elements in the array + * @param * @param arr, i, j The array for the swap and the indexes of the to-swap elements */ - public void swap(T[] arr, int i, int j) { + + public void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; diff --git a/Sorts/SortUtils.java b/Sorts/SortUtils.java index d5f592ad984d..334e3c1c1ad5 100644 --- a/Sorts/SortUtils.java +++ b/Sorts/SortUtils.java @@ -26,11 +26,11 @@ static boolean swap(T[] array, int idx, int idy) { /** - * This method checks if first element is less then the other element + * This method checks if first element is less than the other element * * @param v first element * @param w second element - * @return true if the first element is less then the second element + * @return true if the first element is less than the second element */ static > boolean less(T v, T w) { return v.compareTo(w) < 0; @@ -38,7 +38,19 @@ static > boolean less(T v, T w) { /** - * Just print list + * This method checks if first element is greater than the other element + * + * @param v first element + * @param w second element + * @return true if the first element is greater than the second element + */ + static > boolean greater(T v, T w) { + return v.compareTo(w) > 0; + } + + + /** + * Prints a list * * @param toPrint - a list which should be printed */ @@ -55,7 +67,7 @@ static void print(List toPrint) { /** * Prints an array * - * @param toPrint - the array which should be printed + * @param toPrint - an array which should be printed */ static void print(Object[] toPrint) { System.out.println(Arrays.toString(toPrint)); diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java index cec0ddce0065..76893f45327e 100644 --- a/ciphers/Caesar.java +++ b/ciphers/Caesar.java @@ -125,6 +125,8 @@ public static void main(String[] args) { 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 26acc628e393..60af4ff5429c 100644 --- a/ciphers/ColumnarTranspositionCipher.java +++ b/ciphers/ColumnarTranspositionCipher.java @@ -117,7 +117,7 @@ private static Object[][] tableBuilder(String word) { * 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 375d3e1a949c..67ebe89b8628 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 double closestPair(final Location[] a, final int indexNum) { 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 double closestPair(final Location[] a, final int indexNum) { 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 double closestPair(final Location[] a, final int indexNum) { } } } - secondCount = 0; + ClosestPair.setSecondCount(0); return minValue; } @@ -288,7 +297,7 @@ public double bruteForce(final Location[] arrayParam) { 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 double bruteForce(final Location[] arrayParam) { minValue = length; if (length < minNum) { // Registering final coordinate - minNum = length; + ClosestPair.setMinNum(length); point1 = arrayParam[i]; point2 = arrayParam[j]; }