diff --git a/ClosestPair/ClosestPair.java b/ClosestPair/ClosestPair.java deleted file mode 100644 index 760ef7fd0c5d..000000000000 --- a/ClosestPair/ClosestPair.java +++ /dev/null @@ -1,211 +0,0 @@ -import java.io.*; -import java.util.*; - -public class ClosestPair { - static int count = 0;// array length - static int secondCount = 0;// array length - static Location array[] = new Location[10000]; - static Location point1 = null; // Minimum point coordinate - static Location point2 = null; // Minimum point coordinate - static double minNum = Double.MAX_VALUE;// Minimum point length - - private static class Location { // Location class - double x = 0, y = 0; - - public Location(double x, double y) { //Save x, y coordinates - this.x = x; - this.y = y; - } - } - - public static int xPartition(Location[] a, int first, int last) { // x-axis Quick Sorting - Location pivot = a[last]; // pivot - int pIndex = last; - int i = first - 1; - Location temp; // Temporarily store the value for position transformation - for (int j = first; j <= last - 1; j++) { - if (a[j].x <= pivot.x) { // Less than or less than pivot - i++; - temp = a[i]; // array[i] <-> array[j] - a[i] = a[j]; - a[j] = temp; - } - } - i++; - temp = a[i];// array[pivot] <-> array[i] - a[i] = a[pIndex]; - a[pIndex] = temp; - return i;// pivot index - } - public static int yPartition(Location[] a, int first, int last) { //y-axis Quick Sorting - Location pivot = a[last]; // pivot - int pIndex = last; - int i = first - 1; - Location temp; // Temporarily store the value for position transformation - for (int j = first; j <= last - 1; j++) { - if (a[j].y <= pivot.y) { // Less than or less than pivot - i++; - temp = a[i]; // array[i] <-> array[j] - a[i] = a[j]; - a[j] = temp; - } - } - i++; - temp = a[i];// array[pivot] <-> array[i] - a[i] = a[pIndex]; - a[pIndex] = temp; - return i;// pivot index - } - - public static void xQuickSort(Location[] a, int first, int last) { //x-axis Quick Sorting - if (first < last) { - int q = xPartition(a, first, last); // pivot - xQuickSort(a, first, q - 1); // Left - xQuickSort(a, q + 1, last); // Right - } - } - - public static void yQuickSort(Location[] a, int first, int last) { //y-axis Quick Sorting - if (first < last) { - int q = yPartition(a, first, last); // pivot - yQuickSort(a, first, q - 1); // Left - yQuickSort(a, q + 1, last); // Right - } - } - - public static double closestPair(Location[] a, int indexNum, int first, int last) {// closestPair - Location divideArray[] = new Location[indexNum]; // array stored before divide - System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy from previous array - - int totalNum = indexNum; // number of coordinates in the divideArray array - int divideX = indexNum / 2; // Intermediate value for divide - Location leftArray[] = new Location[divideX]; //divide - left array - Location rightArray[] = new Location[totalNum - divideX]; //divide - right array - - if (indexNum <= 3) { // If the number of coordinates is 3 or less - return bruteForce(divideArray); - } - System.arraycopy(divideArray, 0, leftArray, 0, divideX); //divide - left array - System.arraycopy(divideArray, divideX, rightArray, 0, totalNum - divideX); //divide - right array - - double minLeftArea = 0; //Minimum length of left array - double minRightArea = 0; //Minimum length of right array - double minValue = 0; //Minimum lengt - - minLeftArea = closestPair(leftArray, divideX, 0, divideX - 1); // recursive closestPair - minRightArea = closestPair(rightArray, totalNum - divideX, divideX, totalNum - divideX - 1); - minValue = Math.min(minLeftArea, minRightArea);// window size (= minimum length) - - // Create window - for (int i = 0; i < totalNum; i++) { // Set the size for creating a window and creating a new array for the coordinates in the window - double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); - if (xGap < minValue) { - secondCount++; // size of the array - } else { - if (divideArray[i].x > divideArray[divideX].x) { - break; - } - } - } - Location firstWindow[] = new Location[secondCount]; // new array for coordinates in window - int k = 0; - for (int i = 0; i < totalNum; i++) { - double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); - if (xGap < minValue) { // if it's inside a window - firstWindow[k] = divideArray[i]; // put in an array - k++; - } else { - if (divideArray[i].x > divideArray[divideX].x) { - break; - } - } - } - yQuickSort(firstWindow, 0, secondCount - 1);// Sort by y coordinates - / * Coordinates in Window * / - double length = 0; - for (int i = 0; i < secondCount - 1; i++) { // size comparison within window - for (int j = (i + 1); j < secondCount; j++) { - double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x); - double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y); - if (yGap < minValue) { - length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); - if (length < minValue) { // If the measured distance is less than the current minimum distance - minValue = length;// Change minimum distance to current distance - if (length < minNum) { // Conditional statement for registering final coordinate - minNum = length; - point1 = firstWindow[i]; - point2 = firstWindow[j]; - } - } - } - else - break; - } - } - secondCount = 0; - return minValue; - } - - public static double bruteForce(Location[] array) { // When the number of coordinates is less than 3 - double minValue = Double.MAX_VALUE; // minimum distance - double length = 0; - double xGap = 0, yGap = 0; // Difference between x, y coordinates - if (array.length == 2) { // When there are two coordinates - xGap = (array[0].x - array[1].x); // Difference between x coordinates - yGap = (array[0].y - array[1].y); // Difference between y coordinates - length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // distance between coordinates - if (length < minNum) { // Conditional statement for registering final coordinate - minNum = length; - point1 = array[0]; - point2 = array[1]; - } - return length; - } else if (array.length == 3) { // When there are 3 coordinates - for (int i = 0; i < array.length - 1; i++) { - for (int j = (i + 1); j < array.length; j++) { - xGap = (array[i].x - array[j].x); // Difference between x coordinates - yGap = (array[i].y - array[j].y); // Difference between y coordinates - length = (double) Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); // distance between coordinates - if (length < minValue) { // If the measured distance is less than the current minimum distance - minValue = length; // Change minimum distance to current distance - if (length < minNum) { // Conditional statement for registering final coordinate - minNum = length; - point1 = array[i]; - point2 = array[j]; - } - } - } - } - return minValue; - } - return minValue; - } - - public static void main(String[] args) throws IOException { - // TODO Auto-generated method stub - StringTokenizer token; - - BufferedReader in = new BufferedReader(new FileReader("closest_data.txt")); - //Input data consists of one x-coordinate and one y-coordinate - String ch; - - System.out.println("Input data"); - while ((ch = in.readLine()) != null) { - token = new StringTokenizer(ch, " "); - - array[count] = new Location(Double.parseDouble(token.nextToken()), Double.parseDouble(token.nextToken())); // put in an array - count++; // the number of coordinates actually in the array - System.out.println("x: "+array[count - 1].x + ", y: " + array[count - 1].y); - } - - xQuickSort(array, 0, count - 1); // Sorting by x value - - double result; // minimum distance - result = closestPair(array, count, 0, count - 1); // ClosestPair start - System.out.println("Output Data");// minimum distance coordinates and distance output - System.out.println("(" + point1.x + ", " + point1.y + ")"); - System.out.println("(" + point2.x + ", " + point2.y + ")"); - System.out.println("Minimum Distance : " + result); - - } -} diff --git a/ClosestPair/closest_data.txt b/ClosestPair/closest_data.txt deleted file mode 100644 index 8ebef63f4a66..000000000000 --- a/ClosestPair/closest_data.txt +++ /dev/null @@ -1,12 +0,0 @@ -2 3 -2 16 -3 9 -6 3 -7 7 -9 12 -10 11 -15 2 -15 19 -16 11 -17 13 -19 4 diff --git a/DataStructures/HashMap/HashMap.java b/DataStructures/HashMap/HashMap.java deleted file mode 100644 index 1cce6260e52c..000000000000 --- a/DataStructures/HashMap/HashMap.java +++ /dev/null @@ -1,283 +0,0 @@ -<<<<<<< HEAD:Data Structures/HashMap/HashMap.java - - -import java.util.ArrayList; -import java.util.LinkedList; - -public class HashMap { - public class hmnodes{ //HashMap nodes - K key; - V value; - } - - private int size=0; //size of hashmap - private LinkedList buckets[]; //array of addresses of list - - public HashMap(){ - buckets=new LinkedList[4]; //initially create bucket of any size - for(int i=0;i<4;i++) - buckets[i]=new LinkedList<>(); - } - - public void put(K key,V value) throws Exception{ - int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index - int fountAt=find(bi,key); //check if key already exists or not - if(fountAt==-1){ - hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert - temp.key=key; - temp.value=value; - buckets[bi].addLast(temp); - this.size++; - }else{ - buckets[bi].get(fountAt).value=value;//if already exist modify the value - } - - double lambda = (this.size*1.0)/this.buckets.length; - if(lambda>2.0){ - rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0 - } - - return; - } - - - public V get(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return null; - }else{ - return buckets[bi].get(fountAt).value; - } - } - - public V remove(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return null; - }else{ - this.size--; - return buckets[bi].remove(fountAt).value; - } - } - - public boolean containskey(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return false; - }else{ - return true; - } - } - - public int size(){ - return this.size; - } - - - public boolean isempty(){ - return this.size==0; - } - - public ArrayList keyset() throws Exception{ - ArrayList arr=new ArrayList<>(); - for(int i=0;i valueset() throws Exception{ - ArrayList arr=new ArrayList<>(); - for(int i=0;i"+temp.value+"]"); - } - System.out.println(); - } - } - - public int find(int bi,K key) throws Exception{ - for(int i=0;i ob[]= buckets; - buckets=new LinkedList[ob.length*2]; - for(int i=0;i(); - - size = 0; - for(int i=0;i { - public class hmnodes{ //HashMap nodes - K key; - V value; - } - - private int size=0; //size of hashmap - private LinkedList buckets[]; //array of addresses of list - - public HashMap(){ - buckets=new LinkedList[4]; //initially create bucket of any size - for(int i=0;i<4;i++) - buckets[i]=new LinkedList<>(); - } - - public void put(K key,V value) throws Exception{ - int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index - int fountAt=find(bi,key); //check if key already exists or not - if(fountAt==-1){ - hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert - temp.key=key; - temp.value=value; - buckets[bi].addLast(temp); - this.size++; - }else{ - buckets[bi].get(fountAt).value=value;//if already exist modify the value - } - - double lambda = (this.size*1.0)/this.buckets.length; - if(lambda>2.0){ - rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0 - } - - return; - } - - - public V get(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return null; - }else{ - return buckets[bi].get(fountAt).value; - } - } - - public V remove(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return null; - }else{ - this.size--; - return buckets[bi].remove(fountAt).value; - } - } - - public boolean containskey(K key) throws Exception{ - int bi=bucketIndex(key); - int fountAt=find(bi,key); - if(fountAt==-1){ - return false; - }else{ - return true; - } - } - - public int size(){ - return this.size; - } - - - public boolean isempty(){ - return this.size==0; - } - - public ArrayList keyset() throws Exception{ - ArrayList arr=new ArrayList<>(); - for(int i=0;i valueset() throws Exception{ - ArrayList arr=new ArrayList<>(); - for(int i=0;i"+temp.value+"]"); - } - System.out.println(); - } - } - - public int find(int bi,K key) throws Exception{ - for(int i=0;i ob[]= buckets; - buckets=new LinkedList[ob.length*2]; - for(int i=0;i(); - - size = 0; - for(int i=0;i>>>>>> 7e3a8c55c865471a33f6932a022a1059c5243fc3:data_structures/HashMap/HashMap.java diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index c3229d9c336d..27c1a1a24580 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -20,12 +20,24 @@ class DoublyLinkedList{ private Link tail; /** - * Constructor + * Default Constructor */ public DoublyLinkedList(){ head = null; tail = null; } + + /** + * Constructs a list containing the elements of the array + * @param array the array whose elements are to be placed into this list + * @throws NullPointerException if the specified collection is null + */ + public DoublyLinkedList(int[] array){ + if (array == null) throw new NullPointerException(); + for (int i:array) { + insertTail(i); + } + } /** * Insert an element at the head @@ -60,13 +72,12 @@ public void insertTail(int x){ * * @return The new head */ - public Link deleteHead(){ + public void 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) tail = null; - return temp; } /** @@ -74,11 +85,11 @@ public Link deleteHead(){ * * @return The new tail */ - public Link deleteTail(){ + public void deleteTail(){ Link temp = tail; tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null tail.next = null; // 2ndLast(tail) --> null - return temp; + } /** @@ -87,7 +98,7 @@ public Link deleteTail(){ * @param x element to be deleted * @return Link deleted */ - public Link delete(int x){ + public void delete(int x){ Link current = head; while(current.value != x) //Find the position to delete @@ -102,8 +113,7 @@ else if(current == tail) else{ //Before: 1 <--> 2(current) <--> 3 current.previous.next = current.next; // 1 --> 3 current.next.previous = current.previous; // 1 <--> 3 - } - return current; + } } /** @@ -211,4 +221,4 @@ public static void main(String args[]){ myList.insertOrdered(3); myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) --> } -} \ No newline at end of file +} diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 32747cf2830f..d7d721b2ec1c 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -2,10 +2,10 @@ * This class implements a SinglyLinked List. This is done * using SinglyLinkedList class and a LinkForLinkedList Class. * - * A linked list is implar to an array, it hold values. + * 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 gorws and shrinks as it is edited. This is an example of + * it grows and shrinks as it is edited. This is an example of * a singly linked list. Elements can only be added/removed * at the head/front of the list. * @@ -120,7 +120,7 @@ public static void main(String args[]){ /** * This class is the nodes of the SinglyLinked List. - * They consist of a vlue and a pointer to the node + * They consist of a value and a pointer to the node * after them. * * @author Unknown diff --git a/DataStructures/Matrix/MatrixFastPower.java b/DataStructures/Matrix/MatrixFastPower.java new file mode 100644 index 000000000000..19f8528a36ec --- /dev/null +++ b/DataStructures/Matrix/MatrixFastPower.java @@ -0,0 +1,191 @@ +/** + * + * Java implementation of Matrix fast power + * It can calculate the high power of constant Matrix with O( log(K) ) + * where K is the power of the Matrix + * + * In order to do that, Matrix must be square Matrix ( columns equals rows) + * + * Notice : large power of Matrix may cause overflow + * + * + * other Matrix basic operator is based on @author Kyler Smith, 2017 + * + * @author DDullahan, 2018 + * + */ + +class MatrixFastPower { + + /** + * Matrix Fast Power + * + * @param matrix : square Matrix + * @param k : power of Matrix + * @return product + */ + public static Matrix FastPower(Matrix matrix, int k) throws RuntimeException { + + if(matrix.getColumns() != matrix.getRows()) + throw new RuntimeException("Matrix is not square Matrix."); + + int[][] newData = new int[matrix.getColumns()][matrix.getRows()]; + + for(int i = 0; i < matrix.getColumns(); i++) + newData[i][i] = 1; + + Matrix newMatrix = new Matrix(newData), + coMatrix = new Matrix(matrix.data); + + while(k != 0) { + + if((k & 1) != 0) + newMatrix = newMatrix.multiply(coMatrix); + + k >>= 1; + coMatrix = coMatrix.multiply(coMatrix); + + } + + return newMatrix; + } + + public static void main(String[] argv) { + + int[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; + Matrix matrix = new Matrix(data); + + System.out.println("original matrix : "); + System.out.println(matrix.toString()); + + matrix = MatrixFastPower.FastPower(matrix, 5); + + System.out.println("after power : "); + System.out.println(matrix.toString()); + + matrix = MatrixFastPower.FastPower(matrix, 1000000); + + System.out.println("notice, large power may cause overflow : "); + System.out.print(matrix.toString()); + System.out.println("you can use mod to fix that :-) "); + + } +} +class Matrix { + public int[][] data; + + /** + * Constructor for the matrix takes in a 2D array + * + * @param pData + */ + public Matrix(int[][] pData) { + + /** Make a deep copy of the data */ + if(pData.length != 0) { + int[][] newData = new int[pData.length][pData[0].length]; + + for(int i = 0; i < pData.length; i++) + for(int j = 0; j < pData[0].length; j++) + newData[i][j] = pData[i][j]; + + this.data = newData; + } else { + this.data = null; + } + } + + /** + * Returns the element specified by the given location + * + * @param x : x cooridinate + * @param y : y cooridinate + * @return int : value at location + */ + public int getElement(int x, int y) { + return data[x][y]; + } + + /** + * Returns the number of rows in the Matrix + * + * @return rows + */ + public int getRows() { + if(this.data == null) + return 0; + + return data.length; + } + + /** + * Returns the number of rows in the Matrix + * + * @return columns + */ + public int getColumns() { + if(this.data == null) + return 0; + + return data[0].length; + } + + /** + * Multiplies this matrix with another matrix. + * + * @param other : Matrix to be multiplied with + * @return product + */ + public Matrix multiply(Matrix other) throws RuntimeException { + + int[][] newData = new int[this.data.length][other.getColumns()]; + + if(this.getColumns() != other.getRows()) + throw new RuntimeException("The two matrices cannot be multiplied."); + + int sum; + + for (int i = 0; i < this.getRows(); ++i) + for(int j = 0; j < other.getColumns(); ++j) { + sum = 0; + + for(int k = 0; k < this.getColumns(); ++k) { + sum += this.data[i][k] * other.getElement(k, j); + } + + newData[i][j] = sum; + } + + return new Matrix(newData); + } + + /** + * Returns the Matrix as a String in the following format + * + * [ a b c ] ... + * [ x y z ] ... + * [ i j k ] ... + * ... + * + * @return Matrix as String + * TODO: Work formatting for different digit sizes + */ + public String toString() { + String str = ""; + + for(int i = 0; i < this.data.length; i++) { + str += "[ "; + + for(int j = 0; j < this.data[0].length; j++) { + str += data[i][j]; + str += " "; + } + + str += "]"; + str += "\n"; + } + + return str; + } + +} diff --git a/DataStructures/Trees/GenericTree.Java b/DataStructures/Trees/GenericTree.Java index 16ab5fb53b1e..cc592e04082e 100644 --- a/DataStructures/Trees/GenericTree.Java +++ b/DataStructures/Trees/GenericTree.Java @@ -2,7 +2,7 @@ import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; -public class treeclass { +public class GenericTree { private class Node { int data; ArrayList child = new ArrayList<>(); @@ -22,7 +22,7 @@ public class treeclass { I have done this, while calling from main one have to give minimum parameters. */ - public treeclass() { //Constructor + public GenericTree() { //Constructor Scanner scn = new Scanner(System.in); root = create_treeG(null, 0, scn); } diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index 8cb304f18c8f..1f657d92be97 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -37,14 +37,10 @@ int height(Node root) return 0; else { - /* compute height of each subtree */ - int lheight = height(root.left); - int rheight = height(root.right); - - /* use the larger one */ - if (lheight > rheight) - return(lheight+1); - else return(rheight+1); + /** + * Return the height of larger subtree + */ + return Math.max(height(root.left),height(root.right)) + 1; } } @@ -75,4 +71,4 @@ public static void main(String args[]) System.out.println("Level order traversal of binary tree is "); tree.printLevelOrder(); } -} \ No newline at end of file +} diff --git a/Dynamic Programming/CoinChange.java b/Dynamic Programming/CoinChange.java index f4cda7203b7c..e9d3689d9952 100644 --- a/Dynamic Programming/CoinChange.java +++ b/Dynamic Programming/CoinChange.java @@ -10,9 +10,11 @@ public class CoinChange { public static void main(String[] args) { int amount = 12; - int[] coins = {1, 2, 5}; + int[] coins = {2, 4, 5}; System.out.println("Number of combinations of getting change for " + amount + " is: " + change(coins, amount)); + System.out.println("Minimum number of coins required for amount :" + amount + " is: " + minimumCoins(coins, amount)); + } /** @@ -29,7 +31,7 @@ public static int change(int[] coins, int amount) { for (int coin : coins) { for (int i=coin; i= 0 && chars[index] == '(') { + // ()(()) + res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); + } + } + } + max = Math.max(max, res[i]); + } + + return max; + + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + while (true) { + String str = sc.nextLine(); + if ("quit".equals(str)) { + break; + } + int len = getLongestValidParentheses(str); + System.out.println(len); + + } + + sc.close(); + + } + +} diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java new file mode 100644 index 000000000000..b3df65bfd2e3 --- /dev/null +++ b/Others/Dijkstra.java @@ -0,0 +1,171 @@ +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.io.*; +import java.util.*; +public class Dijkstra { + private static final Graph.Edge[] GRAPH = { + new Graph.Edge("a", "b", 7), //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", "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 { + private final Map graph; // mapping of vertex names to Vertex objects, built from a set of Edges + + /** 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; + public int dist = Integer.MAX_VALUE; // MAX_VALUE assumed to be infinity + 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()) { + + u = q.pollFirst(); // vertex with shortest distance (first iteration will return source) + 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(); + } + } +} diff --git a/Others/FibToN.java b/Others/FibToN.java index 1d1efdc1e753..ae2de417aa50 100644 --- a/Others/FibToN.java +++ b/Others/FibToN.java @@ -1,14 +1,22 @@ +/** + * + * Fibonacci sequence, and characterized by the fact that every number + * after the first two is the sum of the two preceding ones. + * + * Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21,... + * + * Source for the explanation: https://en.wikipedia.org/wiki/Fibonacci_number + */ + import java.util.Scanner; public class FibToN { - public static void main(String[] args) { //take input Scanner scn = new Scanner(System.in); int N = scn.nextInt(); - // print fibonacci sequence less than N + // print all Fibonacci numbers that are smaller than your given input N int first = 0, second = 1; - //first fibo and second fibonacci are 0 and 1 respectively scn.close(); while(first <= N){ //print first fibo 0 then add second fibo into it while updating second as well diff --git a/Others/GCD.java b/Others/GCD.java index 08da3805e9d8..58a2b5eef5aa 100644 --- a/Others/GCD.java +++ b/Others/GCD.java @@ -2,29 +2,37 @@ //This is Euclid's algorithm which is used to find the greatest common denominator //Overide function name gcd -public class GCD{ - - public static int gcd(int num1, int num2) { - - int gcdValue = num1 % num2; - while (gcdValue != 0) { - num2 = gcdValue; - gcdValue = num2 % gcdValue; +public class GCD { + + public static int gcd(int num1, int num2) { + + if (num1 == 0) + return num2; + + while (num2 != 0) { + if (num1 > num2) + num1 -= num2; + else + num2 -= num1; } - return num2; + + return num1; } - public static int gcd(int[] number) { - int result = number[0]; - for(int i = 1; i < number.length; i++) - //call gcd function (input two value) - result = gcd(result, number[i]); - - return result; - } - - public static void main(String[] args) { - int[] myIntArray = {4,16,32}; - //call gcd function (input array) - System.out.println(gcd(myIntArray)); + + public static int gcd(int[] number) { + int result = number[0]; + for (int i = 1; i < number.length; i++) + // call gcd function (input two value) + result = gcd(result, number[i]); + + return result; + } + + public static void main(String[] args) { + int[] myIntArray = { 4, 16, 32 }; + + // 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 } } diff --git a/Others/Huffman.java b/Others/Huffman.java index f3ab6c6b5800..0d937271112f 100644 --- a/Others/Huffman.java +++ b/Others/Huffman.java @@ -1,4 +1,3 @@ - import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; @@ -14,24 +13,24 @@ Enter number of distinct letters 6 -Enter letters with its frequncy to encode +Enter letters with its frequency to encode Enter letter : a -Enter frequncy : 45 +Enter frequency : 45 Enter letter : b -Enter frequncy : 13 +Enter frequency : 13 Enter letter : c -Enter frequncy : 12 +Enter frequency : 12 Enter letter : d -Enter frequncy : 16 +Enter frequency : 16 Enter letter : e -Enter frequncy : 9 +Enter frequency : 9 Enter letter : f -Enter frequncy : 5 +Enter frequency : 5 Letter Encoded Form a 0 @@ -64,17 +63,17 @@ public class Huffman { // A simple function to print a given list //I just made it for debugging - public static void print_list(List li){ + public static void print_list(List li){ Iterator it=li.iterator(); while(it.hasNext()){Node n=it.next();System.out.print(n.freq+" ");}System.out.println(); } //Function for making tree (Huffman Tree) - public static Node make_huffmann_tree(List li){ + public static Node make_huffmann_tree(List li){ //Sorting list in increasing order of its letter frequency li.sort(new comp()); Node temp=null; - Iterator it=li.iterator(); + Iterator it=li.iterator(); //System.out.println(li.size()); //Loop for making huffman tree till only single node remains in list while(true){ @@ -89,7 +88,7 @@ public static Node make_huffmann_tree(List li){ //Below condition is to check either list has 2nd node or not to combine //If this condition will be false, then it means construction of huffman tree is completed if(it.hasNext()){b=(Node)it.next();} - //Combining first two smallest nodes in list to make its parent whose frequncy + //Combining first two smallest nodes in list to make its parent whose frequency //will be equals to sum of frequency of these two nodes if(b!=null){ temp.freq=a.freq+b.freq;a.data=0;b.data=1;//assigining 0 and 1 to left and right nodes @@ -109,7 +108,7 @@ public static Node make_huffmann_tree(List li){ //Function for finding path between root and given letter ch public static void dfs(Node n,String ch){ - Stack st=new Stack(); // stack for storing path + Stack st=new Stack(); // stack for storing path int freq=n.freq; // recording root freq to avoid it adding in path encoding find_path_and_encode(st,n,ch,freq); } @@ -140,15 +139,16 @@ public static void main(String args[]){ System.out.println("Enter number of distinct letters "); int n=in.nextInt(); String s[]=new String[n]; - System.out.print("Enter letters with its frequncy to encode\n"); + System.out.print("Enter letters with its frequency to encode\n"); for(int i=0;i 0 && T.charAt(i) != P.charAt(q)) { + while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { q = pi[q - 1]; } - if (T.charAt(i) == P.charAt(q)) { + if (haystack.charAt(i) == needle.charAt(q)) { q++; } @@ -28,11 +29,9 @@ public void KMPmatcher(final String T, final String P) { q = pi[q - 1]; } } - } - // return the prefix function - private int[] computePrefixFunction(final String P) { + private static int[] computePrefixFunction(final String P) { final int n = P.length(); final int[] pi = new int[n]; pi[0] = 0; @@ -49,7 +48,6 @@ private int[] computePrefixFunction(final String P) { pi[i] = q; } - return pi; } -} +} \ No newline at end of file diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java index 1d0f795a3a35..47c02a6c4979 100644 --- a/Others/PerlinNoise.java +++ b/Others/PerlinNoise.java @@ -3,6 +3,7 @@ /** * For detailed info and implementation see: Perlin-Noise + * Algorithm description: https://en.wikipedia.org/wiki/Perlin_noise */ public class PerlinNoise { /** @@ -137,7 +138,7 @@ public static void main(String[] args) { System.out.println("Charset (String): "); charset = in.next(); - + in.close(); perlinNoise = generatePerlinNoise(width, height, octaveCount, persistence, seed); final char[] chars = charset.toCharArray(); final int length = chars.length; diff --git a/Others/ReverseStackUsingRecursion.java b/Others/ReverseStackUsingRecursion.java index 99f1ab3b3954..5346d70ac3ff 100644 --- a/Others/ReverseStackUsingRecursion.java +++ b/Others/ReverseStackUsingRecursion.java @@ -44,8 +44,7 @@ private static void reverseUsingRecursion(Stack stack) { } /* All items are stored in call stack until we reach the end*/ - int temptop=stack.peek(); - stack.pop(); + int temptop=stack.pop(); reverseUsingRecursion(stack); //Recursion call insertAtEnd(temptop); // Insert items held in call stack one by one into stack } @@ -66,5 +65,4 @@ private static void insertAtEnd(int temptop) { } } - -} +} \ No newline at end of file diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java index b792d692f675..8193d89da79b 100644 --- a/Others/RootPrecision.java +++ b/Others/RootPrecision.java @@ -9,20 +9,21 @@ public class RootPrecision { public static void main(String[] args) { //take input Scanner scn = new Scanner(System.in); - - int N = scn.nextInt(); //N is the input number - int P = scn.nextInt(); //P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. - - System.out.println(squareRoot(N, P)); + System.out.println("Enter a number that you wish to get the squareroot from: \n>"); + int Number = scn.nextInt(); //N is the input number + System.out.println("How many decimals do you want in the answer? \n>"); + int Precision = scn.nextInt(); //Precision for eg - 3 in 2.564 and 5 in 3.80870. + scn.close(); + System.out.println(squareRoot(Number, Precision)); } - public static double squareRoot(int N, int P) { + public static double squareRoot(int Number, int Precision) { double rv = 0; //rv means return value - double root = Math.pow(N, 0.5); + double root = Math.pow(Number, 0.5); //calculate precision to power of 10 and then multiply it with root value. - int precision = (int) Math.pow(10, P); + int precision = (int) Math.pow(10, Precision); root = root * precision; /*typecast it into integer then divide by precision and again typecast into double so as to have decimal points upto P precision */ @@ -30,4 +31,4 @@ public static double squareRoot(int N, int P) { rv = (int)root; return (double)rv/precision; } -} +} \ No newline at end of file diff --git a/README.md b/README.md index ce2cdec5e76a..c11c573e3d53 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Java.svg)](https://travis-ci.org/TheAlgorithms/Java) +# The Algorithms - Java + +## A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we are 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. ### All algorithms implemented in Java (for education) diff --git a/SkylineProblem/SkylineProblem.java b/SkylineProblem/SkylineProblem.java index a0b70631a527..121116e16685 100644 --- a/SkylineProblem/SkylineProblem.java +++ b/SkylineProblem/SkylineProblem.java @@ -1,3 +1,9 @@ +/** + * Given n rectangular buildings in a 2-dimensional city, computes the skyline of these buildings, + * eliminating hidden lines. The main task is to view buildings from a side and remove all sections + * that are not visible. + * Source for explanation: https://www.geeksforgeeks.org/the-skyline-problem-using-divide-and-conquer-algorithm/ + */ import java.util.ArrayList; import java.util.Iterator; import java.util.Scanner; diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java new file mode 100644 index 000000000000..93a5d164dd88 --- /dev/null +++ b/divideconquer/ClosestPair.java @@ -0,0 +1,348 @@ +package divideconquer; + +/** + +* For a set of points in a coordinates system (10000 maximum), +* ClosestPair class calculates the two closest points. + +* @author: anonymous +* @author: Marisa Afuera +*/ + + public final class ClosestPair { + + + /** Number of points */ + int numberPoints = 0; + /** Input data, maximum 10000. */ + private Location[] array; + /** Minimum point coordinate. */ + Location point1 = null; + /** Minimum point coordinate. */ + Location point2 = null; + /** Minimum point length. */ + private static double minNum = Double.MAX_VALUE; + /** secondCount */ + private static int secondCount = 0; + + /** + * Constructor. + */ + ClosestPair(int points) { + numberPoints = points; + array = new Location[numberPoints]; + } + + /** + Location class is an auxiliary type to keep points coordinates. + */ + + public static class Location { + + double x = 0; + double y = 0; + + /** + * @param xpar (IN Parameter) x coordinate
+ * @param ypar (IN Parameter) y coordinate
+ */ + + Location(final double xpar, final double ypar) { //Save x, y coordinates + this.x = xpar; + this.y = ypar; + } + + } + + public Location[] createLocation(int numberValues) { + return new Location[numberValues]; + + } + + public Location buildLocation(double x, double y){ + return new Location(x,y); + } + + + /** xPartition function: arrange x-axis. + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index + */ + + public int xPartition( + final Location[] a, final int first, final int last) { + + Location pivot = a[last]; // pivot + int pIndex = last; + int i = first - 1; + Location temp; // Temporarily store value for position transformation + for (int j = first; j <= last - 1; j++) { + if (a[j].x <= pivot.x) { // Less than or less than pivot + i++; + temp = a[i]; // array[i] <-> array[j] + a[i] = a[j]; + a[j] = temp; + } + } + i++; + temp = a[i]; // array[pivot] <-> array[i] + a[i] = a[pIndex]; + a[pIndex] = temp; + return i; // pivot index + } + + /** yPartition function: arrange y-axis. + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ * @return pivot index + */ + + public int yPartition( + final Location[] a, final int first, final int last) { + + Location pivot = a[last]; // pivot + int pIndex = last; + int i = first - 1; + Location temp; // Temporarily store value for position transformation + for (int j = first; j <= last - 1; j++) { + if (a[j].y <= pivot.y) { // Less than or less than pivot + i++; + temp = a[i]; // array[i] <-> array[j] + a[i] = a[j]; + a[j] = temp; + } + } + i++; + temp = a[i]; // array[pivot] <-> array[i] + a[i] = a[pIndex]; + a[pIndex] = temp; + return i; // pivot index + } + + /** xQuickSort function: //x-axis Quick Sorting. + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */ + + public void xQuickSort( + final Location[] a, final int first, final int last) { + + if (first < last) { + int q = xPartition(a, first, last); // pivot + xQuickSort(a, first, q - 1); // Left + xQuickSort(a, q + 1, last); // Right + } + } + + /** yQuickSort function: //y-axis Quick Sorting. + * @param a (IN Parameter) array of points
+ * @param first (IN Parameter) first point
+ * @param last (IN Parameter) last point
+ */ + + public void yQuickSort( + final Location[] a, final int first, final int last) { + + if (first < last) { + int q = yPartition(a, first, last); // pivot + yQuickSort(a, first, q - 1); // Left + yQuickSort(a, q + 1, last); // Right + } + } + + /** closestPair function: find closest pair. + * @param a (IN Parameter) array stored before divide
+ * @param indexNum (IN Parameter) number coordinates divideArray
+ * @return minimum distance
+ */ + + public double closestPair(final Location[] a, final int indexNum) { + + Location[] divideArray = new Location[indexNum]; + System.arraycopy(a, 0, divideArray, 0, indexNum); // Copy previous array + int totalNum = indexNum; // number of coordinates in the divideArray + int divideX = indexNum / 2; // Intermediate value for divide + Location[] leftArray = new Location[divideX]; //divide - left array + //divide-right array + Location[] rightArray = new Location[totalNum - divideX]; + if (indexNum <= 3) { // If the number of coordinates is 3 or less + return bruteForce(divideArray); + } + //divide-left array + System.arraycopy(divideArray, 0, leftArray, 0, divideX); + //divide-right array + System.arraycopy( + divideArray, divideX, rightArray, 0, totalNum - divideX); + + double minLeftArea = 0; //Minimum length of left array + double minRightArea = 0; //Minimum length of right array + double minValue = 0; //Minimum lengt + + minLeftArea = closestPair(leftArray, divideX); // recursive closestPair + minRightArea = closestPair(rightArray, totalNum - divideX); + // window size (= minimum length) + minValue = Math.min(minLeftArea, minRightArea); + + // Create window. Set the size for creating a window + // and creating a new array for the coordinates in the window + 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 + } else { + if (divideArray[i].x > divideArray[divideX].x) { + break; + } + } + } + // new array for coordinates in window + Location[] firstWindow = new Location[secondCount]; + int k = 0; + for (int i = 0; i < totalNum; i++) { + double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x); + if (xGap < minValue) { // if it's inside a window + firstWindow[k] = divideArray[i]; // put in an array + k++; + } else { + if (divideArray[i].x > divideArray[divideX].x) { + break; + } + } + } + yQuickSort(firstWindow, 0, secondCount - 1); // Sort by y coordinates + /* Coordinates in Window */ + double length = 0; + // size comparison within window + for (int i = 0; i < secondCount - 1; i++) { + for (int j = (i + 1); j < secondCount; j++) { + double xGap = Math.abs(firstWindow[i].x - firstWindow[j].x); + double yGap = Math.abs(firstWindow[i].y - firstWindow[j].y); + if (yGap < minValue) { + length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // If measured distance is less than current min distance + if (length < minValue) { + // Change minimum distance to current distance + minValue = length; + // Conditional for registering final coordinate + if (length < minNum) { + minNum = length; + point1 = firstWindow[i]; + point2 = firstWindow[j]; + } + } + } + else { + break; + } + } + } + secondCount = 0; + return minValue; + } + + /** bruteForce function: When the number of coordinates is less than 3. + * @param arrayParam (IN Parameter) array stored before divide
+ * @return
+ */ + + public double bruteForce(final Location[] arrayParam) { + + double minValue = Double.MAX_VALUE; // minimum distance + double length = 0; + double xGap = 0; // Difference between x coordinates + double yGap = 0; // Difference between y coordinates + double result = 0; + + if (arrayParam.length == 2) { + // Difference between x coordinates + xGap = (arrayParam[0].x - arrayParam[1].x); + // Difference between y coordinates + yGap = (arrayParam[0].y - arrayParam[1].y); + // distance between coordinates + length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // Conditional statement for registering final coordinate + if (length < minNum) { + minNum = length; + + } + point1 = arrayParam[0]; + point2 = arrayParam[1]; + result = length; + } + if (arrayParam.length == 3) { + for (int i = 0; i < arrayParam.length - 1; i++) { + for (int j = (i + 1); j < arrayParam.length; j++) { + // Difference between x coordinates + xGap = (arrayParam[i].x - arrayParam[j].x); + // Difference between y coordinates + yGap = (arrayParam[i].y - arrayParam[j].y); + // distance between coordinates + length = + Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2)); + // If measured distance is less than current min distance + if (length < minValue) { + // Change minimum distance to current distance + minValue = length; + if (length < minNum) { + // Registering final coordinate + minNum = length; + point1 = arrayParam[i]; + point2 = arrayParam[j]; + } + } + } + } + result = minValue; + + } + return result; // If only one point returns 0. + } + + /** main function: execute class. + * @param args (IN Parameter)
+ * @throws IOException If an input or output + * exception occurred + */ + + public static void main(final String[] args) { + + //Input data consists of one x-coordinate and one y-coordinate + + ClosestPair cp = new ClosestPair(12); + cp.array[0]=cp.buildLocation(2,3); + cp.array[1]=cp.buildLocation(2,16); + cp.array[2]=cp.buildLocation(3,9); + cp.array[3]=cp.buildLocation(6,3); + cp.array[4]=cp.buildLocation(7,7); + cp.array[5]=cp.buildLocation(19,4); + cp.array[6]=cp.buildLocation(10,11); + cp.array[7]=cp.buildLocation(15,2); + cp.array[8]=cp.buildLocation(15,19); + cp.array[9]=cp.buildLocation(16,11); + cp.array[10]=cp.buildLocation(17,13); + cp.array[11]=cp.buildLocation(9,12); + + System.out.println("Input data"); + System.out.println("Number of points: "+ cp.array.length); + for (int i=0;i