From 161791d4a5759878f53e4ef2e397502d621a8e81 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Wed, 25 Jul 2018 17:07:34 +0200 Subject: [PATCH 01/34] fixed bug in method gcd(int, int) --- Others/GCD.java | 52 ++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 22 deletions(-) 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 } } From 871793bed18823a3aa93a8e86a4100c19946895a Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Wed, 25 Jul 2018 09:16:16 -0700 Subject: [PATCH 02/34] Deleted conflict file for hahsmap --- DataStructures/HashMap/HashMap.java | 283 ---------------------------- 1 file changed, 283 deletions(-) delete mode 100644 DataStructures/HashMap/HashMap.java 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 From 69279375d40bcfc315071ee7b97a926ca105ad43 Mon Sep 17 00:00:00 2001 From: Keshav Date: Mon, 30 Jul 2018 11:16:40 +0800 Subject: [PATCH 03/34] Add method for minimum number of coins required for given amount --- Dynamic Programming/CoinChange.java | 39 +++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 5 deletions(-) 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 Date: Wed, 1 Aug 2018 14:55:26 +0100 Subject: [PATCH 04/34] Remove Tracis CI badge from README.md Removing the Travis CI badge as it points to a dead URL. As this repository has [very few tests](https://github.com/TheAlgorithms/Java/search?q=Test&unscoped_q=Test), maybe a CI build might be a bit too much. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ce2cdec5e76a..2bf743208910 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# The Algorithms - Java [![Build Status](https://travis-ci.org/TheAlgorithms/Java.svg)](https://travis-ci.org/TheAlgorithms/Java) +# The Algorithms - Java ### All algorithms implemented in Java (for education) From 199220db7c291cba01d80f9b6a648575a75e1c48 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 23 Aug 2018 14:16:56 -0700 Subject: [PATCH 05/34] Deleted irrelevant file --- myfile.txt | 1 - 1 file changed, 1 deletion(-) delete mode 100644 myfile.txt diff --git a/myfile.txt b/myfile.txt deleted file mode 100644 index d1b1c0a7ad80..000000000000 --- a/myfile.txt +++ /dev/null @@ -1 +0,0 @@ -ĒĻĄĢ~ \ No newline at end of file From 0a373b5c101ee0cad5912ecbdfab389a7b02f2fa Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 23 Aug 2018 14:20:01 -0700 Subject: [PATCH 06/34] Delete ClosestPair.java --- ClosestPair/ClosestPair.java | 211 ----------------------------------- 1 file changed, 211 deletions(-) delete mode 100644 ClosestPair/ClosestPair.java 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); - - } -} From 5eaf920106343f4311b4c0f58063d8f634701372 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Thu, 23 Aug 2018 14:20:09 -0700 Subject: [PATCH 07/34] Delete closest_data.txt --- ClosestPair/closest_data.txt | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 ClosestPair/closest_data.txt 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 From a1cbd6542fdedb968a9b4b1759b29bd3169ce8e5 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Fri, 24 Aug 2018 10:37:35 -0700 Subject: [PATCH 08/34] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2bf743208910..c11c573e3d53 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # 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) These are for demonstration purposes only. There are many implementations of sorts in the Java standard library that are much better for performance reasons. From 890b9df9e5c96d7872689dcc38282f7f30d59a97 Mon Sep 17 00:00:00 2001 From: JayH2018 <42029911+JayH2018@users.noreply.github.com> Date: Mon, 27 Aug 2018 15:54:52 +0800 Subject: [PATCH 09/34] className is error Bring fileName into correspondence with className which is marked as public --- DataStructures/Trees/GenericTree.Java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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); } From 28deddd5d78064274b76df56126c9a72163ad361 Mon Sep 17 00:00:00 2001 From: JayH2018 <42029911+JayH2018@users.noreply.github.com> Date: Tue, 28 Aug 2018 14:36:56 +0800 Subject: [PATCH 10/34] source coding is a little complex --- DataStructures/Trees/LevelOrderTraversal.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index 8cb304f18c8f..e20753638212 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 larger one; + */ + 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 +} From 2dc86b6a04eaa57dfbea7bac3e80b5d9995b4545 Mon Sep 17 00:00:00 2001 From: Varun Upadhyay Date: Tue, 28 Aug 2018 06:25:55 -0700 Subject: [PATCH 11/34] Update LevelOrderTraversal.java --- DataStructures/Trees/LevelOrderTraversal.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java index e20753638212..1f657d92be97 100644 --- a/DataStructures/Trees/LevelOrderTraversal.java +++ b/DataStructures/Trees/LevelOrderTraversal.java @@ -38,7 +38,7 @@ int height(Node root) else { /** - * return the larger one; + * Return the height of larger subtree */ return Math.max(height(root.left),height(root.right)) + 1; } From f713a5ff9c5fbf2a2ee2b08c9de75a43b800ada7 Mon Sep 17 00:00:00 2001 From: DDullahan Date: Thu, 30 Aug 2018 16:47:17 +0800 Subject: [PATCH 12/34] Added MatrixFastPower.java --- DataStructures/Matrix/MatrixFastPower.java | 139 +++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 DataStructures/Matrix/MatrixFastPower.java diff --git a/DataStructures/Matrix/MatrixFastPower.java b/DataStructures/Matrix/MatrixFastPower.java new file mode 100644 index 000000000000..c2bdcf7cb47d --- /dev/null +++ b/DataStructures/Matrix/MatrixFastPower.java @@ -0,0 +1,139 @@ +import java.util.*; + +/** + * + * 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 Matrix { + private 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); + } + + /** + * Matrix Fast Power + * + * @param k : power of Matrix + * @return product + */ + public Matrix MatrixFastPower(int k) throws RuntimeException { + + if(this.getColumns() != this.getRows()) + throw new RuntimeException("Matrix is not square Matrix."); + + int[][] newData = new int[this.getColumns()][this.getRows()]; + + for(int i = 0; i < this.getColumns(); i++) + newData[i][i] = 1; + + Matrix newMatrix = new Matrix(newData), + coMatrix = new Matrix(this.data); + + while(k != 0) { + + if((k & 1) != 0) + newMatrix = newMatrix.multiply(coMatrix); + + k >>= 1; + coMatrix = coMatrix.multiply(coMatrix); + + } + + return newMatrix; + } +} From 55c179bf19ddcb1c3fcf5e1d6ec56ff6a1788309 Mon Sep 17 00:00:00 2001 From: DDullahan Date: Thu, 30 Aug 2018 21:52:20 +0800 Subject: [PATCH 13/34] Added MatrixFastPower.java with changes --- DataStructures/Matrix/MatrixFastPower.java | 112 +++++++++++++++------ 1 file changed, 82 insertions(+), 30 deletions(-) diff --git a/DataStructures/Matrix/MatrixFastPower.java b/DataStructures/Matrix/MatrixFastPower.java index c2bdcf7cb47d..19f8528a36ec 100644 --- a/DataStructures/Matrix/MatrixFastPower.java +++ b/DataStructures/Matrix/MatrixFastPower.java @@ -1,5 +1,3 @@ -import java.util.*; - /** * * Java implementation of Matrix fast power @@ -14,11 +12,67 @@ * 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 { - private int[][] data; + public int[][] data; /** * Constructor for the matrix takes in a 2D array @@ -106,34 +160,32 @@ public Matrix multiply(Matrix other) throws RuntimeException { } /** - * Matrix Fast Power - * - * @param k : power of Matrix - * @return product - */ - public Matrix MatrixFastPower(int k) throws RuntimeException { - - if(this.getColumns() != this.getRows()) - throw new RuntimeException("Matrix is not square Matrix."); - - int[][] newData = new int[this.getColumns()][this.getRows()]; - - for(int i = 0; i < this.getColumns(); i++) - newData[i][i] = 1; - - Matrix newMatrix = new Matrix(newData), - coMatrix = new Matrix(this.data); - - while(k != 0) { - - if((k & 1) != 0) - newMatrix = newMatrix.multiply(coMatrix); - - k >>= 1; - coMatrix = coMatrix.multiply(coMatrix); + * 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 newMatrix; + return str; } + } From 88f815545832d68ba443a10f3cc0dd8b69f3334f Mon Sep 17 00:00:00 2001 From: Marisa Afuera Date: Thu, 30 Aug 2018 19:36:00 +0200 Subject: [PATCH 14/34] Refactorized ClosestPair.java in order to be compliant with java sun rules commit divideconquer\ClosesPair.java Refactorized ClosestPair.java. Finding nearest cartesian points. Refactorized ClosestPair.java. Finding nearest cartesian points. --- divideconquer/ClosestPair.java | 348 +++++++++++++++++++++++++++++++++ 1 file changed, 348 insertions(+) create mode 100644 divideconquer/ClosestPair.java 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 Date: Fri, 5 Oct 2018 17:21:05 +0800 Subject: [PATCH 15/34] Add Longest Valid Parentheses algorithm(DP) --- .../LongestValidParentheses.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Dynamic Programming/LongestValidParentheses.java diff --git a/Dynamic Programming/LongestValidParentheses.java b/Dynamic Programming/LongestValidParentheses.java new file mode 100644 index 000000000000..14c98020a126 --- /dev/null +++ b/Dynamic Programming/LongestValidParentheses.java @@ -0,0 +1,63 @@ + +import java.util.Scanner; + +/** + * Given a string containing just the characters '(' and ')', find the length of + * the longest valid (well-formed) parentheses substring. + * + * + * @author Libin Yang (https://github.com/yanglbme) + * @since 2018/10/5 + */ + +public class LongestValidParentheses { + + public static int getLongestValidParentheses(String s) { + if (s == null || s.length() < 2) { + return 0; + } + char[] chars = s.toCharArray(); + int n = chars.length; + int[] res = new int[n]; + res[0] = 0; + res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; + + int max = res[1]; + + for (int i = 2; i < n; ++i) { + if (chars[i] == ')') { + if (chars[i - 1] == '(') { + res[i] = res[i - 2] + 2; + } else { + int index = i - res[i - 1] - 1; + if (index >= 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(); + + } + +} From eb01780ae61066dc2b86094464eab2daf0584f8b Mon Sep 17 00:00:00 2001 From: Doru Kesriyeli Date: Sun, 7 Oct 2018 16:55:52 -0700 Subject: [PATCH 16/34] fixed spelling mistakes --- DataStructures/Lists/SinglyLinkedList.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 From ae2029424b99a997c584b388be96c30b7d5a765a Mon Sep 17 00:00:00 2001 From: Doru Kesriyeli Date: Sun, 7 Oct 2018 17:20:32 -0700 Subject: [PATCH 17/34] removed unused return values --- DataStructures/Lists/DoublyLinkedList.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index c3229d9c336d..1d15e495b53b 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -60,13 +60,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 +73,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 +86,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 +101,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 +209,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 +} From 3562e8398510390703afc27b7457cf5eb07aba66 Mon Sep 17 00:00:00 2001 From: Doru Kesriyeli Date: Sun, 7 Oct 2018 17:28:50 -0700 Subject: [PATCH 18/34] added constructor --- DataStructures/Lists/DoublyLinkedList.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index 1d15e495b53b..d236fe68e9e5 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 From cc0980c23d2e400caf16d5878068ff4cbcff048c Mon Sep 17 00:00:00 2001 From: Doru Kesriyeli Date: Sun, 7 Oct 2018 17:29:23 -0700 Subject: [PATCH 19/34] Update DoublyLinkedList.java --- DataStructures/Lists/DoublyLinkedList.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java index d236fe68e9e5..27c1a1a24580 100644 --- a/DataStructures/Lists/DoublyLinkedList.java +++ b/DataStructures/Lists/DoublyLinkedList.java @@ -34,9 +34,9 @@ public DoublyLinkedList(){ */ public DoublyLinkedList(int[] array){ if (array == null) throw new NullPointerException(); - for (int i:array) { - insertTail(i); - } + for (int i:array) { + insertTail(i); + } } /** From 78e509b373b89290f8acb4a13870423d3a70a413 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 8 Oct 2018 17:09:50 +0300 Subject: [PATCH 20/34] There was no explanation for the SkylineProblem algorithm. Added and explanation to SkylineProblem. --- SkylineProblem/SkylineProblem.java | 6 ++++++ 1 file changed, 6 insertions(+) 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; From c7ca13b9610eeac969dd50d0b7afd2473821c930 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 8 Oct 2018 19:13:19 +0300 Subject: [PATCH 21/34] Added a new Dijkstra's algorithm. The code and comments should be more readable. --- Others/Dijkstra.java | 178 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 Others/Dijkstra.java diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java new file mode 100644 index 000000000000..0591445012e0 --- /dev/null +++ b/Others/Dijkstra.java @@ -0,0 +1,178 @@ +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(); + } + } +} \ No newline at end of file From 6cfc760e30d513401f718f005b6d221ca067a8f5 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 8 Oct 2018 19:14:47 +0300 Subject: [PATCH 22/34] Added a new Dijkstra's algorithm. --- Others/Dijkstra.java | 1 - 1 file changed, 1 deletion(-) diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index 0591445012e0..ae9d35f08884 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -12,7 +12,6 @@ * Also most of the comments are from RosettaCode. * */ - //import java.io.*; import java.util.*; public class Dijkstra { From d2d0b785c37ab3b07631552cab39ebb8674078d8 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 8 Oct 2018 19:16:15 +0300 Subject: [PATCH 23/34] test --- Others/Dijkstra.java | 177 ------------------------------------------- 1 file changed, 177 deletions(-) delete mode 100644 Others/Dijkstra.java diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java deleted file mode 100644 index ae9d35f08884..000000000000 --- a/Others/Dijkstra.java +++ /dev/null @@ -1,177 +0,0 @@ -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(); - } - } -} \ No newline at end of file From c9d0aa129048d065e3f8c8e2522d249a65bc5d8f Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 8 Oct 2018 19:17:56 +0300 Subject: [PATCH 24/34] New Dijkstra's algorithm with better comments. --- Others/Dijkstra.java | 178 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 Others/Dijkstra.java diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java new file mode 100644 index 000000000000..dd671547c51a --- /dev/null +++ b/Others/Dijkstra.java @@ -0,0 +1,178 @@ +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(); + } + } +} \ No newline at end of file From 66c6353705723932f5e80fdeae185302da843d9e Mon Sep 17 00:00:00 2001 From: rmakynen <43169683+rmakynen@users.noreply.github.com> Date: Tue, 9 Oct 2018 09:05:59 +0300 Subject: [PATCH 25/34] Update Dijkstra.java --- Others/Dijkstra.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index dd671547c51a..5df11f0274fa 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -63,13 +63,11 @@ public static class Vertex implements Comparable{ public Vertex previous = null; public final Map neighbours = new HashMap<>(); - public Vertex(String name) - { + public Vertex(String name){ this.name = name; } - private void printPath() - { + private void printPath(){ if (this == this.previous) { System.out.printf("%s", this.name); @@ -85,16 +83,14 @@ else if (this.previous == null) } } - public int compareTo(Vertex other) - { + public int compareTo(Vertex other){ if (dist == other.dist) return name.compareTo(other.name); return Integer.compare(dist, other.dist); } - @Override public String toString() - { + @Override public String toString(){ return "(" + name + ", " + dist + ")"; } } @@ -175,4 +171,4 @@ public void printAllPaths() { System.out.println(); } } -} \ No newline at end of file +} From 57fbbcd83608de76562a4eebded4513809cce15a Mon Sep 17 00:00:00 2001 From: rmakynen <43169683+rmakynen@users.noreply.github.com> Date: Tue, 9 Oct 2018 09:07:56 +0300 Subject: [PATCH 26/34] Updated the format of brackets --- Others/Dijkstra.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index 5df11f0274fa..4ae2daa58fad 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -57,7 +57,7 @@ public Edge(String v1, String v2, int dist) { } /** One vertex of the graph, complete with mappings to neighbouring vertices */ - public static class Vertex implements Comparable{ + 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; @@ -67,7 +67,7 @@ public Vertex(String name){ this.name = name; } - private void printPath(){ + private void printPath() { if (this == this.previous) { System.out.printf("%s", this.name); @@ -83,14 +83,14 @@ else if (this.previous == null) } } - public int compareTo(Vertex other){ + public int compareTo(Vertex other) { if (dist == other.dist) return name.compareTo(other.name); return Integer.compare(dist, other.dist); } - @Override public String toString(){ + @Override public String toString() { return "(" + name + ", " + dist + ")"; } } From f98e3c06bdf37fa8614b5ebd63ad55fbc39fc1c6 Mon Sep 17 00:00:00 2001 From: rmakynen <43169683+rmakynen@users.noreply.github.com> Date: Tue, 9 Oct 2018 09:09:38 +0300 Subject: [PATCH 27/34] Updated brackets --- Others/Dijkstra.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index 4ae2daa58fad..0fe461348b45 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -63,7 +63,7 @@ public static class Vertex implements Comparable { public Vertex previous = null; public final Map neighbours = new HashMap<>(); - public Vertex(String name){ + public Vertex(String name) { this.name = name; } From efae9fb3179b076d134dba7f82d932f085d0ea8f Mon Sep 17 00:00:00 2001 From: rmakynen <43169683+rmakynen@users.noreply.github.com> Date: Tue, 9 Oct 2018 09:16:00 +0300 Subject: [PATCH 28/34] Updated brackets --- Others/Dijkstra.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index 0fe461348b45..b3df65bfd2e3 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -68,16 +68,13 @@ public Vertex(String name) { } private void printPath() { - if (this == this.previous) - { + if (this == this.previous) { System.out.printf("%s", this.name); } - else if (this.previous == null) - { + else if (this.previous == null) { System.out.printf("%s(unreached)", this.name); } - else - { + else { this.previous.printPath(); System.out.printf(" -> %s(%d)", this.name, this.dist); } From c75fce171bf3b9fda951e3b665d2ee2cef31824d Mon Sep 17 00:00:00 2001 From: rmakynen Date: Tue, 9 Oct 2018 15:29:40 +0300 Subject: [PATCH 29/34] Updated comments for the Fibonacci sequence --- Others/FibToN.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) 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 From c6e66109094228e2effd86c1e81b8ee0579dfa34 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 15 Oct 2018 09:21:30 +0300 Subject: [PATCH 30/34] Fixed Compiler warnings, closed the scanned and fixed some typos --- Others/Huffman.java | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) 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 Date: Mon, 15 Oct 2018 11:52:08 +0300 Subject: [PATCH 31/34] The function had cryptic variable names. Now it's more readable. --- Others/KMP.java | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/Others/KMP.java b/Others/KMP.java index c97c248b480a..597f69373bf2 100644 --- a/Others/KMP.java +++ b/Others/KMP.java @@ -1,25 +1,26 @@ - /* Implementation of Knuth–Morris–Pratt algorithm -Usage: -final String T = "AAAAABAAABA"; -final String P = "AAAA"; -KMPmatcher(T, P); +Usage: see the main function for an example */ public class KMP { - - // find the starting index in string T[] that matches the search word P[] - public void KMPmatcher(final String T, final String P) { - final int m = T.length(); - final int n = P.length(); - final int[] pi = computePrefixFunction(P); + //a working example + public static void main(String[] args) { + final String haystack = "AAAAABAAABA"; //This is the full string + final String needle = "AAAA"; //This is the substring that we want to find + KMPmatcher(haystack, needle); + } + // find the starting index in string haystack[] that matches the search word P[] + public static void KMPmatcher(final String haystack, final String needle) { + final int m = haystack.length(); + final int n = needle.length(); + final int[] pi = computePrefixFunction(needle); int q = 0; for (int i = 0; i < m; i++) { - while (q > 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 From 217b31a1936f5ee7601ed571c373ca880f58cd3b Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 15 Oct 2018 15:38:04 +0300 Subject: [PATCH 32/34] Updated description. Fixed compiler warning. --- Others/PerlinNoise.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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; From dd8c8d761a3e908be2ad13cb1e496e83917bd4b5 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 15 Oct 2018 17:18:25 +0300 Subject: [PATCH 33/34] Improved performance by removing an unnecessary "stack.peek()" call --- Others/ReverseStackUsingRecursion.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 From 7351b8ad4461a98efe08e6afab9ce62499d42b14 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 15 Oct 2018 17:59:43 +0300 Subject: [PATCH 34/34] Improved readability, added prints to indicate what user should input --- Others/RootPrecision.java | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) 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