From 161791d4a5759878f53e4ef2e397502d621a8e81 Mon Sep 17 00:00:00 2001 From: Christian Bender Date: Wed, 25 Jul 2018 17:07:34 +0200 Subject: [PATCH 001/112] 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 002/112] 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 003/112] 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 004/112] 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 005/112] 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 006/112] 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 007/112] 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 008/112] 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 009/112] 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 010/112] 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 011/112] 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 012/112] 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 013/112] 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 014/112] 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 00:24:14 +0530 Subject: [PATCH 015/112] Minimum priority queue added alongside heap sort implementation --- DataStructures/Heaps/MinPriorityQueue.java | 131 +++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 DataStructures/Heaps/MinPriorityQueue.java diff --git a/DataStructures/Heaps/MinPriorityQueue.java b/DataStructures/Heaps/MinPriorityQueue.java new file mode 100644 index 000000000000..3dc2bd28083c --- /dev/null +++ b/DataStructures/Heaps/MinPriorityQueue.java @@ -0,0 +1,131 @@ + +/* Minimum Priority Queue +* It is a part of heap data structure +* A heap is a specific tree based data structure +* in which all the nodes of tree are in a specific order. +* that is the children are arranged in some +* respect of their parents, can either be greater +* or less than the parent. This makes it a min priority queue +* or max priority queue. +*/ + +// Functions: insert, delete, peek, isEmpty, print, heapSort, sink + +public class MinPriorityQueue { + private int[] heap; + private int capacity; + private int size; + + // calss the constructor and initializes the capacity + MinPriorityQueue(int c) { + this.capacity = c; + this.size = 0; + this.heap = new int[c + 1]; + } + + // inserts the key at the end and rearranges it + // so that the binary heap is in appropriate order + public void insert(int key) { + if (this.isFull()) + return; + this.heap[this.size + 1] = key; + int k = this.size + 1; + while (k > 1) { + if (this.heap[k] < this.heap[k / 2]) { + int temp = this.heap[k]; + this.heap[k] = this.heap[k / 2]; + this.heap[k / 2] = temp; + } + k = k / 2; + } + this.size++; + } + + // returns the highest priority value + public int peek() { + return this.heap[1]; + } + + // returns boolean value whether the heap is empty or not + public boolean isEmpty() { + if (0 == this.size) + return true; + return false; + } + + // returns boolean value whether the heap is full or not + public boolean isFull() { + if (this.size == this.capacity) + return true; + return false; + } + + // prints the heap + public void print() { + for (int i = 1; i <= this.capacity; i++) + System.out.print(this.heap[i] + " "); + System.out.println(); + } + + // heap sorting can be done by performing + // delete function to the number of times of the size of the heap + // it returns reverse sort because it is a min priority queue + public void heapSort() { + for (int i = 1; i < this.capacity; i++) + this.delete(); + } + + // this function reorders the heap after every delete function + private void sink() { + int k = 1; + while (2 * k <= this.size || 2 * k + 1 <= this.size) { + int minIndex; + if (this.heap[2 * k] >= this.heap[k]) { + if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) { + break; + } else if (2 * k + 1 > this.size) { + break; + } + } + if (2 * k + 1 > this.size) { + minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; + } else { + if (this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k + 1]) { + minIndex = this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; + } else { + minIndex = k; + } + } + int temp = this.heap[k]; + this.heap[k] = this.heap[minIndex]; + this.heap[minIndex] = temp; + k = minIndex; + } + } + + // deletes the highest priority value from the heap + public int delete() { + int min = this.heap[1]; + this.heap[1] = this.heap[this.size]; + this.heap[this.size] = min; + this.size--; + this.sink(); + return min; + } + + public static void main(String[] args) { + // testing + MinPriorityQueue q = new MinPriorityQueue(8); + q.insert(5); + q.insert(2); + q.insert(4); + q.insert(1); + q.insert(7); + q.insert(6); + q.insert(3); + q.insert(8); + q.print(); // [ 1, 2, 3, 5, 7, 6, 4, 8 ] + q.heapSort(); + q.print(); // [ 8, 7, 6, 5, 4, 3, 2, 1 ] + } +} \ No newline at end of file From 18b30402beb79f9f0dad05961c4306241edbca4c Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 5 Oct 2018 17:21:05 +0800 Subject: [PATCH 016/112] 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 017/112] 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 018/112] 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 019/112] 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 020/112] 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 7ed62a9930101c5e685a0ae275392dafea0435d2 Mon Sep 17 00:00:00 2001 From: Lucas Contini Date: Mon, 8 Oct 2018 10:13:08 -0300 Subject: [PATCH 021/112] Improved readability --- Others/Dijkshtra.java | 116 +++++++++++++++++++++++++----------------- 1 file changed, 69 insertions(+), 47 deletions(-) diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java index 05011dd4212f..e0bd6737a462 100644 --- a/Others/Dijkshtra.java +++ b/Others/Dijkshtra.java @@ -3,7 +3,6 @@ */ - import java.io.IOException; import java.util.Arrays; import java.util.Scanner; @@ -11,51 +10,74 @@ public class Dijkshtra { -public static void main(String[] args) throws IOException { - Scanner in =new Scanner(System.in); - - int n=in.nextInt(); //n = Number of nodes or vertices - int m=in.nextInt(); //m = Number of Edges - long w[][]=new long [n+1][n+1]; //Adjacency Matrix - - //Initializing Matrix with Certain Maximum Value for path b/w any two vertices - for (long[] row: w) - Arrays.fill(row, 1000000l); - //From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l - //For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l . - - //Taking Input as Edge Location b/w a pair of vertices - for(int i=0;icmp){ //Comparing previous edge value with current value - Cycle Case - w[x][y]=cmp; w[y][x]=cmp; - } + public static void main(String[] args) throws IOException { + Scanner in = new Scanner(System.in); + + // n = Number of nodes or vertices + int n = in.nextInt(); + // m = Number of Edges + int m = in.nextInt(); + + // Adjacency Matrix + long w[][] = new long [n+1][n+1]; + + //Initializing Matrix with Certain Maximum Value for path b/w any two vertices + for (long[] row : w) { + Arrays.fill(row, 1000000l); + } + + /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l + For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */ + + // Taking Input as Edge Location b/w a pair of vertices + for(int i = 0; i < m; i++) { + int x = in.nextInt(),y=in.nextInt(); + long cmp = in.nextLong(); + + //Comparing previous edge value with current value - Cycle Case + if(w[x][y] > cmp) { + w[x][y] = cmp; w[y][x] = cmp; + } + } + + // Implementing Dijkshtra's Algorithm + Stack t = new Stack(); + int src = in.nextInt(); + + for(int i = 1; i <= n; i++) { + if(i != src) { + t.push(i); + } + } + + Stack p = new Stack(); + p.push(src); + w[src][src] = 0; + + while(!t.isEmpty()) { + int min = 989997979; + int loc = -1; + + for(int i = 0; i < t.size(); i++) { + w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]); + if(w[src][t.elementAt(i)] <= min) { + min = (int) w[src][t.elementAt(i)]; + loc = i; + } + } + p.push(t.elementAt(loc)); + t.removeElementAt(loc); + } + + // Printing shortest path from the given source src + for(int i = 1; i <= n; i++) { + if(i != src && w[src][i] != 1000000l) { + System.out.print(w[src][i] + " "); + } + // Printing -1 if there is no path b/w given pair of edges + else if(i != src) { + System.out.print("-1" + " "); + } + } } - - //Implementing Dijkshtra's Algorithm - - Stack t=new Stack(); - int src=in.nextInt(); - for(int i=1;i<=n;i++){ - if(i!=src){t.push(i);}} - Stack p=new Stack(); - p.push(src); - w[src][src]=0; - while(!t.isEmpty()){int min=989997979,loc=-1; - for(int i=0;i Date: Mon, 8 Oct 2018 17:09:50 +0300 Subject: [PATCH 022/112] 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 023/112] 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 024/112] 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 025/112] 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 026/112] 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 027/112] 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 028/112] 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 029/112] 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 030/112] 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 031/112] 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 7e0ddb3fdae4123ada8dfea9f3b48d1fe46ca36d Mon Sep 17 00:00:00 2001 From: Shruti Sheoran Date: Thu, 11 Oct 2018 11:25:26 +0530 Subject: [PATCH 032/112] Add Median Of Running Array --- Misc/MedianOfRunningArray.java | 50 ++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Misc/MedianOfRunningArray.java diff --git a/Misc/MedianOfRunningArray.java b/Misc/MedianOfRunningArray.java new file mode 100644 index 000000000000..113f19c72b9b --- /dev/null +++ b/Misc/MedianOfRunningArray.java @@ -0,0 +1,50 @@ +import java.util.Collections; +import java.util.PriorityQueue; + +/********************** +author: shrutisheoran +***********************/ + +public class MedianOfRunningArray { + private PriorityQueue p1; + private PriorityQueue p2; + + //Constructor + public MedianOfRunningArray() { + this.p1 = new PriorityQueue<>(Collections.reverseOrder()); //Max Heap + this.p2 = new PriorityQueue<>(); //Min Heap + } + + /* + Inserting lower half of array to max Heap + and upper half to min heap + */ + public void insert(Integer e) { + p2.add(e); + if(p2.size() - p1.size() > 1) + p1.add(p2.remove()); + } + + /* + Returns median at any given point + */ + public Integer median() { + if(p1.size()==p2.size()) + return (p1.peek() + p2.peek())/2; + return p1.size()>p2.size() ? p1.peek() : p2.peek(); + } + + public static void main(String[] args) { + /* + Testing the median function + */ + + MedianOfRunningArray p = new MedianOfRunningArray(); + int arr[] = {10, 7, 4, 9, 2, 3, 11, 17, 14}; + for(int i = 0 ; i < 9 ; i++) { + p.insert(arr[i]); + System.out.print(p.median() + " "); + } + } + +} \ No newline at end of file From c6e66109094228e2effd86c1e81b8ee0579dfa34 Mon Sep 17 00:00:00 2001 From: rmakynen Date: Mon, 15 Oct 2018 09:21:30 +0300 Subject: [PATCH 033/112] 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 034/112] 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 5eaa57983250bbd1f134064f2794f81593032a86 Mon Sep 17 00:00:00 2001 From: shivg7706 Date: Thu, 18 Oct 2018 15:47:00 +0530 Subject: [PATCH 035/112] all cycles present in a graph --- DataStructures/Graphs/Cycles.java | 89 +++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 DataStructures/Graphs/Cycles.java diff --git a/DataStructures/Graphs/Cycles.java b/DataStructures/Graphs/Cycles.java new file mode 100644 index 000000000000..429dd8de41db --- /dev/null +++ b/DataStructures/Graphs/Cycles.java @@ -0,0 +1,89 @@ +import java.util.Scanner; +import java.util.ArrayList; + + +class Cycle { + + private int nodes, edges; + private int [][] adjacencyMatrix; + private boolean [] visited; + ArrayList> cycles = new ArrayList>(); + private boolean [] finalCycles; + + public Cycle() { + Scanner in = new Scanner(System.in); + System.out.print("Enter the no. of nodes: "); + nodes = in.nextInt(); + System.out.print("Enter the no. of Edges: "); + edges = in.nextInt(); + + adjacencyMatrix = new int [nodes][nodes]; + visited = new boolean [nodes]; + + for (int i = 0; i < nodes; i++) { + visited[i] = false; + } + + System.out.println("Enter the details of each edges "); + + for(int i = 0; i < edges; i++) { + int start, end; + start = in.nextInt(); + end = in.nextInt(); + adjacencyMatrix[start][end] = 1; + } + + } + + public void start() { + for (int i = 0; i < nodes; i++) { + ArrayList temp = new ArrayList<>(); + dfs(i, i, temp); + for (int j = 0; j < nodes; j++) { + adjacencyMatrix[i][j] = 0; + adjacencyMatrix[j][i] = 0; + } + } + } + + private void dfs(Integer start, Integer curr, ArrayList temp) { + temp.add(curr); + visited[curr] = true; + for (int i = 0; i < nodes; i++) { + if(adjacencyMatrix[curr][i] == 1) { + if (i == start) { + cycles.add(new ArrayList(temp)); + } else { + if (!visited[i]) { + dfs(start, i, temp); + } + } + } + } + + if(temp.size() > 0) { + temp.remove(temp.size() - 1); + } + visited[curr] = false; + } + + public void printAll() { + for (int i = 0; i < cycles.size(); i++) { + for (int j = 0; j < cycles.get(i).size(); j++) { + System.out.print(cycles.get(i).get(j) + " -> "); + } + System.out.println(cycles.get(i).get(0)); + System.out.println(); + } + + } + +} + +public class Cycles { + public static void main(String[] args) { + Cycle c = new Cycle(); + c.start(); + c.printAll(); + } +} \ No newline at end of file From e89e0295166aefd452beabc465da62ff5c83e995 Mon Sep 17 00:00:00 2001 From: Emily Gong Date: Sun, 21 Oct 2018 16:50:09 -0700 Subject: [PATCH 036/112] update README style and fixed minor issues --- README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c11c573e3d53..bd13231f6f92 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 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. +NOTE: 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) @@ -19,7 +19,7 @@ __Properties__ * Best case performance O(n) * Average case performance O(n^2) -###### View the algorithm in [action][bubble-toptal] +##### View the algorithm in [action][bubble-toptal] @@ -34,7 +34,7 @@ __Properties__ * Best case performance O(n) * Average case performance O(n^2) -###### View the algorithm in [action][insertion-toptal] +##### View the algorithm in [action][insertion-toptal] ### Merge @@ -48,7 +48,7 @@ __Properties__ * Average case performance O(n log n) -###### View the algorithm in [action][merge-toptal] +##### View the algorithm in [action][merge-toptal] ### Quick ![alt text][quick-image] @@ -60,7 +60,7 @@ __Properties__ * Best case performance O(n log n) or O(n) with three-way partition * Average case performance O(n^2) -###### View the algorithm in [action][quick-toptal] +##### View the algorithm in [action][quick-toptal] ### Selection ![alt text][selection-image] @@ -72,7 +72,7 @@ __Properties__ * Best case performance O(n^2) * Average case performance O(n^2) -###### View the algorithm in [action][selection-toptal] +##### View the algorithm in [action][selection-toptal] ### Shell ![alt text][shell-image] @@ -84,7 +84,7 @@ __Properties__ * Best case performance O(n log n) * Average case performance depends on gap sequence -###### View the algorithm in [action][shell-toptal] +##### View the algorithm in [action][shell-toptal] ### Time-Compexity Graphs @@ -119,6 +119,7 @@ __Properties__ * Average case performance O(log n) * Worst case space complexity O(1) +### Shell From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. __Properties__ @@ -126,7 +127,7 @@ __Properties__ * Best case performance O(n log n) * Average case performance depends on gap sequence -###### View the algorithm in [action][shell-toptal] +##### View the algorithm in [action][shell-toptal] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort From 88b772c50ed62adabf525030a30f0624e7ebf164 Mon Sep 17 00:00:00 2001 From: Mojtaba Rahimy Date: Mon, 22 Oct 2018 15:35:15 +0330 Subject: [PATCH 037/112] Update README.md The folder "Data Structures" was renamed to "DataStructures" but the links was not. fixed that. --- README.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index c11c573e3d53..bb08f7586247 100644 --- a/README.md +++ b/README.md @@ -177,20 +177,20 @@ and much more...| and more... ### Data Structures Graphs|Heaps|Lists|Queues| ------|-----|-----|------| -[BFS](Data%20Structures/Graphs/BFS.java)|[Empty Heap Exception](Data%20Structures/Heaps/EmptyHeapException.java)|[Circle Linked List](Data%20Structures/Lists/CircleLinkedList.java)|[Generic Array List Queue](Data%20Structures/Queues/GenericArrayListQueue.java)| -[DFS](Data%20Structures/Graphs/DFS.java)|[Heap](Data%20Structures/Heaps/Heap.java)|[Doubly Linked List](Data%20Structures/Lists/DoublyLinkedList.java)|[Queues](Data%20Structures/Queues/Queues.java)| -[Graphs](Data%20Structures/Graphs/Graphs.java)|[Heap Element](Data%20Structures/Heaps/HeapElement.java)|[Singly Linked List](Data%20Structures/Lists/SinglyLinkedList.java)| -[Kruskals Algorithm](Data%20Structures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)| -[Matrix Graphs](Data%20Structures/Graphs/MatrixGraphs.java)|[Min Heap](Data%20Structures/Heaps/MinHeap.java)| -[PrimMST](Data%20Structures/Graphs/PrimMST.java)| +[BFS](DataStructures/Graphs/BFS.java)|[Empty Heap Exception](DataStructures/Heaps/EmptyHeapException.java)|[Circle Linked List](DataStructures/Lists/CircleLinkedList.java)|[Generic Array List Queue](DataStructures/Queues/GenericArrayListQueue.java)| +[DFS](DataStructures/Graphs/DFS.java)|[Heap](DataStructures/Heaps/Heap.java)|[Doubly Linked List](DataStructures/Lists/DoublyLinkedList.java)|[Queues](DataStructures/Queues/Queues.java)| +[Graphs](DataStructures/Graphs/Graphs.java)|[Heap Element](DataStructures/Heaps/HeapElement.java)|[Singly Linked List](DataStructures/Lists/SinglyLinkedList.java)| +[Kruskals Algorithm](DataStructures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)| +[Matrix Graphs](DataStructures/Graphs/MatrixGraphs.java)|[Min Heap](DataStructures/Heaps/MinHeap.java)| +[PrimMST](DataStructures/Graphs/PrimMST.java)| Stacks|Trees| ------|-----| -[Node Stack](Data%20Structures/Stacks/NodeStack.java)|[AVL Tree](Data%20Structures/Trees/AVLTree.java)| -[Stack of Linked List](Data%20Structures/Stacks/StackOfLinkedList.java)|[Binary Tree](Data%20Structures/Trees/BinaryTree.java)| -[Stacks](Data%20Structures/Stacks/Stacks.java)|And much more...| - -* [Bags](Data%20Structures/Bags/Bag.java) -* [Buffer](Data%20Structures/Buffers/CircularBuffer.java) -* [HashMap](Data%20Structures/HashMap/HashMap.java) -* [Matrix](Data%20Structures/Matrix/Matrix.java) +[Node Stack](DataStructures/Stacks/NodeStack.java)|[AVL Tree](DataStructures/Trees/AVLTree.java)| +[Stack of Linked List](DataStructures/Stacks/StackOfLinkedList.java)|[Binary Tree](DataStructures/Trees/BinaryTree.java)| +[Stacks](DataStructures/Stacks/Stacks.java)|And much more...| + +* [Bags](DataStructures/Bags/Bag.java) +* [Buffer](DataStructures/Buffers/CircularBuffer.java) +* [HashMap](DataStructures/HashMap/HashMap.java) +* [Matrix](DataStructures/Matrix/Matrix.java) From 174b83f764639793ff4eb0d97261ca9325975789 Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 22 Oct 2018 20:35:07 +0100 Subject: [PATCH 038/112] Clean Java BinarySearch Cleans the Java implementation of binary search to be more consistent with styles and to avoid unnecessary boxing of int types --- Searches/src/search/BinarySearch.java | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/Searches/src/search/BinarySearch.java b/Searches/src/search/BinarySearch.java index c560ca1a1220..239bc98c6f2a 100644 --- a/Searches/src/search/BinarySearch.java +++ b/Searches/src/search/BinarySearch.java @@ -2,7 +2,8 @@ import java.util.Arrays; import java.util.Random; -import java.util.stream.Stream; +import java.util.concurrent.ThreadLocalRandom +import java.util.stream.IntStream; import static java.lang.String.format; @@ -70,23 +71,24 @@ private > int search(T array[], T key, int left, int rig // Driver Program public static void main(String[] args) { - - //just generate data - Random r = new Random(); + // Just generate data + Random random = ThreadLocalRandom.current(); + int size = 100; int maxElement = 100000; - Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new); - + + int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(); - //the element that should be found - Integer shouldBeFound = integers[r.nextInt(size - 1)]; + // The element that should be found + int shouldBeFound = integers[r.nextInt(size - 1)]; BinarySearch search = new BinarySearch(); int atIndex = search.find(integers, shouldBeFound); - System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d" - , shouldBeFound, integers[atIndex], atIndex, size)); - + System.out.println(format( + "Should be found: %d. Found %d at index %d. An array length %d", + shouldBeFound, integers[atIndex], atIndex, size + )); int toCheck = Arrays.binarySearch(integers, shouldBeFound); System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex)); From 203f006e9686f5c4948f38a53599ed072fac4e51 Mon Sep 17 00:00:00 2001 From: shivg7706 Date: Fri, 26 Oct 2018 17:32:49 +0530 Subject: [PATCH 039/112] added scheduling algorithm --- Others/SJF.java | 168 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 Others/SJF.java diff --git a/Others/SJF.java b/Others/SJF.java new file mode 100644 index 000000000000..baa8a8fd01f0 --- /dev/null +++ b/Others/SJF.java @@ -0,0 +1,168 @@ +import java.util.Scanner; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.*; + +class Process { + + public int pid; + public int arrivalTime; + public int burstTime; + public int priority; + public int turnAroundTime; + public int waitTime; + public int remainingTime; +} + + +class Schedule { + + private int noOfProcess; + private int timer = 0; + private ArrayList processes; + private ArrayList remainingProcess; + private ArrayList gantChart; + private float burstAll; + private Map> arrivals; + + Schedule() { + Scanner in = new Scanner(System.in); + + processes = new ArrayList(); + remainingProcess = new ArrayList(); + + gantChart = new ArrayList(); + arrivals = new HashMap>(); + + System.out.print("Enter the no. of processes: "); + noOfProcess = in.nextInt(); + System.out.println("Enter the arrival, burst and priority of processes"); + for (int i = 0; i < noOfProcess; i++) { + Process p = new Process(); + p.pid = i; + p.arrivalTime = in.nextInt(); + p.burstTime = in.nextInt(); + p.priority = in.nextInt(); + p.turnAroundTime = 0; + p.waitTime = 0; + p.remainingTime = p.burstTime; + + if (arrivals.get(p.arrivalTime) == null) { + arrivals.put(p.arrivalTime, new ArrayList()); + } + arrivals.get(p.arrivalTime).add(p); + processes.add(p); + burstAll += p.burstTime; + } + + } + + + void startScheduling() { + + + processes.sort(new Comparator() { + @Override + public int compare (Process a, Process b) { + return a.arrivalTime - b.arrivalTime; + } + }); + + while(!(arrivals.size() == 0 && remainingProcess.size() == 0)) { + removeFinishedProcess(); + if(arrivals.get(timer) != null) { + remainingProcess.addAll(arrivals.get(timer)); + arrivals.remove(timer); + } + + remainingProcess.sort(new Comparator() { + private int alpha = 6; + private int beta = 1; + + @Override + public int compare (Process a, Process b) { + int aRem = a.remainingTime; + int bRem = b.remainingTime; + int aprior = a.priority; + int bprior = b.priority; + return (alpha*aRem + beta*aprior) - (alpha*bRem + beta*bprior); + } + }); + + int k = timeElapsed(timer); + ageing(k); + timer++; + } + + System.out.println("Total time required: " + (timer-1)); + } + + void removeFinishedProcess() { + ArrayList completed = new ArrayList(); + for (int i = 0; i < remainingProcess.size(); i++) { + if(remainingProcess.get(i).remainingTime == 0) { + completed.add(i); + } + } + + for (int i = 0; i < completed.size(); i++) { + int pid = remainingProcess.get(completed.get(i)).pid; + processes.get(pid).waitTime = remainingProcess.get(completed.get(i)).waitTime; + remainingProcess.remove(remainingProcess.get(completed.get(i))); + } + + + } + + public int timeElapsed(int i) { + if(!remainingProcess.isEmpty()) { + gantChart.add(i, remainingProcess.get(0).pid); + remainingProcess.get(0).remainingTime--; + return 1; + } + return 0; + } + + public void ageing(int k) { + for (int i = k; i < remainingProcess.size(); i++) { + remainingProcess.get(i).waitTime++; + if (remainingProcess.get(i).waitTime % 7 == 0) { + remainingProcess.get(i).priority--; + } + } + } + + + public void solve() { + System.out.println("Gant chart "); + for (int i = 0; i < gantChart.size(); i++) { + System.out.print(gantChart.get(i) + " "); + } + System.out.println(); + + float waitTimeTot = 0; + float tatTime = 0; + + for (int i = 0; i < noOfProcess; i++) { + processes.get(i).turnAroundTime = processes.get(i).waitTime + processes.get(i).burstTime; + + waitTimeTot += processes.get(i).waitTime; + tatTime += processes.get(i).turnAroundTime; + + System.out.println("Process no.: " + i + " Wait time: " + processes.get(i).waitTime + " Turn Around Time: " + processes.get(i).turnAroundTime); + } + + System.out.println("Average Waiting Time: " + waitTimeTot/noOfProcess); + System.out.println("Average TAT Time: " + tatTime/noOfProcess); + System.out.println("Throughput: " + (float)noOfProcess/(timer - 1)); + } + +} + +public class SJF { + public static void main(String[] args) { + Schedule s = new Schedule(); + s.startScheduling(); + s.solve(); + } +} \ No newline at end of file From 7fc41e87d74f7bde837678e21618f75ed631792c Mon Sep 17 00:00:00 2001 From: shivg7706 Date: Sat, 27 Oct 2018 08:24:42 +0530 Subject: [PATCH 040/112] chnages --- Others/SJF.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Others/SJF.java b/Others/SJF.java index baa8a8fd01f0..3bc510d6c15f 100644 --- a/Others/SJF.java +++ b/Others/SJF.java @@ -31,8 +31,8 @@ class Schedule { processes = new ArrayList(); remainingProcess = new ArrayList(); - gantChart = new ArrayList(); - arrivals = new HashMap>(); + gantChart = new ArrayList<>(); + arrivals = new HashMap<>(); System.out.print("Enter the no. of processes: "); noOfProcess = in.nextInt(); From 6092dfca7954f9b21364b668fba9d8fa731d3c4f Mon Sep 17 00:00:00 2001 From: shivg7706 Date: Sat, 27 Oct 2018 08:29:09 +0530 Subject: [PATCH 041/112] added description about algorithm --- Others/SJF.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Others/SJF.java b/Others/SJF.java index 3bc510d6c15f..244365da4bf6 100644 --- a/Others/SJF.java +++ b/Others/SJF.java @@ -1,3 +1,15 @@ +// Shortest job first. + +// Shortest job first (SJF) or shortest job next, is a scheduling policy +// that selects the waiting process with the smallest execution time to execute next +// Shortest Job first has the advantage of having minimum average waiting +// time among all scheduling algorithms. +// It is a Greedy Algorithm. +// It may cause starvation if shorter processes keep coming. +// This problem has been solved using the concept of aging. + + + import java.util.Scanner; import java.util.ArrayList; import java.util.Comparator; From 1e27a5d0b1e8329aa45470085f680c2e42ecef88 Mon Sep 17 00:00:00 2001 From: shivg7706 Date: Sat, 27 Oct 2018 12:59:00 +0530 Subject: [PATCH 042/112] documentation --- Others/SJF.java | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/Others/SJF.java b/Others/SJF.java index 244365da4bf6..923ece654939 100644 --- a/Others/SJF.java +++ b/Others/SJF.java @@ -1,14 +1,14 @@ -// Shortest job first. - -// Shortest job first (SJF) or shortest job next, is a scheduling policy -// that selects the waiting process with the smallest execution time to execute next -// Shortest Job first has the advantage of having minimum average waiting -// time among all scheduling algorithms. -// It is a Greedy Algorithm. -// It may cause starvation if shorter processes keep coming. -// This problem has been solved using the concept of aging. - - +/** +*

Shortest job first.

+*

Shortest job first (SJF) or shortest job next, is a scheduling policy +* that selects the waiting process with the smallest execution time to execute next +* Shortest Job first has the advantage of having minimum average waiting time among all scheduling algorithms. +* It is a Greedy Algorithm. +* It may cause starvation if shorter processes keep coming. +* This problem has been solved using the concept of aging.

+* @author shivg7706 +* @since 2018/10/27 +*/ import java.util.Scanner; import java.util.ArrayList; @@ -26,7 +26,6 @@ class Process { public int remainingTime; } - class Schedule { private int noOfProcess; From a9502c276e55a7d0ecf5dfa36e10f834deecdc06 Mon Sep 17 00:00:00 2001 From: Hector S Date: Sat, 27 Oct 2018 21:30:33 -0300 Subject: [PATCH 043/112] Update README.md Update average case of quicksort: n log n #607 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb08f7586247..4d08658198c6 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sor __Properties__ * Worst case performance O(n^2) * Best case performance O(n log n) or O(n) with three-way partition -* Average case performance O(n^2) +* Average case performance O(n log n) ###### View the algorithm in [action][quick-toptal] From 819b7fd3da89967b25ea14f85eda94119d9f545f Mon Sep 17 00:00:00 2001 From: varunu28 Date: Tue, 13 Nov 2018 09:15:47 -0800 Subject: [PATCH 044/112] Restructured the repo --- .classpath | 7 - .gitignore | 4 + .project | 17 --- Searches/{src/search => }/BinarySearch.java | 2 +- .../{src/search => }/InterpolationSearch.java | 2 +- .../search => }/IterativeBinarySearch.java | 2 +- .../search => }/IterativeTernarySearch.java | 2 +- Searches/{src/search => }/LinearSearch.java | 2 +- .../{src/search => }/SaddlebackSearch.java | 2 +- .../{src/search => }/SearchAlgorithm.java | 2 +- Searches/{src/search => }/TernarySearch.java | 2 +- SkylineProblem/SkylineProblem.java | 137 ------------------ Sorts/{src/sort => }/BinaryTreeSort.java | 6 +- Sorts/{src/sort => }/BogoSort.java | 12 +- Sorts/{src/sort => }/BubbleSort.java | 4 +- Sorts/{src/sort => }/CocktailShakerSort.java | 16 +- Sorts/{src/sort => }/CombSort.java | 4 +- Sorts/{src/sort => }/CountingSort.java | 4 +- Sorts/{src/sort => }/CycleSort.java | 6 +- Sorts/{src/sort => }/GnomeSort.java | 4 +- Sorts/{src/sort => }/HeapSort.java | 4 +- Sorts/{src/sort => }/InsertionSort.java | 6 +- Sorts/{src/sort => }/MergeSort.java | 4 +- Sorts/{src/sort => }/PancakeSort.java | 4 +- Sorts/{src/sort => }/QuickSort.java | 4 +- Sorts/{src/sort => }/RadixSort.java | 2 +- Sorts/{src/sort => }/SelectionSort.java | 12 +- Sorts/{src/sort => }/ShellSort.java | 4 +- Sorts/{src/sort => }/SortAlgorithm.java | 2 +- Sorts/{src/sort => }/SortUtils.java | 2 +- 30 files changed, 59 insertions(+), 222 deletions(-) delete mode 100644 .classpath delete mode 100644 .project rename Searches/{src/search => }/BinarySearch.java (99%) rename Searches/{src/search => }/InterpolationSearch.java (99%) rename Searches/{src/search => }/IterativeBinarySearch.java (99%) rename Searches/{src/search => }/IterativeTernarySearch.java (99%) rename Searches/{src/search => }/LinearSearch.java (98%) rename Searches/{src/search => }/SaddlebackSearch.java (99%) rename Searches/{src/search => }/SearchAlgorithm.java (96%) rename Searches/{src/search => }/TernarySearch.java (99%) delete mode 100644 SkylineProblem/SkylineProblem.java rename Sorts/{src/sort => }/BinaryTreeSort.java (95%) rename Sorts/{src/sort => }/BogoSort.java (82%) rename Sorts/{src/sort => }/BubbleSort.java (96%) rename Sorts/{src/sort => }/CocktailShakerSort.java (79%) rename Sorts/{src/sort => }/CombSort.java (97%) rename Sorts/{src/sort => }/CountingSort.java (98%) rename Sorts/{src/sort => }/CycleSort.java (95%) rename Sorts/{src/sort => }/GnomeSort.java (95%) rename Sorts/{src/sort => }/HeapSort.java (98%) rename Sorts/{src/sort => }/InsertionSort.java (93%) rename Sorts/{src/sort => }/MergeSort.java (98%) rename Sorts/{src/sort => }/PancakeSort.java (95%) rename Sorts/{src/sort => }/QuickSort.java (97%) rename Sorts/{src/sort => }/RadixSort.java (98%) rename Sorts/{src/sort => }/SelectionSort.java (87%) rename Sorts/{src/sort => }/ShellSort.java (94%) rename Sorts/{src/sort => }/SortAlgorithm.java (98%) rename Sorts/{src/sort => }/SortUtils.java (99%) diff --git a/.classpath b/.classpath deleted file mode 100644 index 67d5f6d35842..000000000000 --- a/.classpath +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/.gitignore b/.gitignore index ae3c1726048c..bf2ba9450292 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ /bin/ +.idea/* +.classpath* +.project* +*.iml diff --git a/.project b/.project deleted file mode 100644 index ea54703d8788..000000000000 --- a/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - Java - - - - - - org.eclipse.jdt.core.javabuilder - - - - - - org.eclipse.jdt.core.javanature - - diff --git a/Searches/src/search/BinarySearch.java b/Searches/BinarySearch.java similarity index 99% rename from Searches/src/search/BinarySearch.java rename to Searches/BinarySearch.java index 239bc98c6f2a..f655c074f279 100644 --- a/Searches/src/search/BinarySearch.java +++ b/Searches/BinarySearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Arrays; import java.util.Random; diff --git a/Searches/src/search/InterpolationSearch.java b/Searches/InterpolationSearch.java similarity index 99% rename from Searches/src/search/InterpolationSearch.java rename to Searches/InterpolationSearch.java index 06313d13ce9c..b2395797c207 100644 --- a/Searches/src/search/InterpolationSearch.java +++ b/Searches/InterpolationSearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Arrays; import java.util.Random; diff --git a/Searches/src/search/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java similarity index 99% rename from Searches/src/search/IterativeBinarySearch.java rename to Searches/IterativeBinarySearch.java index 17bfe3950e94..c6f8e7f1a8d9 100644 --- a/Searches/src/search/IterativeBinarySearch.java +++ b/Searches/IterativeBinarySearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Arrays; import java.util.Random; diff --git a/Searches/src/search/IterativeTernarySearch.java b/Searches/IterativeTernarySearch.java similarity index 99% rename from Searches/src/search/IterativeTernarySearch.java rename to Searches/IterativeTernarySearch.java index c3538e69f00a..598b3b3eb366 100644 --- a/Searches/src/search/IterativeTernarySearch.java +++ b/Searches/IterativeTernarySearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Arrays; import java.util.Random; diff --git a/Searches/src/search/LinearSearch.java b/Searches/LinearSearch.java similarity index 98% rename from Searches/src/search/LinearSearch.java rename to Searches/LinearSearch.java index 6e96da0f43bb..7664d7debb99 100644 --- a/Searches/src/search/LinearSearch.java +++ b/Searches/LinearSearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Random; import java.util.stream.Stream; diff --git a/Searches/src/search/SaddlebackSearch.java b/Searches/SaddlebackSearch.java similarity index 99% rename from Searches/src/search/SaddlebackSearch.java rename to Searches/SaddlebackSearch.java index 68779db8f79f..ed9c9108c480 100644 --- a/Searches/src/search/SaddlebackSearch.java +++ b/Searches/SaddlebackSearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Scanner; diff --git a/Searches/src/search/SearchAlgorithm.java b/Searches/SearchAlgorithm.java similarity index 96% rename from Searches/src/search/SearchAlgorithm.java rename to Searches/SearchAlgorithm.java index ca3bf59ba552..d1a93fb7eacc 100644 --- a/Searches/src/search/SearchAlgorithm.java +++ b/Searches/SearchAlgorithm.java @@ -1,4 +1,4 @@ -package search; +package Searches; /** * The common interface of most searching algorithms diff --git a/Searches/src/search/TernarySearch.java b/Searches/TernarySearch.java similarity index 99% rename from Searches/src/search/TernarySearch.java rename to Searches/TernarySearch.java index 7e60edf3aad7..cefd374098cc 100644 --- a/Searches/src/search/TernarySearch.java +++ b/Searches/TernarySearch.java @@ -1,4 +1,4 @@ -package search; +package Searches; import java.util.Arrays; diff --git a/SkylineProblem/SkylineProblem.java b/SkylineProblem/SkylineProblem.java deleted file mode 100644 index 121116e16685..000000000000 --- a/SkylineProblem/SkylineProblem.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * 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; - -public class SkylineProblem { - Building[] building; - int count; - - public void run() { - Scanner sc = new Scanner(System.in); - - int num = sc.nextInt(); - this.building = new Building[num]; - - for(int i = 0; i < num; i++) { - String input = sc.next(); - String[] data = input.split(","); - this.add(Integer.parseInt(data[0]), Integer.parseInt(data[1]), Integer.parseInt(data[2])); - } - this.print(this.findSkyline(0, num - 1)); - - sc.close(); - } - - public void add(int left, int height, int right) { - building[count++] = new Building(left, height, right); - } - - public void print(ArrayList skyline) { - Iterator it = skyline.iterator(); - - while(it.hasNext()) { - Skyline temp = it.next(); - System.out.print(temp.coordinates + "," + temp.height); - if(it.hasNext()) { - System.out.print(","); - } - } - - } - - public ArrayList findSkyline(int start, int end) { - if(start == end) { - ArrayList list = new ArrayList<>(); - list.add(new Skyline(building[start].left, building[start].height)); - list.add(new Skyline(building[end].right, 0)); - - return list; - } - - int mid = (start + end) / 2; - - ArrayList sky1 = this.findSkyline(start, mid); - ArrayList sky2 = this.findSkyline(mid + 1, end); - - return this.mergeSkyline(sky1, sky2); - } - - public ArrayList mergeSkyline(ArrayList sky1, ArrayList sky2) { - int currentH1 = 0, currentH2 = 0; - ArrayList skyline = new ArrayList<>(); - int maxH = 0; - - while(!sky1.isEmpty() && !sky2.isEmpty()) { - if(sky1.get(0).coordinates < sky2.get(0).coordinates) { - int currentX = sky1.get(0).coordinates; - currentH1 = sky1.get(0).height; - - if(currentH1 < currentH2) { - sky1.remove(0); - if(maxH != currentH2) skyline.add(new Skyline(currentX, currentH2)); - } else { - maxH = currentH1; - sky1.remove(0); - skyline.add(new Skyline(currentX, currentH1)); - } - } else { - int currentX = sky2.get(0).coordinates; - currentH2 = sky2.get(0).height; - - if(currentH2 < currentH1) { - sky2.remove(0); - if(maxH != currentH1) skyline.add(new Skyline(currentX, currentH1)); - } else { - maxH = currentH2; - sky2.remove(0); - skyline.add(new Skyline(currentX, currentH2)); - } - } - } - - while(!sky1.isEmpty()) { - skyline.add(sky1.get(0)); - sky1.remove(0); - } - - while(!sky2.isEmpty()) { - skyline.add(sky2.get(0)); - sky2.remove(0); - } - - return skyline; - } - - public class Skyline { - public int coordinates; - public int height; - - public Skyline(int coordinates, int height) { - this.coordinates = coordinates; - this.height = height; - } - } - - public class Building { - public int left; - public int height; - public int right; - - public Building(int left, int height, int right) { - this.left = left; - this.height = height; - this.right = right; - } - } - - public static void main(String[] args) { - SkylineProblem skylineProblem = new SkylineProblem(); - skylineProblem.run(); - } -} diff --git a/Sorts/src/sort/BinaryTreeSort.java b/Sorts/BinaryTreeSort.java similarity index 95% rename from Sorts/src/sort/BinaryTreeSort.java rename to Sorts/BinaryTreeSort.java index 59d58ab61987..26942754f910 100644 --- a/Sorts/src/sort/BinaryTreeSort.java +++ b/Sorts/BinaryTreeSort.java @@ -1,7 +1,7 @@ -package sort; +package Sorts; -import static sort.SortUtils.less; -import static sort.SortUtils.print; +import static Sorts.SortUtils.less; +import static Sorts.SortUtils.print; /** * diff --git a/Sorts/src/sort/BogoSort.java b/Sorts/BogoSort.java similarity index 82% rename from Sorts/src/sort/BogoSort.java rename to Sorts/BogoSort.java index 1079ca21c27a..f3f923d32edf 100644 --- a/Sorts/src/sort/BogoSort.java +++ b/Sorts/BogoSort.java @@ -1,9 +1,7 @@ -package sort; +package Sorts; import java.util.Random; -import static sort.SortUtils.*; - /** * @@ -19,7 +17,7 @@ public class BogoSort implements SortAlgorithm { private static > boolean isSorted(T array[]){ for(int i = 0; i void nextPermutation(T array[]){ for (int i = 0; i < array.length; i++) { int randomIndex = i + random.nextInt(length - i); - swap(array, randomIndex, i); + SortUtils.swap(array, randomIndex, i); } } @@ -49,11 +47,11 @@ public static void main(String[] args) { BogoSort bogoSort = new BogoSort(); // print a sorted array - print(bogoSort.sort(integers)); + SortUtils.print(bogoSort.sort(integers)); // String Input String[] strings = {"c", "a", "e", "b","d"}; - print(bogoSort.sort(strings)); + SortUtils.print(bogoSort.sort(strings)); } } diff --git a/Sorts/src/sort/BubbleSort.java b/Sorts/BubbleSort.java similarity index 96% rename from Sorts/src/sort/BubbleSort.java rename to Sorts/BubbleSort.java index 1173245fcabf..274979a456b1 100644 --- a/Sorts/src/sort/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** * diff --git a/Sorts/src/sort/CocktailShakerSort.java b/Sorts/CocktailShakerSort.java similarity index 79% rename from Sorts/src/sort/CocktailShakerSort.java rename to Sorts/CocktailShakerSort.java index 7982b8fcfcae..5f4b89942645 100644 --- a/Sorts/src/sort/CocktailShakerSort.java +++ b/Sorts/CocktailShakerSort.java @@ -1,6 +1,4 @@ -package sort; - -import static sort.SortUtils.*; +package Sorts; /** * @@ -29,8 +27,8 @@ public > T[] sort(T[] array) { // front swappedRight = 0; for (int i = left; i < right; i++) { - if (less(array[i + 1], array[i])) { - swap(array, i, i + 1); + if (SortUtils.less(array[i + 1], array[i])) { + SortUtils.swap(array, i, i + 1); swappedRight = i; } } @@ -38,8 +36,8 @@ public > T[] sort(T[] array) { right = swappedRight; swappedLeft = length - 1; for (int j = right; j > left; j--) { - if (less(array[j], array[j - 1])) { - swap(array, j - 1, j); + if (SortUtils.less(array[j], array[j - 1])) { + SortUtils.swap(array, j - 1, j); swappedLeft = j; } } @@ -56,11 +54,11 @@ public static void main(String[] args) { CocktailShakerSort shakerSort = new CocktailShakerSort(); // Output => 1 4 6 9 12 23 54 78 231 - print(shakerSort.sort(integers)); + SortUtils.print(shakerSort.sort(integers)); // String Input String[] strings = { "c", "a", "e", "b", "d" }; - print(shakerSort.sort(strings)); + SortUtils.print(shakerSort.sort(strings)); } diff --git a/Sorts/src/sort/CombSort.java b/Sorts/CombSort.java similarity index 97% rename from Sorts/src/sort/CombSort.java rename to Sorts/CombSort.java index 492605ca56e7..83e24edaec9c 100644 --- a/Sorts/src/sort/CombSort.java +++ b/Sorts/CombSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** diff --git a/Sorts/src/sort/CountingSort.java b/Sorts/CountingSort.java similarity index 98% rename from Sorts/src/sort/CountingSort.java rename to Sorts/CountingSort.java index 39442a00fbb8..7243a27a9dd4 100644 --- a/Sorts/src/sort/CountingSort.java +++ b/Sorts/CountingSort.java @@ -1,4 +1,4 @@ -package sort; +package Sorts; import java.util.*; import java.util.stream.IntStream; @@ -6,7 +6,7 @@ import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; -import static sort.SortUtils.print; +import static Sorts.SortUtils.print; /** * diff --git a/Sorts/src/sort/CycleSort.java b/Sorts/CycleSort.java similarity index 95% rename from Sorts/src/sort/CycleSort.java rename to Sorts/CycleSort.java index ea4f05535c7a..eba541a061e8 100644 --- a/Sorts/src/sort/CycleSort.java +++ b/Sorts/CycleSort.java @@ -1,7 +1,7 @@ -package sort; +package Sorts; -import static sort.SortUtils.less; -import static sort.SortUtils.print; +import static Sorts.SortUtils.less; +import static Sorts.SortUtils.print; /** * @author Podshivalov Nikita (https://github.com/nikitap492) diff --git a/Sorts/src/sort/GnomeSort.java b/Sorts/GnomeSort.java similarity index 95% rename from Sorts/src/sort/GnomeSort.java rename to Sorts/GnomeSort.java index 14af67c65bb6..ef5dca141436 100644 --- a/Sorts/src/sort/GnomeSort.java +++ b/Sorts/GnomeSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** * Implementation of gnome sort diff --git a/Sorts/src/sort/HeapSort.java b/Sorts/HeapSort.java similarity index 98% rename from Sorts/src/sort/HeapSort.java rename to Sorts/HeapSort.java index 6fab3747fd2f..9be2c2e70345 100644 --- a/Sorts/src/sort/HeapSort.java +++ b/Sorts/HeapSort.java @@ -1,10 +1,10 @@ -package sort; +package Sorts; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** * Heap Sort Algorithm diff --git a/Sorts/src/sort/InsertionSort.java b/Sorts/InsertionSort.java similarity index 93% rename from Sorts/src/sort/InsertionSort.java rename to Sorts/InsertionSort.java index 593614304c5b..f29c3537ce0d 100644 --- a/Sorts/src/sort/InsertionSort.java +++ b/Sorts/InsertionSort.java @@ -1,7 +1,7 @@ -package sort; +package Sorts; -import static sort.SortUtils.less; -import static sort.SortUtils.print; +import static Sorts.SortUtils.less; +import static Sorts.SortUtils.print; /** * diff --git a/Sorts/src/sort/MergeSort.java b/Sorts/MergeSort.java similarity index 98% rename from Sorts/src/sort/MergeSort.java rename to Sorts/MergeSort.java index 2c7a141bdc32..3c4fa4a2b99a 100644 --- a/Sorts/src/sort/MergeSort.java +++ b/Sorts/MergeSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.print; +import static Sorts.SortUtils.print; /** * This method implements the Generic Merge Sort diff --git a/Sorts/src/sort/PancakeSort.java b/Sorts/PancakeSort.java similarity index 95% rename from Sorts/src/sort/PancakeSort.java rename to Sorts/PancakeSort.java index 902db4b39cb8..395b75f93a75 100644 --- a/Sorts/src/sort/PancakeSort.java +++ b/Sorts/PancakeSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** * Implementation of gnome sort diff --git a/Sorts/src/sort/QuickSort.java b/Sorts/QuickSort.java similarity index 97% rename from Sorts/src/sort/QuickSort.java rename to Sorts/QuickSort.java index 4159fc829881..36b042c13821 100644 --- a/Sorts/src/sort/QuickSort.java +++ b/Sorts/QuickSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** * diff --git a/Sorts/src/sort/RadixSort.java b/Sorts/RadixSort.java similarity index 98% rename from Sorts/src/sort/RadixSort.java rename to Sorts/RadixSort.java index 0d1e6966101a..9fd1ab7b8356 100644 --- a/Sorts/src/sort/RadixSort.java +++ b/Sorts/RadixSort.java @@ -1,4 +1,4 @@ -package sort; +package Sorts; import java.util.Arrays; diff --git a/Sorts/src/sort/SelectionSort.java b/Sorts/SelectionSort.java similarity index 87% rename from Sorts/src/sort/SelectionSort.java rename to Sorts/SelectionSort.java index 960215a686d2..7ab599f943f2 100644 --- a/Sorts/src/sort/SelectionSort.java +++ b/Sorts/SelectionSort.java @@ -1,6 +1,4 @@ -package sort; - -import static sort.SortUtils.*; +package Sorts; /** * @@ -27,14 +25,14 @@ public > T[] sort(T[] arr) { int min = i; for (int j = i +1 ; j < n; j++) { - if (less(arr[j], arr[min])) { + if (SortUtils.less(arr[j], arr[min])) { min = j; } } // Swapping if index of min is changed if (min != i) { - swap(arr, i , min); + SortUtils.swap(arr, i , min); } } @@ -51,13 +49,13 @@ public static void main(String[] args) { Integer[] sorted = selectionSort.sort(arr); // Output => 1 4 6 9 12 23 54 78 231 - print(sorted); + SortUtils.print(sorted); // String Input String[] strings = {"c", "a", "e", "b","d"}; String[] sortedStrings = selectionSort.sort(strings); //Output => a b c d e - print(sortedStrings); + SortUtils.print(sortedStrings); } } diff --git a/Sorts/src/sort/ShellSort.java b/Sorts/ShellSort.java similarity index 94% rename from Sorts/src/sort/ShellSort.java rename to Sorts/ShellSort.java index bafd19b145d7..31c2c6077897 100644 --- a/Sorts/src/sort/ShellSort.java +++ b/Sorts/ShellSort.java @@ -1,6 +1,6 @@ -package sort; +package Sorts; -import static sort.SortUtils.*; +import static Sorts.SortUtils.*; /** diff --git a/Sorts/src/sort/SortAlgorithm.java b/Sorts/SortAlgorithm.java similarity index 98% rename from Sorts/src/sort/SortAlgorithm.java rename to Sorts/SortAlgorithm.java index 46b1f58e128f..e6004156559b 100644 --- a/Sorts/src/sort/SortAlgorithm.java +++ b/Sorts/SortAlgorithm.java @@ -1,4 +1,4 @@ -package sort; +package Sorts; import java.util.Arrays; import java.util.List; diff --git a/Sorts/src/sort/SortUtils.java b/Sorts/SortUtils.java similarity index 99% rename from Sorts/src/sort/SortUtils.java rename to Sorts/SortUtils.java index 8766e9d0e4d7..b3392352becd 100644 --- a/Sorts/src/sort/SortUtils.java +++ b/Sorts/SortUtils.java @@ -1,4 +1,4 @@ -package sort; +package Sorts; import java.util.Arrays; import java.util.List; From c4f7a45ed236fb1dd2d733b4a5d1863a2ff57145 Mon Sep 17 00:00:00 2001 From: 1700022814 <512620936@qq.com> Date: Sun, 18 Nov 2018 16:22:08 +0800 Subject: [PATCH 045/112] fix BinaryTree.java put method#644 --- DataStructures/Trees/BinaryTree.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java index a20d24eebc35..0c6e89cd36ae 100644 --- a/DataStructures/Trees/BinaryTree.java +++ b/DataStructures/Trees/BinaryTree.java @@ -69,8 +69,12 @@ public Node find(int key) { Node current = root; while (current != null) { if(key < current.data) { + if(current.left == null) + return current; //The key isn't exist, returns the parent current = current.left; } else if(key > current.data) { + if(current.right == null) + return current; current = current.right; } else { // If you find the value return it return current; From 21d8937baa0198563cd545639eaa20b298c63229 Mon Sep 17 00:00:00 2001 From: Shoaib Rayeen Date: Wed, 21 Nov 2018 05:22:24 +0530 Subject: [PATCH 046/112] Optimized Version [Without Hashmap & recursion] --- Dynamic Programming/Fibonacci.java | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index b2524b4db471..d177b5bb9c5d 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -29,6 +29,10 @@ public static void main(String[] args) throws Exception { * Outputs the nth fibonacci number **/ + + + + private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); @@ -71,5 +75,35 @@ private static int fibBotUp(int n) { return fib.get(n); } + + + + /** + * This method finds the nth fibonacci number using bottom up + * + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) + * @param n The input n for which we have to determine the fibonacci number + * Outputs the nth fibonacci number + * + * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. + * It saves both memory and time. + * Space Complexity will be O(1) + * Time Complexity will be O(n) + * + * Whereas , the above functions will take O(n) Space. + **/ + private static int fibOptimized(int n) { + + if (n == 0) { + return 0; + } + int prev = 0 , res = 1 , next; + for ( int i = 2; i < n; i++) { + next = prev + res; + prev = res; + res = next; + } + return res; + } } From 80674d128dba62f281bda14aa3050d5e27af90e1 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Thu, 6 Dec 2018 23:05:01 +0900 Subject: [PATCH 047/112] translate readme into korean language To help Korean Student Study Algorithm easier --- README-ko.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 README-ko.md diff --git a/README-ko.md b/README-ko.md new file mode 100644 index 000000000000..aac05a0a7e0d --- /dev/null +++ b/README-ko.md @@ -0,0 +1 @@ +한글 리드미 만들기 From 915410078442be230736ccbd7b7bc3b82bd9f9a1 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Thu, 6 Dec 2018 23:14:58 +0900 Subject: [PATCH 048/112] README-kor update 1 --- README-ko.md | 197 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 196 insertions(+), 1 deletion(-) diff --git a/README-ko.md b/README-ko.md index aac05a0a7e0d..3b2a44c63184 100644 --- a/README-ko.md +++ b/README-ko.md @@ -1 +1,196 @@ -한글 리드미 만들기 +# 알고리즘 - ìžë°” + +## ì´ [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)는 기존 프로ì íŠ¸ë¥¼ Java 프로ì íЏ 구조로 재개발하기 위해 작성ë˜ì—ˆë‹¤. 기여ë„를 위해 개발 지사로 전환할 수 있다. ìžì„¸í•œ ë‚´ìš©ì€ ì´ ë¬¸ì œë¥¼ 참조하십시오. ì»¨íŠ¸ë¦¬ë·°ì…˜ì„ ìœ„í•´ [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)로 전환할 수 있다. ìžì„¸í•œ ë‚´ìš©ì€ [ì´ ì´ìŠˆ](https://github.com/TheAlgorithms/Java/issues/474)를 참고하십시오. + +### 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. + +## Sort Algorithms + + +### Bubble +![alt text][bubble-image] + +From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][bubble-toptal] + + + +### Insertion +![alt text][insertion-image] + +From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. +In the figure, each bar represents an element of an array that needs to be sorted. What happens at the first intersection of the top most and second top most bars is to swap these elements, represented by bars, because the second element has a higher precedence than the first element does. By repeating this method, insertion sort completes sorting. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n) +* Average case performance O(n^2) + +###### View the algorithm in [action][insertion-toptal] + + +### Merge +![alt text][merge-image] + +From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelt mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. + +__Properties__ +* Worst case performance O(n log n) (typical) +* Best case performance O(n log n) +* Average case performance O(n log n) + + +###### View the algorithm in [action][merge-toptal] + +### Quick +![alt text][quick-image] + +From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n log n) or O(n) with three-way partition +* Average case performance O(n log n) + +###### View the algorithm in [action][quick-toptal] + +### Selection +![alt text][selection-image] + +From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. + +__Properties__ +* Worst case performance O(n^2) +* Best case performance O(n^2) +* Average case performance O(n^2) + +###### View the algorithm in [action][selection-toptal] + +### Shell +![alt text][shell-image] + +From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. + +__Properties__ +* Worst case performance O(nlog2 2n) +* Best case performance O(n log n) +* Average case performance depends on gap sequence + +###### View the algorithm in [action][shell-toptal] + +### Time-Compexity Graphs + +Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) + +[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) + +---------------------------------------------------------------------------------- + +## Search Algorithms + +### Linear +![alt text][linear-image] + +From [Wikipedia][linear-wiki]: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. + The linear search runs in at the worst linear time and makes at most n comparisons, where n is the length of the list. + +__Properties__ +* Worst case performance O(n) +* Best case performance O(1) +* Average case performance O(n) +* Worst case space complexity O(1) iterative + +### Binary +![alt text][binary-image] + +From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. + +__Properties__ +* Worst case performance O(log n) +* Best case performance O(1) +* Average case performance O(log n) +* Worst case space complexity O(1) + +From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. + +__Properties__ +* Worst case performance O(nlog2 2n) +* Best case performance O(n log n) +* Average case performance depends on gap sequence + +###### View the algorithm in [action][shell-toptal] + +[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort +[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort +[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" + +[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort +[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort +[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort" + +[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort +[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort +[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort" + +[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort +[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort +[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort" + +[selection-toptal]: https://www.toptal.com/developers/sorting-algorithms/selection-sort +[selection-wiki]: https://en.wikipedia.org/wiki/Selection_sort +[selection-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Selection_sort_animation.gif/250px-Selection_sort_animation.gif "Selection Sort Sort" + +[shell-toptal]: https://www.toptal.com/developers/sorting-algorithms/shell-sort +[shell-wiki]: https://en.wikipedia.org/wiki/Shellsort +[shell-image]: https://upload.wikimedia.org/wikipedia/commons/d/d8/Sorting_shellsort_anim.gif "Shell Sort" + +[linear-wiki]: https://en.wikipedia.org/wiki/Linear_search +[linear-image]: http://www.tutorialspoint.com/data_structures_algorithms/images/linear_search.gif + +[binary-wiki]: https://en.wikipedia.org/wiki/Binary_search_algorithm +[binary-image]: https://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_search_into_array.png + + +-------------------------------------------------------------------- +## Links to the rest of the algorithms + +Conversions | Dynamic Programming |Ciphers|Miscellaneous| +----------- |----------------------------------------------------------------|-------|-------------| +[Any Base to Any Base](Conversions/AnyBaseToAnyBase.java)| [Coin Change](Dynamic%20Programming/CoinChange.java)|[Caesar](ciphers/Caesar.java)|[Heap Sort](misc/heap_sort.java)| +[Any Base to Decimal](Conversions/AnyBaseToDecimal.java)|[Egg Dropping](Dynamic%20Programming/EggDropping.java)|[Columnar Transposition Cipher](ciphers/ColumnarTranspositionCipher.java)|[Palindromic Prime Checker](misc/PalindromicPrime.java)| +[Binary to Decimal](Conversions/BinaryToDecimal.java)|[Fibonacci](Dynamic%20Programming/Fibonacci.java)|[RSA](ciphers/RSA.java)|More soon...| +[Binary to HexaDecimal](Conversions/BinaryToHexadecimal.java)|[Kadane Algorithm](Dynamic%20Programming/KadaneAlgorithm.java)|more coming soon...| +[Binary to Octal](Conversions/BinaryToOctal.java)|[Knapsack](Dynamic%20Programming/Knapsack.java)| +[Decimal To Any Base](Conversions/DecimalToAnyBase.java)|[Longest Common Subsequence](Dynamic%20Programming/LongestCommonSubsequence.java)| +[Decimal To Binary](Conversions/DecimalToBinary.java)|[Longest Increasing Subsequence](Dynamic%20Programming/LongestIncreasingSubsequence.java)| +[Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java)|[Rod Cutting](Dynamic%20Programming/RodCutting.java)| +and much more...| and more...| + +### Data Structures +Graphs|Heaps|Lists|Queues| +------|-----|-----|------| +[BFS](DataStructures/Graphs/BFS.java)|[Empty Heap Exception](DataStructures/Heaps/EmptyHeapException.java)|[Circle Linked List](DataStructures/Lists/CircleLinkedList.java)|[Generic Array List Queue](DataStructures/Queues/GenericArrayListQueue.java)| +[DFS](DataStructures/Graphs/DFS.java)|[Heap](DataStructures/Heaps/Heap.java)|[Doubly Linked List](DataStructures/Lists/DoublyLinkedList.java)|[Queues](DataStructures/Queues/Queues.java)| +[Graphs](DataStructures/Graphs/Graphs.java)|[Heap Element](DataStructures/Heaps/HeapElement.java)|[Singly Linked List](DataStructures/Lists/SinglyLinkedList.java)| +[Kruskals Algorithm](DataStructures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)| +[Matrix Graphs](DataStructures/Graphs/MatrixGraphs.java)|[Min Heap](DataStructures/Heaps/MinHeap.java)| +[PrimMST](DataStructures/Graphs/PrimMST.java)| + +Stacks|Trees| +------|-----| +[Node Stack](DataStructures/Stacks/NodeStack.java)|[AVL Tree](DataStructures/Trees/AVLTree.java)| +[Stack of Linked List](DataStructures/Stacks/StackOfLinkedList.java)|[Binary Tree](DataStructures/Trees/BinaryTree.java)| +[Stacks](DataStructures/Stacks/Stacks.java)|And much more...| + +* [Bags](DataStructures/Bags/Bag.java) +* [Buffer](DataStructures/Buffers/CircularBuffer.java) +* [HashMap](DataStructures/HashMap/HashMap.java) +* [Matrix](DataStructures/Matrix/Matrix.java) From 52961998f6451f276ed862d40eb829851f38b8d5 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Thu, 6 Dec 2018 23:25:57 +0900 Subject: [PATCH 049/112] README-kor translated till bubble sort --- README-ko.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README-ko.md b/README-ko.md index 3b2a44c63184..b075dc09f403 100644 --- a/README-ko.md +++ b/README-ko.md @@ -2,22 +2,22 @@ ## ì´ [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)는 기존 프로ì íŠ¸ë¥¼ Java 프로ì íЏ 구조로 재개발하기 위해 작성ë˜ì—ˆë‹¤. 기여ë„를 위해 개발 지사로 전환할 수 있다. ìžì„¸í•œ ë‚´ìš©ì€ ì´ ë¬¸ì œë¥¼ 참조하십시오. ì»¨íŠ¸ë¦¬ë·°ì…˜ì„ ìœ„í•´ [개발브런치](https://github.com/TheAlgorithms/Java/tree/Development)로 전환할 수 있다. ìžì„¸í•œ ë‚´ìš©ì€ [ì´ ì´ìŠˆ](https://github.com/TheAlgorithms/Java/issues/474)를 참고하십시오. -### 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. +ì´ê²ƒë“¤ì€ 단지 ì‹œë²”ì„ ìœ„í•œ 것ì´ë‹¤. 표준 ìžë°” ë¼ì´ë¸ŒëŸ¬ë¦¬ì—는 성능ìƒì˜ ì´ìœ ë¡œ ë” ë‚˜ì€ ê²ƒë“¤ì´ êµ¬í˜„ë˜ì–´ìžˆë‹¤ -## Sort Algorithms +## ì •ë ¬ 알고리즘 -### Bubble +### Bubble(버블 소트) ![alt text][bubble-image] -From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. +From [Wikipedia][bubble-wiki]: 버블 소트(sinking sorë¼ê³ ë„ 불리움)는 리스트를 반복ì ì¸ 단계로 접근하여 정렬한다. ê°ê°ì˜ ì§ì„ 비êµí•˜ë©°, 순서가 ìž˜ëª»ëœ ê²½ìš° 그접한 ì•„ì´í…œë“¤ì„ 스왑하는 알고리즘ì´ë‹¤. ë” ì´ìƒ 스왑할 ê²ƒì´ ì—†ì„ ë•Œê¹Œì§€ 반복하며, ë°˜ë³µì´ ëë‚¨ìŒ ë¦¬ìŠ¤íŠ¸ê°€ ì •ë ¬ë˜ì—ˆìŒì„ ì˜ë¯¸í•œë‹¤. -__Properties__ -* Worst case performance O(n^2) -* Best case performance O(n) -* Average case performance O(n^2) +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(n^2) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n) +* í‰ê·  성능 O(n^2) ###### View the algorithm in [action][bubble-toptal] From 3167e87049eb5847f02a52586a94a2fe3d9e5848 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Thu, 6 Dec 2018 23:32:07 +0900 Subject: [PATCH 050/112] README-ko translatie ~insertion sort --- README-ko.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/README-ko.md b/README-ko.md index b075dc09f403..f28bbb2c502b 100644 --- a/README-ko.md +++ b/README-ko.md @@ -9,7 +9,7 @@ ## ì •ë ¬ 알고리즘 -### Bubble(버블 소트) +### Bubble(버블 ì •ë ¬) ![alt text][bubble-image] From [Wikipedia][bubble-wiki]: 버블 소트(sinking sorë¼ê³ ë„ 불리움)는 리스트를 반복ì ì¸ 단계로 접근하여 정렬한다. ê°ê°ì˜ ì§ì„ 비êµí•˜ë©°, 순서가 ìž˜ëª»ëœ ê²½ìš° 그접한 ì•„ì´í…œë“¤ì„ 스왑하는 알고리즘ì´ë‹¤. ë” ì´ìƒ 스왑할 ê²ƒì´ ì—†ì„ ë•Œê¹Œì§€ 반복하며, ë°˜ë³µì´ ëë‚¨ìŒ ë¦¬ìŠ¤íŠ¸ê°€ ì •ë ¬ë˜ì—ˆìŒì„ ì˜ë¯¸í•œë‹¤. @@ -23,16 +23,15 @@ __ì†ì„±__ -### Insertion +### Insertion(삽입 ì •ë ¬) ![alt text][insertion-image] -From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. -In the figure, each bar represents an element of an array that needs to be sorted. What happens at the first intersection of the top most and second top most bars is to swap these elements, represented by bars, because the second element has a higher precedence than the first element does. By repeating this method, insertion sort completes sorting. +From [Wikipedia][insertion-wiki]: 삽입 ì •ë ¬ì€ ìµœì¢… ì •ë ¬ëœ ë°°ì—´(ë˜ëŠ” 리스트)ì„ í•œë²ˆì— í•˜ë‚˜ì”© 구축하는 알고리즘ì´ë‹¤. ì´ê²ƒì€ í° ë¦¬ìŠ¤íŠ¸ì—서 ë” ë‚˜ì€ ì•Œê³ ë¦¬ì¦˜ì¸ í€µ 소트, íž™ 소트, ë˜ëŠ” 머지 소트보다 훨씬 ì•ˆì¢‹ì€ íš¨ìœ¨ì„ ê°€ì§„ë‹¤. 그림ì—서 ê° ë§‰ëŒ€ëŠ” 정렬해야 하는 ë°°ì—´ì˜ ìš”ì†Œë¥¼ 나타낸다. ìƒë‹¨ê³¼ ë‘ ë²ˆì§¸ ìƒë‹¨ ë§‰ëŒ€ì˜ ì²« 번째 êµì°¨ì ì—서 ë°œìƒí•˜ëŠ” ê²ƒì€ ë‘ ë²ˆì§¸ 요소가 첫 번째 요소보다 ë” ë†’ì€ ìš°ì„  순위를 가지기 ë–„ë¬¸ì— ë§‰ëŒ€ë¡œ 표시ë˜ëŠ” ì´ëŸ¬í•œ 요소를 êµí™˜í•œ 것ì´ë‹¤. ì´ ë°©ë²•ì„ ë°˜ë³µí•˜ë©´ 삽입 ì •ë ¬ì´ ì™„ë£Œëœë‹¤. -__Properties__ -* Worst case performance O(n^2) -* Best case performance O(n) -* Average case performance O(n^2) +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(n^2) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n) +* í‰ê·  O(n^2) ###### View the algorithm in [action][insertion-toptal] From a607bb956118e5862455ad70669fdeddcef47f46 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 06:24:03 +0900 Subject: [PATCH 051/112] Update README-ko.md ~merge --- README-ko.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README-ko.md b/README-ko.md index f28bbb2c502b..6282a5bf1b55 100644 --- a/README-ko.md +++ b/README-ko.md @@ -36,15 +36,15 @@ __ì†ì„±__ ###### View the algorithm in [action][insertion-toptal] -### Merge +### Merge(합병 ì •ë ¬) ![alt text][merge-image] -From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelt mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945. +From [Wikipedia][merge-wiki]: 컴퓨터 과학ì—서, 합병 ì •ë ¬ì€ íš¨ìœ¨ì ì¸, 범용ì ì¸, ë¹„êµ ê¸°ë°˜ ì •ë ¬ 알고리즘ì´ë‹¤. ëŒ€ë¶€ë¶„ì˜ êµ¬í˜„ì€ ì•ˆì •ì ì¸ 분류를 ì´ë£¨ëŠ”ë°, ì´ê²ƒì€ êµ¬í˜„ì´ ì •ë ¬ëœ ì¶œë ¥ì— ë™ì¼í•œ ìš”ì†Œì˜ ìž…ë ¥ 순서를 유지한다는 ê²ƒì„ ì˜ë¯¸í•œë‹¤. 합병 ì •ë ¬ì€ 1945ë…„ì— John von Neumannì´ ë°œëª…í•œ ë¶„í•  ì •ë³µ 알고리즘ì´ë‹¤. __Properties__ -* Worst case performance O(n log n) (typical) -* Best case performance O(n log n) -* Average case performance O(n log n) +* ìµœì•…ì˜ ì„±ëŠ¥ O(n log n) (ì¼ë°˜ì ) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n log n) +* í‰ê·  O(n log n) ###### View the algorithm in [action][merge-toptal] From 4723e5fbe7eb877c75286be1e84c12ad0616535c Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 06:33:01 +0900 Subject: [PATCH 052/112] Update README-ko.md ~selection sort --- README-ko.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README-ko.md b/README-ko.md index 6282a5bf1b55..0173c0f0a68c 100644 --- a/README-ko.md +++ b/README-ko.md @@ -41,7 +41,7 @@ __ì†ì„±__ From [Wikipedia][merge-wiki]: 컴퓨터 과학ì—서, 합병 ì •ë ¬ì€ íš¨ìœ¨ì ì¸, 범용ì ì¸, ë¹„êµ ê¸°ë°˜ ì •ë ¬ 알고리즘ì´ë‹¤. ëŒ€ë¶€ë¶„ì˜ êµ¬í˜„ì€ ì•ˆì •ì ì¸ 분류를 ì´ë£¨ëŠ”ë°, ì´ê²ƒì€ êµ¬í˜„ì´ ì •ë ¬ëœ ì¶œë ¥ì— ë™ì¼í•œ ìš”ì†Œì˜ ìž…ë ¥ 순서를 유지한다는 ê²ƒì„ ì˜ë¯¸í•œë‹¤. 합병 ì •ë ¬ì€ 1945ë…„ì— John von Neumannì´ ë°œëª…í•œ ë¶„í•  ì •ë³µ 알고리즘ì´ë‹¤. -__Properties__ +__ì†ì„±__ * ìµœì•…ì˜ ì„±ëŠ¥ O(n log n) (ì¼ë°˜ì ) * ìµœê³ ì˜ ì„±ëŠ¥ O(n log n) * í‰ê·  O(n log n) @@ -49,25 +49,25 @@ __Properties__ ###### View the algorithm in [action][merge-toptal] -### Quick +### Quick(퀵 ì •ë ¬) ![alt text][quick-image] -From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. +From [Wikipedia][quick-wiki]: 퀵 ì •ë ¬sometimes called partition-exchange sort)ì€ íš¨ìœ¨ì ì¸ ì •ë ¬ 알고리즘으로, ë°°ì—´ì˜ ìš”ì†Œë¥¼ 순서대로 정렬하는 체계ì ì¸ 방법 ì—­í™œì„ í•œë‹¤. -__Properties__ -* Worst case performance O(n^2) -* Best case performance O(n log n) or O(n) with three-way partition -* Average case performance O(n log n) +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(n^2) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n log n) or O(n) with three-way partition +* í‰ê·  O(n log n) ###### View the algorithm in [action][quick-toptal] -### Selection +### Selection(ì„ íƒ ì •ë ¬) ![alt text][selection-image] -From [Wikipedia][selection-wiki]: The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right. +From [Wikipedia][selection-wiki]: 알고리즘 ìž…ë ¥ 리스트를 ë‘ ë¶€ë¶„ìœ¼ë¡œ 나눈다 : 첫 ë¶€ë¶„ì€ ì•„ì´í…œë“¤ì´ ì´ë¯¸ 왼쪽ì—서 오른쪽으로 ì •ë ¬ë˜ì—ˆë‹¤. 그리고 ë‚¨ì€ ë¶€ë¶„ì˜ ì•„ì´í…œë“¤ì€ 나머지 í•­ëª©ì„ ì°¨ì§€í•˜ëŠ” 리스트ì´ë‹¤. 처ìŒì—는 ì •ë ¬ëœ ë¦¬ìŠ¤íŠ¸ëŠ” 공백ì´ê³  나머지가 ì „ë¶€ì´ë‹¤. 오르차순(ë˜ëŠ” 내림차순) ì•Œê³ ë¦¬ì¦˜ì€ ê°€ìž¥ ìž‘ì€ ìš”ì†Œë¥¼ ì •ë ¬ë˜ì§€ ì•Šì€ ë¦¬ìŠ¤íŠ¸ì—서 찾고 ì •ë ¬ì´ ì•ˆëœ ê°€ìž¥ 왼쪽(ì •ë ¬ëœ ë¦¬ìŠ¤íŠ¸) 리스트와 바꾼다. ì´ë ‡ê²Œ 오른쪽으로 나아간다. -__Properties__ -* Worst case performance O(n^2) +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(n^2) * Best case performance O(n^2) * Average case performance O(n^2) From cbd3ac6ea9a17728743feb292dc83aa07969728a Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 06:36:51 +0900 Subject: [PATCH 053/112] Update README-ko.md ~shell --- README-ko.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README-ko.md b/README-ko.md index 0173c0f0a68c..7cf4863b2729 100644 --- a/README-ko.md +++ b/README-ko.md @@ -68,19 +68,19 @@ From [Wikipedia][selection-wiki]: 알고리즘 ìž…ë ¥ 리스트를 ë‘ ë¶€ë¶„ìœ¼ __ì†ì„±__ * ìµœì•…ì˜ ì„±ëŠ¥ O(n^2) -* Best case performance O(n^2) -* Average case performance O(n^2) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n^2) +* í‰ê·  O(n^2) ###### View the algorithm in [action][selection-toptal] -### Shell +### Shell(쉘 ì •ë ¬) ![alt text][shell-image] -From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. +From [Wikipedia][shell-wiki]: 쉘 ì •ë ¬ì€ ë©€ë¦¬ 떨어져 있는 í•­ëª©ì˜ êµí™˜ì„ 허용하는 삽입 ì¢…ë¥˜ì˜ ì¼ë°˜í™”ì´ë‹¤. ê·¸ ì•„ì´ë””어는 모든 n번째 요소가 ì •ë ¬ëœ ëª©ë¡ì„ 제공한다는 ê²ƒì„ ê³ ë ¤í•˜ì—¬ ì–´ëŠ ê³³ì—서든지 시작하ë„ë¡ ìš”ì†Œì˜ ëª©ë¡ì„ 배열하는 것ì´ë‹¤. ì´ëŸ¬í•œ 목ë¡ì€ h-sorted로 알려져 있다. 마찬가지로, ê°ê° 개별ì ìœ¼ë¡œ ì •ë ¬ëœ h ì¸í„°ë¦¬ë¸Œ 목ë¡ìœ¼ë¡œ ê°„ì£¼ë  ìˆ˜ 있다. -__Properties__ -* Worst case performance O(nlog2 2n) -* Best case performance O(n log n) +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(nlog2 2n) +* ìµœê³ ì˜ ì„±ëŠ¥ O(n log n) * Average case performance depends on gap sequence ###### View the algorithm in [action][shell-toptal] From 23f0342499a78119b42710fb3b80ebb0b425d708 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 06:38:43 +0900 Subject: [PATCH 054/112] Update README.md fix word --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d08658198c6..3d589a2f79c2 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ __Properties__ ###### View the algorithm in [action][shell-toptal] -### Time-Compexity Graphs +### Time-Complexity Graphs Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) From c3bce80b14c85580f23beda2664d00c0b5b92118 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 07:32:53 +0900 Subject: [PATCH 055/112] Update README-ko.md ~linear sesarch --- README-ko.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README-ko.md b/README-ko.md index 7cf4863b2729..058705ca938b 100644 --- a/README-ko.md +++ b/README-ko.md @@ -85,29 +85,29 @@ __ì†ì„±__ ###### View the algorithm in [action][shell-toptal] -### Time-Compexity Graphs +### 시간 복잡성 그래프 -Comparing the complexity of sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort) +ì •ë ¬ ì•Œê³ ë¦¬ì¦˜ì˜ ë³µìž¡ì„± ë¹„êµ (버블 ì •ë ¬, 삽입 ì •ë ¬, ì„ íƒ ì •ë ¬) -[Complexity Graphs](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) +[복잡성 그래프](https://github.com/prateekiiest/Python/blob/master/sorts/sortinggraphs.png) ---------------------------------------------------------------------------------- -## Search Algorithms +## 검색 알고리즘 -### Linear +### Linear (선형 íƒìƒ‰) ![alt text][linear-image] -From [Wikipedia][linear-wiki]: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. - The linear search runs in at the worst linear time and makes at most n comparisons, where n is the length of the list. +From [Wikipedia][linear-wiki]: 선형 íƒìƒ‰ ë˜ëŠ” 순차 íƒìƒ‰ì€ ëª©ë¡ ë‚´ì—서 ëª©í‘œê°’ì„ ì°¾ëŠ” 방법ì´ë‹¤. ì¼ì¹˜ í•­ëª©ì´ ë°œê²¬ë˜ê±°ë‚˜ 모든 요소가 íƒìƒ‰ë  때까지 목ë¡ì˜ ê° ìš”ì†Œì— ëŒ€í•´ ëª©í‘œê°’ì„ ìˆœì°¨ì ìœ¼ë¡œ 검사한다. + 선형 ê²€ìƒ‰ì€ ìµœì•…ì˜ ì„ í˜• 시간으로 실행ë˜ë©° 최대 nê°œì˜ ë¹„êµì—서 ì´ë£¨ì–´ì§„다. 여기서 nì€ ëª©ë¡ì˜ 길ì´ë‹¤. -__Properties__ -* Worst case performance O(n) -* Best case performance O(1) -* Average case performance O(n) -* Worst case space complexity O(1) iterative +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(n) +* ìµœê³ ì˜ ì„±ëŠ¥ O(1) +* í‰ê·  O(n) +* ìµœì•…ì˜ ê²½ìš° 공간 복잡성 O(1) iterative -### Binary +### Binary (ì´ì§„ íƒìƒ‰) ![alt text][binary-image] From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. From 377d9de301e08003a4b3458dcbd97264ec3f5327 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 07:38:38 +0900 Subject: [PATCH 056/112] Update README-ko.md ~binary search --- README-ko.md | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/README-ko.md b/README-ko.md index 058705ca938b..fb2525c32a9c 100644 --- a/README-ko.md +++ b/README-ko.md @@ -110,20 +110,13 @@ __ì†ì„±__ ### Binary (ì´ì§„ íƒìƒ‰) ![alt text][binary-image] -From [Wikipedia][binary-wiki]: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. +From [Wikipedia][binary-wiki]: ì´ì§„ íƒìƒ‰, (also known as half-interval search or logarithmic search), ì€ ì •ë ¬ëœ ë°°ì—´ ë‚´ì—서 ëª©í‘œê°’ì˜ ìœ„ì¹˜ë¥¼ 찾는 검색 알고리즘ì´ë‹¤. ëª©í‘œê°’ì„ ë°°ì—´ì˜ ì¤‘ê°„ 요소와 비êµí•œë‹¤; 만약 ëª©í‘œê°’ì´ ë™ì¼í•˜ì§€ 않으면, ëª©í‘œë¬¼ì˜ ì ˆë°˜ì´ ì œê±°ë˜ê³  ê²€ìƒ‰ì´ ì„±ê³µí•  때까지 나머지 절반ì—서 게ì†ëœë‹¤. -__Properties__ -* Worst case performance O(log n) -* Best case performance O(1) -* Average case performance O(log n) -* Worst case space complexity O(1) - -From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. - -__Properties__ -* Worst case performance O(nlog2 2n) -* Best case performance O(n log n) -* Average case performance depends on gap sequence +__ì†ì„±__ +* ìµœì•…ì˜ ì„±ëŠ¥ O(log n) +* ìµœê³ ì˜ ì„±ëŠ¥ O(1) +* í‰ê·  O(log n) +* ìµœì•…ì˜ ê²½ìš° 공간 복잡성 O(1) ###### View the algorithm in [action][shell-toptal] From 88f992f6021bebf73883b4b571f27a751b8f584f Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 07:45:45 +0900 Subject: [PATCH 057/112] Update README-ko.md --- README-ko.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README-ko.md b/README-ko.md index fb2525c32a9c..8c2e72928aa6 100644 --- a/README-ko.md +++ b/README-ko.md @@ -118,7 +118,6 @@ __ì†ì„±__ * í‰ê·  O(log n) * ìµœì•…ì˜ ê²½ìš° 공간 복잡성 O(1) -###### View the algorithm in [action][shell-toptal] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort @@ -152,9 +151,9 @@ __ì†ì„±__ -------------------------------------------------------------------- -## Links to the rest of the algorithms +## 나머지 ì•Œê³ ë¦¬ì¦˜ì— ëŒ€í•œ ë§í¬ -Conversions | Dynamic Programming |Ciphers|Miscellaneous| +전환 | 다ì´ë‚˜ë¯¹í”„로그래ë°(DP) |암호|ê·¸ 외 것들| ----------- |----------------------------------------------------------------|-------|-------------| [Any Base to Any Base](Conversions/AnyBaseToAnyBase.java)| [Coin Change](Dynamic%20Programming/CoinChange.java)|[Caesar](ciphers/Caesar.java)|[Heap Sort](misc/heap_sort.java)| [Any Base to Decimal](Conversions/AnyBaseToDecimal.java)|[Egg Dropping](Dynamic%20Programming/EggDropping.java)|[Columnar Transposition Cipher](ciphers/ColumnarTranspositionCipher.java)|[Palindromic Prime Checker](misc/PalindromicPrime.java)| From 1d531d1ca5782f2c41bbc886ce2b72ec108e4114 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 07:46:34 +0900 Subject: [PATCH 058/112] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 3d589a2f79c2..ee9b9e9e899e 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,6 @@ __Properties__ * Best case performance O(n log n) * Average case performance depends on gap sequence -###### View the algorithm in [action][shell-toptal] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort From 68e704d3922435048e7ce585a1ad5237c663241d Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 07:47:36 +0900 Subject: [PATCH 059/112] Update README.md delete duplicate description about shell sort --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index ee9b9e9e899e..9ac45b9ba1b2 100644 --- a/README.md +++ b/README.md @@ -119,14 +119,6 @@ __Properties__ * Average case performance O(log n) * Worst case space complexity O(1) -From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. - -__Properties__ -* Worst case performance O(nlog2 2n) -* Best case performance O(n log n) -* Average case performance depends on gap sequence - - [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort [bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort [bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort" From 4f0e0edbfb10fbc9374056b210713c0b285cb1de Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 08:04:59 +0900 Subject: [PATCH 060/112] Update README-ko.md tranlation finish --- README-ko.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README-ko.md b/README-ko.md index 8c2e72928aa6..0c15ded78e5f 100644 --- a/README-ko.md +++ b/README-ko.md @@ -165,21 +165,21 @@ __ì†ì„±__ [Decimal To Hexadecimal](Conversions/DecimalToHexaDecimal.java)|[Rod Cutting](Dynamic%20Programming/RodCutting.java)| and much more...| and more...| -### Data Structures -Graphs|Heaps|Lists|Queues| +### ìžë£Œ 구조 +그래프|íž™|리스트|í| ------|-----|-----|------| -[BFS](DataStructures/Graphs/BFS.java)|[Empty Heap Exception](DataStructures/Heaps/EmptyHeapException.java)|[Circle Linked List](DataStructures/Lists/CircleLinkedList.java)|[Generic Array List Queue](DataStructures/Queues/GenericArrayListQueue.java)| -[DFS](DataStructures/Graphs/DFS.java)|[Heap](DataStructures/Heaps/Heap.java)|[Doubly Linked List](DataStructures/Lists/DoublyLinkedList.java)|[Queues](DataStructures/Queues/Queues.java)| -[Graphs](DataStructures/Graphs/Graphs.java)|[Heap Element](DataStructures/Heaps/HeapElement.java)|[Singly Linked List](DataStructures/Lists/SinglyLinkedList.java)| -[Kruskals Algorithm](DataStructures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)| -[Matrix Graphs](DataStructures/Graphs/MatrixGraphs.java)|[Min Heap](DataStructures/Heaps/MinHeap.java)| -[PrimMST](DataStructures/Graphs/PrimMST.java)| - -Stacks|Trees| +[너비우선íƒìƒ‰](DataStructures/Graphs/BFS.java)|[빈 íž™ 예외처리](DataStructures/Heaps/EmptyHeapException.java)|[ì›í˜• 연결리스트](DataStructures/Lists/CircleLinkedList.java)|[제너릭 ì–´ë ˆì´ ë¦¬ìŠ¤íŠ¸ í](DataStructures/Queues/GenericArrayListQueue.java)| +[깊ì´ìš°ì„ íƒìƒ‰](DataStructures/Graphs/DFS.java)|[íž™](DataStructures/Heaps/Heap.java)|[ì´ì¤‘ 연결리스트](DataStructures/Lists/DoublyLinkedList.java)|[í](DataStructures/Queues/Queues.java)| +[그래프](DataStructures/Graphs/Graphs.java)|[íž™ 요소](DataStructures/Heaps/HeapElement.java)|[단순 연결리스트](DataStructures/Lists/SinglyLinkedList.java)| +[í¬ë£¨ìŠ¤ì¹¼ 알고리즘](DataStructures/Graphs/KruskalsAlgorithm.java)|[최대힙](Data%Structures/Heaps/MaxHeap.java)| +[행렬 그래프](DataStructures/Graphs/MatrixGraphs.java)|[최소힙](DataStructures/Heaps/MinHeap.java)| +[프림 최소신장트리](DataStructures/Graphs/PrimMST.java)| + +스íƒ|트리| ------|-----| -[Node Stack](DataStructures/Stacks/NodeStack.java)|[AVL Tree](DataStructures/Trees/AVLTree.java)| -[Stack of Linked List](DataStructures/Stacks/StackOfLinkedList.java)|[Binary Tree](DataStructures/Trees/BinaryTree.java)| -[Stacks](DataStructures/Stacks/Stacks.java)|And much more...| +[노드 스íƒ](DataStructures/Stacks/NodeStack.java)|[AVL 트리](DataStructures/Trees/AVLTree.java)| +[연결리스트 스íƒ](DataStructures/Stacks/StackOfLinkedList.java)|[ì´ì§„ 트리](DataStructures/Trees/BinaryTree.java)| +[스íƒ](DataStructures/Stacks/Stacks.java)|And much more...| * [Bags](DataStructures/Bags/Bag.java) * [Buffer](DataStructures/Buffers/CircularBuffer.java) From 15e1ae94298310537c3bbe21083cb2acf44a77d7 Mon Sep 17 00:00:00 2001 From: SunggyuLee <37533101+SunggyuLee@users.noreply.github.com> Date: Sun, 16 Dec 2018 17:17:46 +0900 Subject: [PATCH 061/112] Update README.md duplicate description about shell sort and deleted one. --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index 959f676eafe2..f0fcdd663cbe 100644 --- a/README.md +++ b/README.md @@ -119,14 +119,6 @@ __Properties__ * Average case performance O(log n) * Worst case space complexity O(1) -### Shell -From [Wikipedia][shell-wiki]: Shellsort is a generalization of insertion sort that allows the exchange of items that are far apart. The idea is to arrange the list of elements so that, starting anywhere, considering every nth element gives a sorted list. Such a list is said to be h-sorted. Equivalently, it can be thought of as h interleaved lists, each individually sorted. - -__Properties__ -* Worst case performance O(nlog2 2n) -* Best case performance O(n log n) -* Average case performance depends on gap sequence - ##### View the algorithm in [action][shell-toptal] [bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort From eb67cca42b307b3cd46a51a3cea687851339028e Mon Sep 17 00:00:00 2001 From: Mihir Hindocha Date: Sun, 16 Dec 2018 02:44:01 -0600 Subject: [PATCH 062/112] update README.md The link to the HashMap.java was broken. Directory changed from DataStructures/Hashmap/HashMap.java to DataStructures/Hashmap/Hashing/HashMap.java --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f0fcdd663cbe..a8eb9970cfae 100644 --- a/README.md +++ b/README.md @@ -185,5 +185,5 @@ Stacks|Trees| * [Bags](DataStructures/Bags/Bag.java) * [Buffer](DataStructures/Buffers/CircularBuffer.java) -* [HashMap](DataStructures/HashMap/HashMap.java) +* [HashMap](DataStructures/HashMap/Hashing/HashMap.java) * [Matrix](DataStructures/Matrix/Matrix.java) From 4f07881c425585bbe1fae9b2438146bfe9fd07c1 Mon Sep 17 00:00:00 2001 From: SunggyuLee Date: Wed, 19 Dec 2018 23:02:39 +0900 Subject: [PATCH 063/112] recommand scanner method --- Others/Armstrong.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Others/Armstrong.java b/Others/Armstrong.java index 9267d9eaf648..9bdb31918d19 100644 --- a/Others/Armstrong.java +++ b/Others/Armstrong.java @@ -9,10 +9,10 @@ * */ public class Armstrong { + static Scanner scan; public static void main(String[] args) { - Scanner scan = new Scanner(System.in); - System.out.println("please enter the number"); - int n = scan.nextInt(); + scan = new Scanner(System.in); + int n = inputInt("please enter the number"); boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n); if (isArmstrong) { System.out.println("the number is armstrong"); @@ -42,6 +42,9 @@ public static boolean checkIfANumberIsAmstrongOrNot(int number) { } else { return false; } - + } + private static int inputInt(String string) { + System.out.print(string); + return Integer.parseInt(scan.nextLine()); } } \ No newline at end of file From 42bed5719557512012a13b23b691a571be8ffc86 Mon Sep 17 00:00:00 2001 From: SunggyuLee Date: Wed, 19 Dec 2018 23:24:50 +0900 Subject: [PATCH 064/112] add Ford_Fulkerson Algorithm using dp --- Dynamic Programming/Ford_Fulkerson.java | 71 +++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Dynamic Programming/Ford_Fulkerson.java diff --git a/Dynamic Programming/Ford_Fulkerson.java b/Dynamic Programming/Ford_Fulkerson.java new file mode 100644 index 000000000000..534a9dc9a7df --- /dev/null +++ b/Dynamic Programming/Ford_Fulkerson.java @@ -0,0 +1,71 @@ +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; +import java.util.Vector; + +public class Ford_Fulkerson { + Scanner scan = new Scanner(System.in); + final static int INF = 987654321; + static int V; // edges + static int[][] capacity, flow; + + public static void main(String[] args) { + System.out.println("V : 6"); + V = 6; + capacity = new int[V][V]; + + capacity[0][1] = 12; + capacity[0][3] = 13; + capacity[1][2] = 10; + capacity[2][3] = 13; + capacity[2][4] = 3; + capacity[2][5] = 15; + capacity[3][2] = 7; + capacity[3][4] = 15; + capacity[4][5] = 17; + + System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5)); + } + + private static int networkFlow(int source, int sink) { + flow = new int[V][V]; + int totalFlow = 0; + while (true) { + Vector parent = new Vector<>(V); + for (int i = 0; i < V; i++) + parent.add(-1); + Queue q = new LinkedList<>(); + parent.set(source, source); + q.add(source); + while (!q.isEmpty() && parent.get(sink) == -1) { + int here = q.peek(); + q.poll(); + for (int there = 0; there < V; ++there) + if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) { + q.add(there); + parent.set(there, here); + } + } + if (parent.get(sink) == -1) + break; + + int amount = INF; + String printer = "path : "; + StringBuilder sb = new StringBuilder(); + for (int p = sink; p != source; p = parent.get(p)) { + amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount); + sb.append(p + "-"); + } + sb.append(source); + for (int p = sink; p != source; p = parent.get(p)) { + flow[parent.get(p)][p] += amount; + flow[p][parent.get(p)] -= amount; + } + totalFlow += amount; + printer += sb.reverse() + " / max flow : " + totalFlow; + System.out.println(printer); + } + + return totalFlow; + } +} From 2da7d89123520702c38fbbcb5fee53f88ee2152a Mon Sep 17 00:00:00 2001 From: SunggyuLee Date: Wed, 19 Dec 2018 23:42:15 +0900 Subject: [PATCH 065/112] add Matrix chain multiplication algorithm --- .../MatrixChainMultiplication.java | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Dynamic Programming/MatrixChainMultiplication.java diff --git a/Dynamic Programming/MatrixChainMultiplication.java b/Dynamic Programming/MatrixChainMultiplication.java new file mode 100644 index 000000000000..b22312355aec --- /dev/null +++ b/Dynamic Programming/MatrixChainMultiplication.java @@ -0,0 +1,120 @@ +import java.util.ArrayList; +import java.util.Scanner; + +public class MatrixChainMultiplicationTest { + private static Scanner scan = new Scanner(System.in); + private static ArrayList mArray = new ArrayList<>(); + private static int size; + private static int[][] m; + private static int[][] s; + private static int[] p; + + public static void main(String[] args) { + int count = 1; + while(true) { + String [] mSize = input("input size of matrix A("+count+") ( ex. 10 20 ) : "); + int col = Integer.parseInt(mSize[0]); + if (col==0) break; + int row = Integer.parseInt(mSize[1]); + + Matrix matrix = new Matrix(count, col, row); + mArray.add(matrix); + count++; + } + for(Matrix m : mArray) { + System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row()); + } + + size = mArray.size(); + m = new int[size + 1][size + 1]; + s = new int[size + 1][size + 1]; + p = new int[size + 1]; + + for (int i=0; i Date: Fri, 21 Dec 2018 09:51:26 +0800 Subject: [PATCH 066/112] Update MatrixChainMultiplication.java --- .../MatrixChainMultiplication.java | 240 +++++++++--------- 1 file changed, 127 insertions(+), 113 deletions(-) diff --git a/Dynamic Programming/MatrixChainMultiplication.java b/Dynamic Programming/MatrixChainMultiplication.java index b22312355aec..d84ecf2299b6 100644 --- a/Dynamic Programming/MatrixChainMultiplication.java +++ b/Dynamic Programming/MatrixChainMultiplication.java @@ -1,120 +1,134 @@ import java.util.ArrayList; +import java.util.Arrays; import java.util.Scanner; -public class MatrixChainMultiplicationTest { - private static Scanner scan = new Scanner(System.in); - private static ArrayList mArray = new ArrayList<>(); - private static int size; - private static int[][] m; - private static int[][] s; - private static int[] p; - - public static void main(String[] args) { - int count = 1; - while(true) { - String [] mSize = input("input size of matrix A("+count+") ( ex. 10 20 ) : "); - int col = Integer.parseInt(mSize[0]); - if (col==0) break; - int row = Integer.parseInt(mSize[1]); - - Matrix matrix = new Matrix(count, col, row); - mArray.add(matrix); - count++; - } - for(Matrix m : mArray) { - System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row()); - } - - size = mArray.size(); - m = new int[size + 1][size + 1]; - s = new int[size + 1][size + 1]; - p = new int[size + 1]; - - for (int i=0; i mArray = new ArrayList<>(); + private static int size; + private static int[][] m; + private static int[][] s; + private static int[] p; + + public static void main(String[] args) { + int count = 1; + while (true) { + String[] mSize = input("input size of matrix A(" + count + ") ( ex. 10 20 ) : "); + int col = Integer.parseInt(mSize[0]); + if (col == 0) break; + int row = Integer.parseInt(mSize[1]); + + Matrix matrix = new Matrix(count, col, row); + mArray.add(matrix); + count++; + } + for (Matrix m : mArray) { + System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row()); + } + + size = mArray.size(); + m = new int[size + 1][size + 1]; + s = new int[size + 1][size + 1]; + p = new int[size + 1]; + + for (int i = 0; i < size + 1; i++) { + Arrays.fill(m[i], -1); + Arrays.fill(s[i], -1); + } + + for (int i = 0; i < p.length; i++) { + p[i] = i == 0 ? mArray.get(i).col() : mArray.get(i - 1).row(); + } + + matrixChainOrder(); + for (int i = 0; i < size; i++) { + System.out.print("-------"); + } + System.out.println(); + printArray(m); + for (int i = 0; i < size; i++) { + System.out.print("-------"); + } + System.out.println(); + printArray(s); + for (int i = 0; i < size; i++) { + System.out.print("-------"); + } + System.out.println(); + + System.out.println("Optimal solution : " + m[1][size]); + System.out.print("Optimal parens : "); + printOptimalParens(1, size); + } + + private static void printOptimalParens(int i, int j) { + if (i == j) { + System.out.print("A" + i); + } else { + System.out.print("("); + printOptimalParens(i, s[i][j]); + printOptimalParens(s[i][j] + 1, j); + System.out.print(")"); + } + } + + private static void printArray(int[][] array) { + for (int i = 1; i < size + 1; i++) { + for (int j = 1; j < size + 1; j++) { + System.out.print(String.format("%7d", array[i][j])); + } + System.out.println(); + } + } + + private static void matrixChainOrder() { + for (int i = 1; i < size + 1; i++) { + m[i][i] = 0; + } + + for (int l = 2; l < size + 1; l++) { + for (int i = 1; i < size - l + 2; i++) { + int j = i + l - 1; + m[i][j] = Integer.MAX_VALUE; + + for (int k = i; k < j; k++) { + int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; + if (q < m[i][j]) { + m[i][j] = q; + s[i][j] = k; + } + } + } + } + } + + private static String[] input(String string) { + System.out.print(string); + return (scan.nextLine().split(" ")); + } } + class Matrix { - private int count; - private int col; - private int row; - public Matrix(int count, int col, int row) { - this.count = count; - this.col = col; - this.row = row; - } - public int count() { return this.count; } - public int col() { return this.col; } - public int row() { return this.row; } + private int count; + private int col; + private int row; + + Matrix(int count, int col, int row) { + this.count = count; + this.col = col; + this.row = row; + } + + int count() { + return count; + } + + int col() { + return col; + } + + int row() { + return row; + } } From a5bf69fcbd6eff2858581d07b013d79ad68fa0ce Mon Sep 17 00:00:00 2001 From: jasonptong <43040084+jasonptong@users.noreply.github.com> Date: Sat, 22 Dec 2018 17:27:31 -0800 Subject: [PATCH 067/112] Update Palindrome.java Test cases where String x is null or has a length of 0 or 1 for FirstWay method. --- Others/Palindrome.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Others/Palindrome.java b/Others/Palindrome.java index 0bbddb7544c8..52062c6c4666 100644 --- a/Others/Palindrome.java +++ b/Others/Palindrome.java @@ -1,6 +1,6 @@ class Palindrome { - private String reverseString(String x){ //*helper method + private String reverseString(String x){ //*helper method String output = ""; for(int i=x.length()-1; i>=0; i--){ output += x.charAt(i); //addition of chars create String @@ -10,7 +10,9 @@ private String reverseString(String x){ //*helper method public Boolean FirstWay(String x){ //*palindrome method, returns true if palindrome - return (x.equalsIgnoreCase(reverseString(x))); + if(x == null || x.length() <= 1) + return true; + return (x.equalsIgnoreCase(reverseString(x))); } public boolean SecondWay(String x) From 2d383bf48e7f058ec6d20b668e7a89edb3d51d43 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Mon, 24 Dec 2018 10:01:45 +0800 Subject: [PATCH 068/112] Update Palindrome.java --- Others/Palindrome.java | 45 +++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/Others/Palindrome.java b/Others/Palindrome.java index 52062c6c4666..d482dfd01bce 100644 --- a/Others/Palindrome.java +++ b/Others/Palindrome.java @@ -1,28 +1,23 @@ class Palindrome { - - private String reverseString(String x){ //*helper method - String output = ""; - for(int i=x.length()-1; i>=0; i--){ - output += x.charAt(i); //addition of chars create String - } - return output; - } - - - public Boolean FirstWay(String x){ //*palindrome method, returns true if palindrome - if(x == null || x.length() <= 1) - return true; - return (x.equalsIgnoreCase(reverseString(x))); - } - - public boolean SecondWay(String x) - { - if (x.length() == 0 || x.length() == 1) - return true; - if (x.charAt(0) != x.charAt(x.length() - 1)) - return false; + private String reverseString(String x) { // *helper method + StringBuilder output = new StringBuilder(x); + return output.reverse().toString(); + } - return SecondWay(x.substring(1 , x.length() - 1)); - } - } + public boolean FirstWay(String x) { // *palindrome method, returns true if palindrome + if (x == null || x.length() <= 1) + return true; + return x.equalsIgnoreCase(reverseString(x)); + } + + public boolean SecondWay(String x) { + if (x.length() == 0 || x.length() == 1) + return true; + + if (x.charAt(0) != x.charAt(x.length() - 1)) + return false; + + return SecondWay(x.substring(1, x.length() - 1)); + } +} From 4bbc39f93b6f038182f2f4217e966d209f8cac62 Mon Sep 17 00:00:00 2001 From: Hayder Hassan Date: Fri, 4 Jan 2019 22:10:02 +0000 Subject: [PATCH 069/112] Move code for Stack Array from Stacks.java to StackArray.java --- DataStructures/Stacks/StackArray.java | 146 ++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 DataStructures/Stacks/StackArray.java diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java new file mode 100644 index 000000000000..795958e8a0d7 --- /dev/null +++ b/DataStructures/Stacks/StackArray.java @@ -0,0 +1,146 @@ +/** + * This class implements a Stack using a regular array. + * + * A stack is exactly what it sounds like. An element gets added to the top of + * the stack and only the element on the top may be removed. This is an example + * of an array implementation of a Stack. So an element can only be added/removed + * from the end of the array. In theory stack have no fixed size, but with an + * array implementation it does. + * + * @author Unknown + * + */ +public class StackArray{ + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + StackArray myStackArray = new StackArray(4); //Declare a stack of maximum size 4 + //Populate the stack + myStackArray.push(5); + myStackArray.push(8); + myStackArray.push(2); + myStackArray.push(9); + + System.out.println("*********************Stack Array Implementation*********************"); + System.out.println(myStackArray.isEmpty()); //will print false + System.out.println(myStackArray.isFull()); //will print true + System.out.println(myStackArray.peek()); //will print 9 + System.out.println(myStackArray.pop()); //will print 9 + System.out.println(myStackArray.peek()); // will print 2 + } + + /** The max size of the Stack */ + private int maxSize; + + /** The array representation of the Stack */ + private int[] stackArray; + + /** The top of the stack */ + private int top; + + /** + * Constructor + * + * @param size Size of the Stack + */ + public StackArray(int size){ + maxSize = size; + stackArray = new int[maxSize]; + top = -1; + } + + /** + * Adds an element to the top of the stack + * + * @param value The element added + */ + public void push(int value){ + if(!isFull()){ //Checks for a full stack + top++; + stackArray[top] = value; + }else{ + resize(maxSize*2); + push(value);// don't forget push after resizing + } + } + + /** + * Removes the top element of the stack and returns the value you've removed + * + * @return value popped off the Stack + */ + public int pop(){ + if(!isEmpty()){ //Checks for an empty stack + return stackArray[top--]; + } + + if(top < maxSize/4){ + resize(maxSize/2); + return pop();// don't forget pop after resizing + } + else{ + System.out.println("The stack is already empty"); + return -1; + } + } + + /** + * Returns the element at the top of the stack + * + * @return element at the top of the stack + */ + public int peek(){ + if(!isEmpty()){ //Checks for an empty stack + return stackArray[top]; + }else{ + System.out.println("The stack is empty, cant peek"); + return -1; + } + } + + private void resize(int newSize){ + //private int[] transferArray = new int[newSize]; we can't put modifires here ! + int[] transferArray = new int[newSize]; + + //for(int i = 0; i < stackArray.length(); i++){ the length isn't a method . + for(int i = 0; i < stackArray.length; i++){ + transferArray[i] = stackArray[i]; + stackArray = transferArray; + } + maxSize = newSize; + } + + /** + * Returns true if the stack is empty + * + * @return true if the stack is empty + */ + public boolean isEmpty(){ + return(top == -1); + } + + /** + * Returns true if the stack is full + * + * @return true if the stack is full + */ + public boolean isFull(){ + return(top+1 == maxSize); + } + + /** + * Deletes everything in the Stack + * + * Doesn't delete elements in the array + * but if you call push method after calling + * makeEmpty it will overwrite previous + * values + */ + public void makeEmpty(){ //Doesn't delete elements in the array but if you call + top = -1; //push method after calling makeEmpty it will overwrite previous values + } +} \ No newline at end of file From bbbf63c9a1303aabbde7a5bd060b466d12349339 Mon Sep 17 00:00:00 2001 From: Hayder Hassan Date: Fri, 4 Jan 2019 22:22:08 +0000 Subject: [PATCH 070/112] Move code for Stack ArrayList from Stacks.java to StackArrayList.java --- DataStructures/Stacks/StackArrayList.java | 94 +++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 DataStructures/Stacks/StackArrayList.java diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java new file mode 100644 index 000000000000..5093b76f07b7 --- /dev/null +++ b/DataStructures/Stacks/StackArrayList.java @@ -0,0 +1,94 @@ +import java.util.ArrayList; + +/** + * This class implements a Stack using an ArrayList. + * + * A stack is exactly what it sounds like. An element gets added to the top of + * the stack and only the element on the top may be removed. + * + * This is an ArrayList Implementation of a stack, where size is not + * a problem we can extend the stack as much as we want. + * + * @author Unknown + * + */ +public class StackArrayList{ + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + StackArrayList myStackArrayList = new StackArrayList(); //Declare a stack of maximum size 4 + //Populate the stack + myStackArrayList.push(5); + myStackArrayList.push(8); + myStackArrayList.push(2); + myStackArrayList.push(9); + + System.out.println("*********************Stack List Implementation*********************"); + System.out.println(myStackArrayList.isEmpty()); //will print false + System.out.println(myStackArrayList.peek()); //will print 9 + System.out.println(myStackArrayList.pop()); //will print 9 + System.out.println(myStackArrayList.peek()); // will print 2 + System.out.println(myStackArrayList.pop()); //will print 2 + } + + /** ArrayList representation of the stack */ + private ArrayList stackList; + + /** + * Constructor + */ + public StackArrayList(){ + stackList = new ArrayList<>(); + } + + /** + * Adds value to the end of list which + * is the top for stack + * + * @param value value to be added + */ + public void push(int value){ + stackList.add(value); + } + + /** + * Pops last element of list which is indeed + * the top for Stack + * + * @return Element popped + */ + public int pop(){ + + if(!isEmpty()){ // checks for an empty Stack + + int popValue=stackList.get(stackList.size()-1); + stackList.remove(stackList.size()-1); //removes the poped element from the list + return popValue; + } + + System.out.print("The stack is already empty "); + return -1; + } + + /** + * Checks for empty Stack + * + * @return true if stack is empty + */ + public boolean isEmpty(){ + return stackList.isEmpty(); + } + + /** + * Top element of stack + * + * @return top element of stack + */ + public int peek(){ + return stackList.get(stackList.size()-1); + } +} \ No newline at end of file From 787a9fa0caab16e40ca4380abc6803b98d03f26b Mon Sep 17 00:00:00 2001 From: Hayder Hassan Date: Fri, 4 Jan 2019 22:29:37 +0000 Subject: [PATCH 071/112] Update link to StackArray and StackArrayList classes The Stacks link in the Korean readme takes user to the Stacks directory rather than a specific Java file. Will need a Korean translator to help with the new links. --- README-ko.md | 2 +- README.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README-ko.md b/README-ko.md index 0c15ded78e5f..c53868cc1310 100644 --- a/README-ko.md +++ b/README-ko.md @@ -179,7 +179,7 @@ and much more...| and more... ------|-----| [노드 스íƒ](DataStructures/Stacks/NodeStack.java)|[AVL 트리](DataStructures/Trees/AVLTree.java)| [연결리스트 스íƒ](DataStructures/Stacks/StackOfLinkedList.java)|[ì´ì§„ 트리](DataStructures/Trees/BinaryTree.java)| -[스íƒ](DataStructures/Stacks/Stacks.java)|And much more...| +[스íƒ](DataStructures/Stacks)|And much more...| * [Bags](DataStructures/Bags/Bag.java) * [Buffer](DataStructures/Buffers/CircularBuffer.java) diff --git a/README.md b/README.md index a8eb9970cfae..08c79b28baf3 100644 --- a/README.md +++ b/README.md @@ -181,7 +181,8 @@ Stacks|Trees| ------|-----| [Node Stack](DataStructures/Stacks/NodeStack.java)|[AVL Tree](DataStructures/Trees/AVLTree.java)| [Stack of Linked List](DataStructures/Stacks/StackOfLinkedList.java)|[Binary Tree](DataStructures/Trees/BinaryTree.java)| -[Stacks](DataStructures/Stacks/Stacks.java)|And much more...| +[Array Stack](DataStructures/Stacks/StackArray.java)|And much more...| +[ArrayList Stack](DataStructures/Stacks/StackArrayList.java)|| * [Bags](DataStructures/Bags/Bag.java) * [Buffer](DataStructures/Buffers/CircularBuffer.java) From 29b7ad43d10c3ed63a1974a27bc2dc9b432ed8e1 Mon Sep 17 00:00:00 2001 From: Hayder Hassan Date: Fri, 4 Jan 2019 22:36:37 +0000 Subject: [PATCH 072/112] Remove Stacks.java which has been replaced by two new files StackArray.java & StackArrayList.java --- DataStructures/Stacks/Stacks.java | 240 ------------------------------ 1 file changed, 240 deletions(-) delete mode 100644 DataStructures/Stacks/Stacks.java diff --git a/DataStructures/Stacks/Stacks.java b/DataStructures/Stacks/Stacks.java deleted file mode 100644 index 2861ef5c17e8..000000000000 --- a/DataStructures/Stacks/Stacks.java +++ /dev/null @@ -1,240 +0,0 @@ -import java.util.ArrayList; - -/** - * This class implements a Stack using two different implementations. - * Stack is used with a regular array and Stack2 uses an ArrayList. - * - * A stack is exactly what it sounds like. An element gets added to the top of - * the stack and only the element on the top may be removed. This is an example - * of an array implementation of a Stack. So an element can only be added/removed - * from the end of the array. In theory stack have no fixed size, but with an - * array implementation it does. - * - * @author Unknown - * - */ -class Stack{ - /** The max size of the Stack */ - private int maxSize; - /** The array representation of the Stack */ - private int[] stackArray; - /** The top of the stack */ - private int top; - - /** - * Constructor - * - * @param size Size of the Stack - */ - public Stack(int size){ - maxSize = size; - stackArray = new int[maxSize]; - top = -1; - } - - /** - * Adds an element to the top of the stack - * - * @param value The element added - */ - public void push(int value){ - if(!isFull()){ //Checks for a full stack - top++; - stackArray[top] = value; - }else{ - resize(maxSize*2); - push(value);// don't forget push after resizing - } - } - - /** - * Removes the top element of the stack and returns the value you've removed - * - * @return value popped off the Stack - */ - public int pop(){ - if(!isEmpty()){ //Checks for an empty stack - return stackArray[top--]; - } - - if(top < maxSize/4){ - resize(maxSize/2); - return pop();// don't forget pop after resizing - } - else{ - System.out.println("The stack is already empty"); - return -1; - } - } - - /** - * Returns the element at the top of the stack - * - * @return element at the top of the stack - */ - public int peek(){ - if(!isEmpty()){ //Checks for an empty stack - return stackArray[top]; - }else{ - System.out.println("The stack is empty, cant peek"); - return -1; - } - } - - private void resize(int newSize){ - //private int[] transferArray = new int[newSize]; we can't put modifires here ! - int[] transferArray = new int[newSize]; - - //for(int i = 0; i < stackArray.length(); i++){ the length isn't a method . - for(int i = 0; i < stackArray.length; i++){ - transferArray[i] = stackArray[i]; - stackArray = transferArray; - } - maxSize = newSize; - } - - /** - * Returns true if the stack is empty - * - * @return true if the stack is empty - */ - public boolean isEmpty(){ - return(top == -1); - } - - /** - * Returns true if the stack is full - * - * @return true if the stack is full - */ - public boolean isFull(){ - return(top+1 == maxSize); - } - - /** - * Deletes everything in the Stack - * - * Doesn't delete elements in the array - * but if you call push method after calling - * makeEmpty it will overwrite previous - * values - */ - public void makeEmpty(){ //Doesn't delete elements in the array but if you call - top = -1; //push method after calling makeEmpty it will overwrite previous values - } -} - -/** - * This is an ArrayList Implementation of stack, Where size is not - * a problem we can extend the stack as much as we want. - * - * @author Unknown - * - */ -class Stack2{ - /** ArrayList representation of the stack */ - ArrayList stackList; - - /** - * Constructor - */ - Stack2(){ - stackList=new ArrayList<>(); - } - - /** - * Adds value to the end of list which - * is the top for stack - * - * @param value value to be added - */ - void push(int value){ - stackList.add(value); - } - - /** - * Pops last element of list which is indeed - * the top for Stack - * - * @return Element popped - */ - int pop(){ - - if(!isEmpty()){ // checks for an empty Stack - - int popValue=stackList.get(stackList.size()-1); - stackList.remove(stackList.size()-1); //removes the poped element from the list - return popValue; - } - else{ - System.out.print("The stack is already empty "); - return -1; - } - - } - - /** - * Checks for empty Stack - * - * @return true if stack is empty - */ - boolean isEmpty(){ - if(stackList.isEmpty()) - return true; - - else return false; - - } - - /** - * Top element of stack - * - * @return top element of stack - */ - int peek(){ - return stackList.get(stackList.size()-1); - } - } - -/** - * This class implements the Stack and Stack2 created above - * - * @author Unknown - * - */ -public class Stacks{ - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String args[]){ - Stack myStack = new Stack(4); //Declare a stack of maximum size 4 - //Populate the stack - myStack.push(5); - myStack.push(8); - myStack.push(2); - myStack.push(9); - - System.out.println("*********************Stack Array Implementation*********************"); - System.out.println(myStack.isEmpty()); //will print false - System.out.println(myStack.isFull()); //will print true - System.out.println(myStack.peek()); //will print 9 - System.out.println(myStack.pop()); //will print 9 - System.out.println(myStack.peek()); // will print 2 - - Stack2 myStack2 = new Stack2(); //Declare a stack of maximum size 4 - //Populate the stack - myStack2.push(5); - myStack2.push(8); - myStack2.push(2); - myStack2.push(9); - - System.out.println("*********************Stack List Implementation*********************"); - System.out.println(myStack2.isEmpty()); //will print false - System.out.println(myStack2.peek()); //will print 9 - System.out.println(myStack2.pop()); //will print 9 - System.out.println(myStack2.peek()); // will print 2 - System.out.println(myStack2.pop()); //will print 2 - } -} From fc64d05b5c803d6b723d463e25dc600d9e9ede6e Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 6 Jan 2019 08:56:51 +0800 Subject: [PATCH 073/112] Format code in StackArray --- DataStructures/Stacks/StackArray.java | 260 +++++++++++++------------- 1 file changed, 133 insertions(+), 127 deletions(-) diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java index 795958e8a0d7..6e580918fabc 100644 --- a/DataStructures/Stacks/StackArray.java +++ b/DataStructures/Stacks/StackArray.java @@ -1,6 +1,6 @@ /** * This class implements a Stack using a regular array. - * + *

* A stack is exactly what it sounds like. An element gets added to the top of * the stack and only the element on the top may be removed. This is an example * of an array implementation of a Stack. So an element can only be added/removed @@ -8,139 +8,145 @@ * array implementation it does. * * @author Unknown - * */ -public class StackArray{ - - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - StackArray myStackArray = new StackArray(4); //Declare a stack of maximum size 4 - //Populate the stack - myStackArray.push(5); - myStackArray.push(8); - myStackArray.push(2); - myStackArray.push(9); - - System.out.println("*********************Stack Array Implementation*********************"); - System.out.println(myStackArray.isEmpty()); //will print false - System.out.println(myStackArray.isFull()); //will print true - System.out.println(myStackArray.peek()); //will print 9 - System.out.println(myStackArray.pop()); //will print 9 - System.out.println(myStackArray.peek()); // will print 2 - } - - /** The max size of the Stack */ - private int maxSize; - - /** The array representation of the Stack */ - private int[] stackArray; - - /** The top of the stack */ - private int top; - - /** - * Constructor - * - * @param size Size of the Stack - */ - public StackArray(int size){ - maxSize = size; - stackArray = new int[maxSize]; - top = -1; - } - - /** - * Adds an element to the top of the stack - * - * @param value The element added - */ - public void push(int value){ - if(!isFull()){ //Checks for a full stack - top++; - stackArray[top] = value; - }else{ - resize(maxSize*2); - push(value);// don't forget push after resizing +public class StackArray { + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + // Declare a stack of maximum size 4 + StackArray myStackArray = new StackArray(4); + + // Populate the stack + myStackArray.push(5); + myStackArray.push(8); + myStackArray.push(2); + myStackArray.push(9); + + System.out.println("*********************Stack Array Implementation*********************"); + System.out.println(myStackArray.isEmpty()); // will print false + System.out.println(myStackArray.isFull()); // will print true + System.out.println(myStackArray.peek()); // will print 9 + System.out.println(myStackArray.pop()); // will print 9 + System.out.println(myStackArray.peek()); // will print 2 + } + + /** + * The max size of the Stack + */ + private int maxSize; + + /** + * The array representation of the Stack + */ + private int[] stackArray; + + /** + * The top of the stack + */ + private int top; + + /** + * Constructor + * + * @param size Size of the Stack + */ + public StackArray(int size) { + maxSize = size; + stackArray = new int[maxSize]; + top = -1; } - } - - /** - * Removes the top element of the stack and returns the value you've removed - * - * @return value popped off the Stack - */ - public int pop(){ - if(!isEmpty()){ //Checks for an empty stack - return stackArray[top--]; + + /** + * Adds an element to the top of the stack + * + * @param value The element added + */ + public void push(int value) { + if (!isFull()) { // Checks for a full stack + top++; + stackArray[top] = value; + } else { + resize(maxSize * 2); + push(value); // don't forget push after resizing + } } - if(top < maxSize/4){ - resize(maxSize/2); - return pop();// don't forget pop after resizing + /** + * Removes the top element of the stack and returns the value you've removed + * + * @return value popped off the Stack + */ + public int pop() { + if (!isEmpty()) { // Checks for an empty stack + return stackArray[top--]; + } + + if (top < maxSize / 4) { + resize(maxSize / 2); + return pop();// don't forget pop after resizing + } else { + System.out.println("The stack is already empty"); + return -1; + } } - else{ - System.out.println("The stack is already empty"); - return -1; + + /** + * Returns the element at the top of the stack + * + * @return element at the top of the stack + */ + public int peek() { + if (!isEmpty()) { // Checks for an empty stack + return stackArray[top]; + } else { + System.out.println("The stack is empty, cant peek"); + return -1; + } } - } - - /** - * Returns the element at the top of the stack - * - * @return element at the top of the stack - */ - public int peek(){ - if(!isEmpty()){ //Checks for an empty stack - return stackArray[top]; - }else{ - System.out.println("The stack is empty, cant peek"); - return -1; + + private void resize(int newSize) { + // private int[] transferArray = new int[newSize]; we can't put modifiers here ! + int[] transferArray = new int[newSize]; + + // for(int i = 0; i < stackArray.length(); i++){ the length isn't a method . + for (int i = 0; i < stackArray.length; i++) { + transferArray[i] = stackArray[i]; + stackArray = transferArray; + } + maxSize = newSize; + } + + /** + * Returns true if the stack is empty + * + * @return true if the stack is empty + */ + public boolean isEmpty() { + return (top == -1); } - } - private void resize(int newSize){ - //private int[] transferArray = new int[newSize]; we can't put modifires here ! - int[] transferArray = new int[newSize]; + /** + * Returns true if the stack is full + * + * @return true if the stack is full + */ + public boolean isFull() { + return (top + 1 == maxSize); + } - //for(int i = 0; i < stackArray.length(); i++){ the length isn't a method . - for(int i = 0; i < stackArray.length; i++){ - transferArray[i] = stackArray[i]; - stackArray = transferArray; + /** + * Deletes everything in the Stack + *

+ * Doesn't delete elements in the array + * but if you call push method after calling + * makeEmpty it will overwrite previous + * values + */ + public void makeEmpty() { // Doesn't delete elements in the array but if you call + top = -1; // push method after calling makeEmpty it will overwrite previous values } - maxSize = newSize; - } - - /** - * Returns true if the stack is empty - * - * @return true if the stack is empty - */ - public boolean isEmpty(){ - return(top == -1); - } - - /** - * Returns true if the stack is full - * - * @return true if the stack is full - */ - public boolean isFull(){ - return(top+1 == maxSize); - } - - /** - * Deletes everything in the Stack - * - * Doesn't delete elements in the array - * but if you call push method after calling - * makeEmpty it will overwrite previous - * values - */ - public void makeEmpty(){ //Doesn't delete elements in the array but if you call - top = -1; //push method after calling makeEmpty it will overwrite previous values - } -} \ No newline at end of file +} From 7c33d2e3132f7dfaa41dc1b2728df85926811c67 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 6 Jan 2019 09:01:33 +0800 Subject: [PATCH 074/112] Update StackArrayList.java --- DataStructures/Stacks/StackArrayList.java | 145 +++++++++++----------- 1 file changed, 73 insertions(+), 72 deletions(-) diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java index 5093b76f07b7..afc804440403 100644 --- a/DataStructures/Stacks/StackArrayList.java +++ b/DataStructures/Stacks/StackArrayList.java @@ -2,93 +2,94 @@ /** * This class implements a Stack using an ArrayList. - * + *

* A stack is exactly what it sounds like. An element gets added to the top of * the stack and only the element on the top may be removed. - * + *

* This is an ArrayList Implementation of a stack, where size is not * a problem we can extend the stack as much as we want. * * @author Unknown - * */ -public class StackArrayList{ +public class StackArrayList { - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String[] args) { - StackArrayList myStackArrayList = new StackArrayList(); //Declare a stack of maximum size 4 - //Populate the stack - myStackArrayList.push(5); - myStackArrayList.push(8); - myStackArrayList.push(2); - myStackArrayList.push(9); + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String[] args) { + + StackArrayList myStackArrayList = new StackArrayList(); + + myStackArrayList.push(5); + myStackArrayList.push(8); + myStackArrayList.push(2); + myStackArrayList.push(9); - System.out.println("*********************Stack List Implementation*********************"); - System.out.println(myStackArrayList.isEmpty()); //will print false - System.out.println(myStackArrayList.peek()); //will print 9 - System.out.println(myStackArrayList.pop()); //will print 9 - System.out.println(myStackArrayList.peek()); // will print 2 - System.out.println(myStackArrayList.pop()); //will print 2 - } + System.out.println("*********************Stack List Implementation*********************"); + System.out.println(myStackArrayList.isEmpty()); // will print false + System.out.println(myStackArrayList.peek()); // will print 9 + System.out.println(myStackArrayList.pop()); // will print 9 + System.out.println(myStackArrayList.peek()); // will print 2 + System.out.println(myStackArrayList.pop()); // will print 2 + } - /** ArrayList representation of the stack */ - private ArrayList stackList; + /** + * ArrayList representation of the stack + */ + private ArrayList stackList; - /** - * Constructor - */ - public StackArrayList(){ - stackList = new ArrayList<>(); - } + /** + * Constructor + */ + public StackArrayList() { + stackList = new ArrayList<>(); + } - /** - * Adds value to the end of list which - * is the top for stack - * - * @param value value to be added - */ - public void push(int value){ - stackList.add(value); - } + /** + * Adds value to the end of list which + * is the top for stack + * + * @param value value to be added + */ + public void push(int value) { + stackList.add(value); + } - /** - * Pops last element of list which is indeed - * the top for Stack - * - * @return Element popped - */ - public int pop(){ + /** + * Pops last element of list which is indeed + * the top for Stack + * + * @return Element popped + */ + public int pop() { - if(!isEmpty()){ // checks for an empty Stack + if (!isEmpty()) { // checks for an empty Stack + int popValue = stackList.get(stackList.size() - 1); + stackList.remove(stackList.size() - 1); // removes the poped element from the list + return popValue; + } - int popValue=stackList.get(stackList.size()-1); - stackList.remove(stackList.size()-1); //removes the poped element from the list - return popValue; + System.out.print("The stack is already empty!"); + return -1; } - System.out.print("The stack is already empty "); - return -1; - } - - /** - * Checks for empty Stack - * - * @return true if stack is empty - */ - public boolean isEmpty(){ - return stackList.isEmpty(); - } + /** + * Checks for empty Stack + * + * @return true if stack is empty + */ + public boolean isEmpty() { + return stackList.isEmpty(); + } - /** - * Top element of stack - * - * @return top element of stack - */ - public int peek(){ - return stackList.get(stackList.size()-1); - } -} \ No newline at end of file + /** + * Top element of stack + * + * @return top element of stack + */ + public int peek() { + return stackList.get(stackList.size() - 1); + } +} From 928a5fed1577204a7216d1bc568128ea9f4d6c79 Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Wed, 9 Jan 2019 14:11:48 +0200 Subject: [PATCH 075/112] Add files via upload SkyLine Algorithm --- divideconquer/SkylineAlgorithm.java | 241 ++++++++++++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 divideconquer/SkylineAlgorithm.java diff --git a/divideconquer/SkylineAlgorithm.java b/divideconquer/SkylineAlgorithm.java new file mode 100644 index 000000000000..a1d4918ce326 --- /dev/null +++ b/divideconquer/SkylineAlgorithm.java @@ -0,0 +1,241 @@ + +package skylinealgorithm; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Scanner; + +/** + * + * @author Dimitrios Panagiotis Grigoriou / dimgrichr + * + * Space complexity: O(n) + * Time complexity: O(nlogn), because it is a divide and conquer algorithm + */ +public class SkylineAlgorithm { + private Scanner scanner; + private File file; + private ArrayList points; + private int tableSize; + + + /** + * Main constructor of the application. + * ArrayList points gets created, which represents the sum of all edges, + * which are read from input file. + * File's(built-in class) object file is created, + * and gets combined with Scanner's(built-in class) object scanner, + * so that the points are read. + * @param name , the name of the input file. + * @throws FileNotFoundException , if input file is not found. + */ + public SkylineAlgorithm(String name) throws FileNotFoundException{ + File file = new File(name); + scanner = new Scanner(file); + points = new ArrayList<>(); + tableSize=scanner.nextInt(); + } + + + /** + * ArrayList points is filled with all points that are included + * in the input file. + * Points are sorted based on the x-value, using a Comparator. + * @see XComparator + */ + public void fillMass(){ + for(int i=0;scanner.hasNextInt();i++){ + //points get added to the ArrayList + points.add(new Point(scanner.nextInt(),scanner.nextInt())); + } + //ArrayList points gets sorted + Collections.sort(points,new XComparator()); + } + + + /** + * @return points, the ArrayList that includes all points. + */ + public ArrayList getPoints(){ + return points; + } + + + /** + * The main divide and conquer, and also recursive algorithm. + * It gets an ArrayList full of points as an argument. + * If the size of that ArrayList is 1 or 2, + * the ArrayList is returned as it is, or with one less point + * (if the initial size is 2 and one of it's points, is dominated by the other one). + * On the other hand, if the ArrayList's size is bigger than 2, + * the function is called again, twice, + * with arguments the corresponding half of the initial ArrayList each time. + * Once the flashback has ended, the function produceFinalSkyLine gets called, + * in order to produce the final skyline, and return it. + * @param list, the initial list of points + * @return leftSkyLine, the combination of first half's and second half's skyline + * @see Point + * @see produceFinalSkyLine + */ + public ArrayList produceSubSkyLines(ArrayList list){ + + //part where function exits flashback + int size = list.size(); + if(size == 1){ + return list; + } + else if(size==2){ + if(list.get(0).dominates(list.get(1))){ + list.remove(1); + } + else{ + if(list.get(1).dominates(list.get(0))){ + list.remove(0); + } + } + return list; + } + + //recursive part of the function + ArrayList leftHalf=new ArrayList<>(); + ArrayList rightHalf=new ArrayList<>(); + for (int i=0;i leftSubSkyLine=new ArrayList<>(); + ArrayList rightSubSkyLine=new ArrayList<>(); + leftSubSkyLine=produceSubSkyLines(leftHalf); + rightSubSkyLine=produceSubSkyLines(rightHalf); + + //skyline is produced + return produceFinalSkyLine(leftSubSkyLine,rightSubSkyLine); + } + + + /** + * The first half's skyline gets cleared + * from some points that are not part of the final skyline + * (Points with same x-value and different y=values. The point with the smallest y-value is kept). + * Then, the minimum y-value of the points of first half's skyline is found. + * That helps us to clear the second half's skyline, because, the points + * of second half's skyline that have greater y-value of the minimum y-value that we found before, + * are dominated, so they are not part of the final skyline. + * Finally, the "cleaned" first half's and second half's skylines, are combined, + * producing the final skyline, which is returned. + * @param left the skyline of the left part of points + * @param right the skyline of the right part of points + * @return left the final skyline + */ + public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right){ + + //dominated points of ArrayList left are removed + for(int i=0;ileft.get(i+1).y){ + left.remove(i); + i--; + } + } + + //minimum y-value is found + int min=left.get(0).y; + for(int i=1;ileft.get(i).y){ + min = left.get(i).y; + if(min==1){ + i=left.size(); + } + } + } + + //dominated points of ArrayList right are removed + for(int i=0;i=min){ + right.remove(i); + i--; + } + } + + //final skyline found and returned + left.addAll(right); + return left; + } + + + + public static class Point{ + private int x; + private int y; + /** + * The main constructor of Point Class, used to represent the 2 Dimension points. + * @param x the point's x-value. + * @param y the point's y-value. + */ + public Point(int x, int y){ + this.x=x; + this.y=y; + } + /** + * @return x, the x-value + */ + public int getX(){ + return x; + } + /** + * @return y, the y-value + */ + public int getY(){ + return y; + } + /** + * Based on the skyline theory, + * it checks if the point that calls the function dominates the argument point. + * @param p1 the point that is compared + * @return true if the point wich calls the function dominates p1 + * false otherwise. + */ + public boolean dominates(Point p1){ + + //checks if p1 is dominated + if((this.x { + @Override + public int compare(Point a, Point b) { + return a.x < b.x ? -1 : a.x == b.x ? 0 : 1; + } + } + + + //main function + public static void main(String[] args) throws FileNotFoundException { + if (args.length != 1) + { + System.out.println("Insert the input file"); + return; + } + SkylineAlgorithm skyline = new SkylineAlgorithm(args[0]); + skyline.fillMass(); + ArrayList list = skyline.produceSubSkyLines(skyline.getPoints()); + for(Point x: list){ + System.out.println(x.getX() + " " + x.getY()); + } + } +} From a85b36db9557b4abe1b39b3be7a6c8425793fde8 Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Wed, 9 Jan 2019 14:22:34 +0200 Subject: [PATCH 076/112] Add files via upload --- Dynamic Programming/TaskCosts.java | 118 +++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 Dynamic Programming/TaskCosts.java diff --git a/Dynamic Programming/TaskCosts.java b/Dynamic Programming/TaskCosts.java new file mode 100644 index 000000000000..10e5457b626c --- /dev/null +++ b/Dynamic Programming/TaskCosts.java @@ -0,0 +1,118 @@ +package projectb; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + +/** + * + * @author dimig + */ +public class TaskCosts { + + private Scanner scanner; + private File file; + + private int tasks; + private int vms; + + private int[][] vmsPer; + private int[][] vmsCom; + private int[][] costs; + + + private TaskCosts(String nameOfInputFile) throws FileNotFoundException{ + File file = new File(nameOfInputFile); + scanner = new Scanner(file); + tasks = scanner.nextInt(); + vms = scanner.nextInt(); + costs = new int[tasks][vms]; + vmsPer = new int[tasks][vms]; + vmsCom = new int[vms][vms]; + for(int i=0;i Date: Fri, 11 Jan 2019 20:33:50 +0800 Subject: [PATCH 077/112] Update BinarySearch.java fix --- Searches/BinarySearch.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java index f655c074f279..6877a55f1d95 100644 --- a/Searches/BinarySearch.java +++ b/Searches/BinarySearch.java @@ -72,7 +72,7 @@ private > int search(T array[], T key, int left, int rig // Driver Program public static void main(String[] args) { // Just generate data - Random random = ThreadLocalRandom.current(); + Random r = ThreadLocalRandom.current(); int size = 100; int maxElement = 100000; From 21a7b9db58b085f1fcaaa70c0d20d7d379f71a78 Mon Sep 17 00:00:00 2001 From: Guo_1_9 Date: Sun, 13 Jan 2019 05:13:09 +0800 Subject: [PATCH 078/112] Update MergeSort.java --- Sorts/MergeSort.java | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java index 3c4fa4a2b99a..e14334b163bf 100644 --- a/Sorts/MergeSort.java +++ b/Sorts/MergeSort.java @@ -70,26 +70,19 @@ private static > void merge(T[] arr, T[] temp, int left, while (i <= mid && j <= right) { if (temp[i].compareTo(temp[j]) <= 0) { - arr[k] = temp[i]; - i++; + arr[k++] = temp[i++]; } else { - arr[k] = temp[j]; - j++; + arr[k++] = temp[j++]; } - k++; } while (i <= mid) { - arr[k] = temp[i]; - i++; - k++; + arr[k++] = temp[i++]; } while (j <= right) { - arr[k] = temp[j]; - j++; - k++; + arr[k++] = temp[j++]; } } From d55d1e4d0e8ce9b11035c804f63e41258cc8cc20 Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Tue, 15 Jan 2019 12:39:14 +0200 Subject: [PATCH 079/112] Delete SkylineAlgorithm.java --- divideconquer/SkylineAlgorithm.java | 241 ---------------------------- 1 file changed, 241 deletions(-) delete mode 100644 divideconquer/SkylineAlgorithm.java diff --git a/divideconquer/SkylineAlgorithm.java b/divideconquer/SkylineAlgorithm.java deleted file mode 100644 index a1d4918ce326..000000000000 --- a/divideconquer/SkylineAlgorithm.java +++ /dev/null @@ -1,241 +0,0 @@ - -package skylinealgorithm; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Scanner; - -/** - * - * @author Dimitrios Panagiotis Grigoriou / dimgrichr - * - * Space complexity: O(n) - * Time complexity: O(nlogn), because it is a divide and conquer algorithm - */ -public class SkylineAlgorithm { - private Scanner scanner; - private File file; - private ArrayList points; - private int tableSize; - - - /** - * Main constructor of the application. - * ArrayList points gets created, which represents the sum of all edges, - * which are read from input file. - * File's(built-in class) object file is created, - * and gets combined with Scanner's(built-in class) object scanner, - * so that the points are read. - * @param name , the name of the input file. - * @throws FileNotFoundException , if input file is not found. - */ - public SkylineAlgorithm(String name) throws FileNotFoundException{ - File file = new File(name); - scanner = new Scanner(file); - points = new ArrayList<>(); - tableSize=scanner.nextInt(); - } - - - /** - * ArrayList points is filled with all points that are included - * in the input file. - * Points are sorted based on the x-value, using a Comparator. - * @see XComparator - */ - public void fillMass(){ - for(int i=0;scanner.hasNextInt();i++){ - //points get added to the ArrayList - points.add(new Point(scanner.nextInt(),scanner.nextInt())); - } - //ArrayList points gets sorted - Collections.sort(points,new XComparator()); - } - - - /** - * @return points, the ArrayList that includes all points. - */ - public ArrayList getPoints(){ - return points; - } - - - /** - * The main divide and conquer, and also recursive algorithm. - * It gets an ArrayList full of points as an argument. - * If the size of that ArrayList is 1 or 2, - * the ArrayList is returned as it is, or with one less point - * (if the initial size is 2 and one of it's points, is dominated by the other one). - * On the other hand, if the ArrayList's size is bigger than 2, - * the function is called again, twice, - * with arguments the corresponding half of the initial ArrayList each time. - * Once the flashback has ended, the function produceFinalSkyLine gets called, - * in order to produce the final skyline, and return it. - * @param list, the initial list of points - * @return leftSkyLine, the combination of first half's and second half's skyline - * @see Point - * @see produceFinalSkyLine - */ - public ArrayList produceSubSkyLines(ArrayList list){ - - //part where function exits flashback - int size = list.size(); - if(size == 1){ - return list; - } - else if(size==2){ - if(list.get(0).dominates(list.get(1))){ - list.remove(1); - } - else{ - if(list.get(1).dominates(list.get(0))){ - list.remove(0); - } - } - return list; - } - - //recursive part of the function - ArrayList leftHalf=new ArrayList<>(); - ArrayList rightHalf=new ArrayList<>(); - for (int i=0;i leftSubSkyLine=new ArrayList<>(); - ArrayList rightSubSkyLine=new ArrayList<>(); - leftSubSkyLine=produceSubSkyLines(leftHalf); - rightSubSkyLine=produceSubSkyLines(rightHalf); - - //skyline is produced - return produceFinalSkyLine(leftSubSkyLine,rightSubSkyLine); - } - - - /** - * The first half's skyline gets cleared - * from some points that are not part of the final skyline - * (Points with same x-value and different y=values. The point with the smallest y-value is kept). - * Then, the minimum y-value of the points of first half's skyline is found. - * That helps us to clear the second half's skyline, because, the points - * of second half's skyline that have greater y-value of the minimum y-value that we found before, - * are dominated, so they are not part of the final skyline. - * Finally, the "cleaned" first half's and second half's skylines, are combined, - * producing the final skyline, which is returned. - * @param left the skyline of the left part of points - * @param right the skyline of the right part of points - * @return left the final skyline - */ - public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right){ - - //dominated points of ArrayList left are removed - for(int i=0;ileft.get(i+1).y){ - left.remove(i); - i--; - } - } - - //minimum y-value is found - int min=left.get(0).y; - for(int i=1;ileft.get(i).y){ - min = left.get(i).y; - if(min==1){ - i=left.size(); - } - } - } - - //dominated points of ArrayList right are removed - for(int i=0;i=min){ - right.remove(i); - i--; - } - } - - //final skyline found and returned - left.addAll(right); - return left; - } - - - - public static class Point{ - private int x; - private int y; - /** - * The main constructor of Point Class, used to represent the 2 Dimension points. - * @param x the point's x-value. - * @param y the point's y-value. - */ - public Point(int x, int y){ - this.x=x; - this.y=y; - } - /** - * @return x, the x-value - */ - public int getX(){ - return x; - } - /** - * @return y, the y-value - */ - public int getY(){ - return y; - } - /** - * Based on the skyline theory, - * it checks if the point that calls the function dominates the argument point. - * @param p1 the point that is compared - * @return true if the point wich calls the function dominates p1 - * false otherwise. - */ - public boolean dominates(Point p1){ - - //checks if p1 is dominated - if((this.x { - @Override - public int compare(Point a, Point b) { - return a.x < b.x ? -1 : a.x == b.x ? 0 : 1; - } - } - - - //main function - public static void main(String[] args) throws FileNotFoundException { - if (args.length != 1) - { - System.out.println("Insert the input file"); - return; - } - SkylineAlgorithm skyline = new SkylineAlgorithm(args[0]); - skyline.fillMass(); - ArrayList list = skyline.produceSubSkyLines(skyline.getPoints()); - for(Point x: list){ - System.out.println(x.getX() + " " + x.getY()); - } - } -} From 96ad920ce5975e17ac4c644819dc3e204b8e772b Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Tue, 15 Jan 2019 12:41:26 +0200 Subject: [PATCH 080/112] Addition of the Skyline Algorithm Implementation of the skyline algorithm --- divideconquer/SkylineAlgorithm.java | 190 ++++++++++++++++++++++++++++ 1 file changed, 190 insertions(+) create mode 100644 divideconquer/SkylineAlgorithm.java diff --git a/divideconquer/SkylineAlgorithm.java b/divideconquer/SkylineAlgorithm.java new file mode 100644 index 000000000000..f1b1f44c7433 --- /dev/null +++ b/divideconquer/SkylineAlgorithm.java @@ -0,0 +1,190 @@ +package skylinealgorithm; + +import java.util.ArrayList; +import java.util.Comparator; + +/** + * + * @author dimgrichr + * + * Space complexity: O(n) + * Time complexity: O(nlogn), because it is a divide and conquer algorithm + */ +public class SkylineAlgorithm { + private ArrayList points; + + + /** + * Main constructor of the application. + * ArrayList points gets created, which represents the sum of all edges. + */ + public SkylineAlgorithm(){ + points = new ArrayList<>(); + } + + + /** + * @return points, the ArrayList that includes all points. + */ + public ArrayList getPoints(){ + return points; + } + + + /** + * The main divide and conquer, and also recursive algorithm. + * It gets an ArrayList full of points as an argument. + * If the size of that ArrayList is 1 or 2, + * the ArrayList is returned as it is, or with one less point + * (if the initial size is 2 and one of it's points, is dominated by the other one). + * On the other hand, if the ArrayList's size is bigger than 2, + * the function is called again, twice, + * with arguments the corresponding half of the initial ArrayList each time. + * Once the flashback has ended, the function produceFinalSkyLine gets called, + * in order to produce the final skyline, and return it. + * @param list, the initial list of points + * @return leftSkyLine, the combination of first half's and second half's skyline + * @see Point + * @see produceFinalSkyLine + */ + public ArrayList produceSubSkyLines(ArrayList list){ + + //part where function exits flashback + int size = list.size(); + if(size == 1){ + return list; + } + else if(size==2){ + if(list.get(0).dominates(list.get(1))){ + list.remove(1); + } + else{ + if(list.get(1).dominates(list.get(0))){ + list.remove(0); + } + } + return list; + } + + //recursive part of the function + ArrayList leftHalf=new ArrayList<>(); + ArrayList rightHalf=new ArrayList<>(); + for (int i=0;i leftSubSkyLine=new ArrayList<>(); + ArrayList rightSubSkyLine=new ArrayList<>(); + leftSubSkyLine=produceSubSkyLines(leftHalf); + rightSubSkyLine=produceSubSkyLines(rightHalf); + + //skyline is produced + return produceFinalSkyLine(leftSubSkyLine,rightSubSkyLine); + } + + + /** + * The first half's skyline gets cleared + * from some points that are not part of the final skyline + * (Points with same x-value and different y=values. The point with the smallest y-value is kept). + * Then, the minimum y-value of the points of first half's skyline is found. + * That helps us to clear the second half's skyline, because, the points + * of second half's skyline that have greater y-value of the minimum y-value that we found before, + * are dominated, so they are not part of the final skyline. + * Finally, the "cleaned" first half's and second half's skylines, are combined, + * producing the final skyline, which is returned. + * @param left the skyline of the left part of points + * @param right the skyline of the right part of points + * @return left the final skyline + */ + public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right){ + + //dominated points of ArrayList left are removed + for(int i=0;ileft.get(i+1).y){ + left.remove(i); + i--; + } + } + + //minimum y-value is found + int min=left.get(0).y; + for(int i=1;ileft.get(i).y){ + min = left.get(i).y; + if(min==1){ + i=left.size(); + } + } + } + + //dominated points of ArrayList right are removed + for(int i=0;i=min){ + right.remove(i); + i--; + } + } + + //final skyline found and returned + left.addAll(right); + return left; + } + + + + public static class Point{ + private int x; + private int y; + /** + * The main constructor of Point Class, used to represent the 2 Dimension points. + * @param x the point's x-value. + * @param y the point's y-value. + */ + public Point(int x, int y){ + this.x=x; + this.y=y; + } + /** + * @return x, the x-value + */ + public int getX(){ + return x; + } + /** + * @return y, the y-value + */ + public int getY(){ + return y; + } + /** + * Based on the skyline theory, + * it checks if the point that calls the function dominates the argument point. + * @param p1 the point that is compared + * @return true if the point wich calls the function dominates p1 + * false otherwise. + */ + public boolean dominates(Point p1){ + + //checks if p1 is dominated + if((this.x { + @Override + public int compare(Point a, Point b) { + return a.x < b.x ? -1 : a.x == b.x ? 0 : 1; + } + } +} From 8f78a3fe6cbd79029f5213c783880b6308890132 Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Tue, 15 Jan 2019 12:44:48 +0200 Subject: [PATCH 081/112] Delete TaskCosts.java --- Dynamic Programming/TaskCosts.java | 118 ----------------------------- 1 file changed, 118 deletions(-) delete mode 100644 Dynamic Programming/TaskCosts.java diff --git a/Dynamic Programming/TaskCosts.java b/Dynamic Programming/TaskCosts.java deleted file mode 100644 index 10e5457b626c..000000000000 --- a/Dynamic Programming/TaskCosts.java +++ /dev/null @@ -1,118 +0,0 @@ -package projectb; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Scanner; - -/** - * - * @author dimig - */ -public class TaskCosts { - - private Scanner scanner; - private File file; - - private int tasks; - private int vms; - - private int[][] vmsPer; - private int[][] vmsCom; - private int[][] costs; - - - private TaskCosts(String nameOfInputFile) throws FileNotFoundException{ - File file = new File(nameOfInputFile); - scanner = new Scanner(file); - tasks = scanner.nextInt(); - vms = scanner.nextInt(); - costs = new int[tasks][vms]; - vmsPer = new int[tasks][vms]; - vmsCom = new int[vms][vms]; - for(int i=0;i Date: Tue, 15 Jan 2019 19:54:43 +0800 Subject: [PATCH 082/112] Update SkylineAlgorithm.java --- divideconquer/SkylineAlgorithm.java | 153 ++++++++++++++-------------- 1 file changed, 74 insertions(+), 79 deletions(-) diff --git a/divideconquer/SkylineAlgorithm.java b/divideconquer/SkylineAlgorithm.java index f1b1f44c7433..51bce90c98d2 100644 --- a/divideconquer/SkylineAlgorithm.java +++ b/divideconquer/SkylineAlgorithm.java @@ -1,36 +1,32 @@ -package skylinealgorithm; - import java.util.ArrayList; import java.util.Comparator; /** - * * @author dimgrichr - * + *

* Space complexity: O(n) * Time complexity: O(nlogn), because it is a divide and conquer algorithm */ public class SkylineAlgorithm { private ArrayList points; - - + /** * Main constructor of the application. * ArrayList points gets created, which represents the sum of all edges. */ - public SkylineAlgorithm(){ + public SkylineAlgorithm() { points = new ArrayList<>(); } - - + + /** * @return points, the ArrayList that includes all points. */ - public ArrayList getPoints(){ + public ArrayList getPoints() { return points; } - - + + /** * The main divide and conquer, and also recursive algorithm. * It gets an ArrayList full of points as an argument. @@ -38,55 +34,51 @@ public ArrayList getPoints(){ * the ArrayList is returned as it is, or with one less point * (if the initial size is 2 and one of it's points, is dominated by the other one). * On the other hand, if the ArrayList's size is bigger than 2, - * the function is called again, twice, + * the function is called again, twice, * with arguments the corresponding half of the initial ArrayList each time. * Once the flashback has ended, the function produceFinalSkyLine gets called, * in order to produce the final skyline, and return it. + * * @param list, the initial list of points * @return leftSkyLine, the combination of first half's and second half's skyline * @see Point * @see produceFinalSkyLine */ - public ArrayList produceSubSkyLines(ArrayList list){ - - //part where function exits flashback + public ArrayList produceSubSkyLines(ArrayList list) { + + // part where function exits flashback int size = list.size(); - if(size == 1){ + if (size == 1) { return list; - } - else if(size==2){ - if(list.get(0).dominates(list.get(1))){ + } else if (size == 2) { + if (list.get(0).dominates(list.get(1))) { list.remove(1); - } - else{ - if(list.get(1).dominates(list.get(0))){ + } else { + if (list.get(1).dominates(list.get(0))) { list.remove(0); } } return list; } - - //recursive part of the function - ArrayList leftHalf=new ArrayList<>(); - ArrayList rightHalf=new ArrayList<>(); - for (int i=0;i leftHalf = new ArrayList<>(); + ArrayList rightHalf = new ArrayList<>(); + for (int i = 0; i < list.size(); i++) { + if (i < list.size() / 2) { leftHalf.add(list.get(i)); - } - else{ + } else { rightHalf.add(list.get(i)); } } - ArrayList leftSubSkyLine=new ArrayList<>(); - ArrayList rightSubSkyLine=new ArrayList<>(); - leftSubSkyLine=produceSubSkyLines(leftHalf); - rightSubSkyLine=produceSubSkyLines(rightHalf); - - //skyline is produced - return produceFinalSkyLine(leftSubSkyLine,rightSubSkyLine); + ArrayList leftSubSkyLine = produceSubSkyLines(leftHalf); + ArrayList rightSubSkyLine= produceSubSkyLines(rightHalf); + + // skyline is produced + return produceFinalSkyLine(leftSubSkyLine, rightSubSkyLine); } - - + + /** * The first half's skyline gets cleared * from some points that are not part of the final skyline @@ -97,94 +89,97 @@ else if(size==2){ * are dominated, so they are not part of the final skyline. * Finally, the "cleaned" first half's and second half's skylines, are combined, * producing the final skyline, which is returned. - * @param left the skyline of the left part of points + * + * @param left the skyline of the left part of points * @param right the skyline of the right part of points * @return left the final skyline */ - public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right){ - - //dominated points of ArrayList left are removed - for(int i=0;ileft.get(i+1).y){ + public ArrayList produceFinalSkyLine(ArrayList left, ArrayList right) { + + // dominated points of ArrayList left are removed + for (int i = 0; i < left.size() - 1; i++) { + if (left.get(i).x == left.get(i + 1).x && left.get(i).y > left.get(i + 1).y) { left.remove(i); i--; } } - - //minimum y-value is found - int min=left.get(0).y; - for(int i=1;ileft.get(i).y){ + + // minimum y-value is found + int min = left.get(0).y; + for (int i = 1; i < left.size(); i++) { + if (min > left.get(i).y) { min = left.get(i).y; - if(min==1){ - i=left.size(); + if (min == 1) { + i = left.size(); } } } - - //dominated points of ArrayList right are removed - for(int i=0;i=min){ + + // dominated points of ArrayList right are removed + for (int i = 0; i < right.size(); i++) { + if (right.get(i).y >= min) { right.remove(i); i--; } } - - //final skyline found and returned + + // final skyline found and returned left.addAll(right); return left; } - - - public static class Point{ + + public static class Point { private int x; private int y; + /** * The main constructor of Point Class, used to represent the 2 Dimension points. + * * @param x the point's x-value. * @param y the point's y-value. */ - public Point(int x, int y){ - this.x=x; - this.y=y; + public Point(int x, int y) { + this.x = x; + this.y = y; } + /** * @return x, the x-value */ - public int getX(){ + public int getX() { return x; } + /** * @return y, the y-value */ - public int getY(){ + public int getY() { return y; } + /** * Based on the skyline theory, * it checks if the point that calls the function dominates the argument point. + * * @param p1 the point that is compared * @return true if the point wich calls the function dominates p1 - * false otherwise. + * false otherwise. */ - public boolean dominates(Point p1){ - - //checks if p1 is dominated - if((this.x { - @Override - public int compare(Point a, Point b) { - return a.x < b.x ? -1 : a.x == b.x ? 0 : 1; - } + @Override + public int compare(Point a, Point b) { + return Integer.compare(a.x, b.x); + } } } From d4b67256993d155c374170b283fd3d6f0eb64cf7 Mon Sep 17 00:00:00 2001 From: dimgrichr <32580033+dimgrichr@users.noreply.github.com> Date: Tue, 15 Jan 2019 14:27:31 +0200 Subject: [PATCH 083/112] Cyclic redundancy check Algorithm Implementation of an CRC Algorithm, used in order to examine already received packets/messages. --- Others/CRCAlgorithm.java | 209 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 Others/CRCAlgorithm.java diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java new file mode 100644 index 000000000000..f26763db892a --- /dev/null +++ b/Others/CRCAlgorithm.java @@ -0,0 +1,209 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package crcalgorithm; + +import java.util.ArrayList; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +/** + * + * @author dimig + */ +public class CRCAlgorithm { + + private int correctMess; + + private int wrongMess; + + private int wrongMessCaught; + + private int wrongMessNotCaught; + + private int messSize; + + private double ber; + + private boolean messageChanged; + + private ArrayList message; + + private ArrayList dividedMessage; + + private ArrayList p; + + private Random randomGenerator; + + + /** + * The algorithm's main constructor. + * The most significant variables, used in the algorithm, + * are set in their initial values. + * @param str The binary number P, in a string form, which is used by the CRC algorithm + * @param size The size of every transmitted message + * @param ber The Bit Error Rate + */ + public CRCAlgorithm(String str, int size, double ber){ + messageChanged=false; + message = new ArrayList<>(); + messSize = size; + dividedMessage = new ArrayList<>(); + p = new ArrayList<>(); + for(int i=0;i(); + dividedMessage = new ArrayList<>(); + } + + /** + * Random messages, consisted of 0's and 1's, + * are generated, so that they can later be transmitted + */ + public void generateRandomMess(){ + for(int i=0;i is created. + * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's. + * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes. + * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes. + * If check == false, the diviided Message is added at the end of the ArrayList message. + * @param check the variable used to determine, if the message is going to be checked from the receiver + * if true, it is checked + * otherwise, it is not + */ + public void divideMessageWithP(boolean check){ + ArrayList x = new ArrayList<>(); + ArrayList k = (ArrayList) message.clone(); + if(!check){ + for(int i=0;i) x.clone(); + if(!check){ + for(int z:dividedMessage){ + message.add(z); + } + } + else{ + if(dividedMessage.contains(1) && messageChanged){ + wrongMessCaught++; + } + else if(!dividedMessage.contains(1) && messageChanged){ + wrongMessNotCaught++; + } + else if(!messageChanged){ + correctMess++; + } + } + } + + /** + * Once the message is transmitted, some of it's elements, + * is possible to change from 1 to 0, or from 0 to 1, + * because of the Bit Error Rate (ber). + * For every element of the message, a random double number is created. + * If that number is smaller than ber, then the spesific element changes. + * On the other hand, if it's bigger than ber, it does not. + * Based on these changes. the boolean variable messageChanged, gets the value: + * true, or false. + */ + public void changeMess(){ + for(int y : message){ + double x = randomGenerator.nextDouble(); + while(x<0.0000 || x>1.00000){ + x = randomGenerator.nextDouble(); + } + if(x Date: Tue, 15 Jan 2019 14:28:47 +0200 Subject: [PATCH 084/112] Delete CRCAlgorithm.java --- Others/CRCAlgorithm.java | 209 --------------------------------------- 1 file changed, 209 deletions(-) delete mode 100644 Others/CRCAlgorithm.java diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java deleted file mode 100644 index f26763db892a..000000000000 --- a/Others/CRCAlgorithm.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ -package crcalgorithm; - -import java.util.ArrayList; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -/** - * - * @author dimig - */ -public class CRCAlgorithm { - - private int correctMess; - - private int wrongMess; - - private int wrongMessCaught; - - private int wrongMessNotCaught; - - private int messSize; - - private double ber; - - private boolean messageChanged; - - private ArrayList message; - - private ArrayList dividedMessage; - - private ArrayList p; - - private Random randomGenerator; - - - /** - * The algorithm's main constructor. - * The most significant variables, used in the algorithm, - * are set in their initial values. - * @param str The binary number P, in a string form, which is used by the CRC algorithm - * @param size The size of every transmitted message - * @param ber The Bit Error Rate - */ - public CRCAlgorithm(String str, int size, double ber){ - messageChanged=false; - message = new ArrayList<>(); - messSize = size; - dividedMessage = new ArrayList<>(); - p = new ArrayList<>(); - for(int i=0;i(); - dividedMessage = new ArrayList<>(); - } - - /** - * Random messages, consisted of 0's and 1's, - * are generated, so that they can later be transmitted - */ - public void generateRandomMess(){ - for(int i=0;i is created. - * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's. - * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes. - * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes. - * If check == false, the diviided Message is added at the end of the ArrayList message. - * @param check the variable used to determine, if the message is going to be checked from the receiver - * if true, it is checked - * otherwise, it is not - */ - public void divideMessageWithP(boolean check){ - ArrayList x = new ArrayList<>(); - ArrayList k = (ArrayList) message.clone(); - if(!check){ - for(int i=0;i) x.clone(); - if(!check){ - for(int z:dividedMessage){ - message.add(z); - } - } - else{ - if(dividedMessage.contains(1) && messageChanged){ - wrongMessCaught++; - } - else if(!dividedMessage.contains(1) && messageChanged){ - wrongMessNotCaught++; - } - else if(!messageChanged){ - correctMess++; - } - } - } - - /** - * Once the message is transmitted, some of it's elements, - * is possible to change from 1 to 0, or from 0 to 1, - * because of the Bit Error Rate (ber). - * For every element of the message, a random double number is created. - * If that number is smaller than ber, then the spesific element changes. - * On the other hand, if it's bigger than ber, it does not. - * Based on these changes. the boolean variable messageChanged, gets the value: - * true, or false. - */ - public void changeMess(){ - for(int y : message){ - double x = randomGenerator.nextDouble(); - while(x<0.0000 || x>1.00000){ - x = randomGenerator.nextDouble(); - } - if(x Date: Tue, 15 Jan 2019 14:32:01 +0200 Subject: [PATCH 085/112] Cyclic Redundancy Check Algorithm Implementation of a CRC algorithm, used in order to examine received messages/packets for any errors. This type of algorithms, is widely used in networks. --- Others/CRCAlgorithm.java | 204 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 Others/CRCAlgorithm.java diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java new file mode 100644 index 000000000000..f932a9b74a73 --- /dev/null +++ b/Others/CRCAlgorithm.java @@ -0,0 +1,204 @@ +package crcalgorithm; + +import java.util.ArrayList; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; + +/** + * + * @author dimgrichr + */ +public class CRCAlgorithm { + + private int correctMess; + + private int wrongMess; + + private int wrongMessCaught; + + private int wrongMessNotCaught; + + private int messSize; + + private double ber; + + private boolean messageChanged; + + private ArrayList message; + + private ArrayList dividedMessage; + + private ArrayList p; + + private Random randomGenerator; + + + /** + * The algorithm's main constructor. + * The most significant variables, used in the algorithm, + * are set in their initial values. + * @param str The binary number P, in a string form, which is used by the CRC algorithm + * @param size The size of every transmitted message + * @param ber The Bit Error Rate + */ + public CRCAlgorithm(String str, int size, double ber){ + messageChanged=false; + message = new ArrayList<>(); + messSize = size; + dividedMessage = new ArrayList<>(); + p = new ArrayList<>(); + for(int i=0;i(); + dividedMessage = new ArrayList<>(); + } + + /** + * Random messages, consisted of 0's and 1's, + * are generated, so that they can later be transmitted + */ + public void generateRandomMess(){ + for(int i=0;i is created. + * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's. + * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes. + * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes. + * If check == false, the diviided Message is added at the end of the ArrayList message. + * @param check the variable used to determine, if the message is going to be checked from the receiver + * if true, it is checked + * otherwise, it is not + */ + public void divideMessageWithP(boolean check){ + ArrayList x = new ArrayList<>(); + ArrayList k = (ArrayList) message.clone(); + if(!check){ + for(int i=0;i) x.clone(); + if(!check){ + for(int z:dividedMessage){ + message.add(z); + } + } + else{ + if(dividedMessage.contains(1) && messageChanged){ + wrongMessCaught++; + } + else if(!dividedMessage.contains(1) && messageChanged){ + wrongMessNotCaught++; + } + else if(!messageChanged){ + correctMess++; + } + } + } + + /** + * Once the message is transmitted, some of it's elements, + * is possible to change from 1 to 0, or from 0 to 1, + * because of the Bit Error Rate (ber). + * For every element of the message, a random double number is created. + * If that number is smaller than ber, then the spesific element changes. + * On the other hand, if it's bigger than ber, it does not. + * Based on these changes. the boolean variable messageChanged, gets the value: + * true, or false. + */ + public void changeMess(){ + for(int y : message){ + double x = randomGenerator.nextDouble(); + while(x<0.0000 || x>1.00000){ + x = randomGenerator.nextDouble(); + } + if(x Date: Thu, 17 Jan 2019 13:43:12 -0200 Subject: [PATCH 086/112] Correction of a RuntimeException Uncompilable source code --- DataStructures/Trees/AVLTree.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DataStructures/Trees/AVLTree.java b/DataStructures/Trees/AVLTree.java index 4bcf402dc0b7..720d46fd51df 100644 --- a/DataStructures/Trees/AVLTree.java +++ b/DataStructures/Trees/AVLTree.java @@ -176,9 +176,10 @@ private int height(Node n) { } private void setBalance(Node... nodes) { - for (Node n : nodes) + for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); + } } public void printBalance() { From 6cc1414a2aadb5de5c97d1e8a5f26898bb573971 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 23 Jan 2019 14:03:30 +0800 Subject: [PATCH 087/112] docs(Others): rename GuassLegendre to fix #689 - Fix #689 - Thank you @SebastianOner --- Others/{GuassLengendre.java => GuassLegendre.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Others/{GuassLengendre.java => GuassLegendre.java} (100%) diff --git a/Others/GuassLengendre.java b/Others/GuassLegendre.java similarity index 100% rename from Others/GuassLengendre.java rename to Others/GuassLegendre.java From b123975b56287baf1e0b453b875f621dfc9c7c05 Mon Sep 17 00:00:00 2001 From: ulvi Date: Sun, 27 Jan 2019 02:26:01 +0400 Subject: [PATCH 088/112] added new field and modified some methods --- DataStructures/Lists/SinglyLinkedList.java | 64 +++++++++++++--------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index d7d721b2ec1c..e1eef01f5563 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -1,14 +1,14 @@ /** * This class implements a SinglyLinked List. This is done * using SinglyLinkedList class and a LinkForLinkedList Class. - * + * * A linked list is similar to an array, it hold values. * However, links in a linked list do not have indexes. With * a linked list you do not need to predetermine it's size as * it grows and shrinks as it is edited. This is an example of * a singly linked list. Elements can only be added/removed * at the head/front of the list. - * + * * @author Unknown * */ @@ -25,15 +25,23 @@ public SinglyLinkedList(){ /** * This method inserts an element at the head - * + * * @param x Element to be added */ public void insertHead(int x){ Node newNode = new Node(x); //Create a new link with a value attached to it newNode.next = head; //Set the new link to point to the current head head = newNode; //Now set the new link to be the head + Node.indexCount++; //Count the all indexes of inserted values } - + /** + * Insert values at spesific position + * @param number inserted value + * @param position spesific position of inserted value + */ + public void addToSpecifiedPosition(int number, int position) { + InsertNth(head, number, position); + } /** * Inserts a new node at a specified position @@ -44,40 +52,37 @@ public void insertHead(int x){ */ Node InsertNth(Node head, int data, int position) { - - Node newNode = new Node(); - newNode.data = data; - - if (position == 0) { - newNode.next = head; - return newNode; - } + Node newNode = new Node(data); Node current = head; + int temp = position - Node.getIndexCount(); - while (--position > 0) { - current = current.next; + while (temp-- > 0) { + insertHead(0); + System.out.println("Do something " + Node.indexCount); } - - newNode.next = current.next; - current.next = newNode; + + newNode.next = current; + head = newNode; + insertHead(newNode.value); return head; } - + /** * This method deletes an element at the head - * + * * @return The element deleted */ public Node deleteHead(){ Node temp = head; head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head + --Node.indexCount; return temp; } /** * Checks if the list is empty - * + * * @return true is list is empty */ public boolean isEmpty(){ @@ -95,10 +100,10 @@ public void display(){ } System.out.println(); } - + /** * Main method - * + * * @param args Command line arguments */ public static void main(String args[]){ @@ -122,19 +127,23 @@ public static void main(String args[]){ * This class is the nodes of the SinglyLinked List. * They consist of a value and a pointer to the node * after them. - * + * * @author Unknown * */ class Node{ /** The value of the node */ public int value; + /** + * The count of Indexes + */ + public static int indexCount; /** Point to the next node */ public Node next; //This is what the link will point to /** * Constructor - * + * * @param valuein Value to be put in the node */ public Node(int valuein){ @@ -147,5 +156,10 @@ public Node(int valuein){ public int getValue(){ return value; } - + /** + * @return the count of indexes + */ + public static int getIndexCount() { + return indexCount; + } } From f348e1832b1e0232c44539ad09203cf5348618c6 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 27 Jan 2019 09:46:48 +0800 Subject: [PATCH 089/112] Update SinglyLinkedList.java --- DataStructures/Lists/SinglyLinkedList.java | 236 ++++++++++----------- 1 file changed, 110 insertions(+), 126 deletions(-) diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index e1eef01f5563..1d61e31b2ad0 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -1,7 +1,7 @@ /** * This class implements a SinglyLinked List. This is done * using SinglyLinkedList class and a LinkForLinkedList Class. - * + *

* 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 @@ -9,118 +9,115 @@ * a singly linked list. Elements can only be added/removed * at the head/front of the list. * - * @author Unknown - * + * @author yanglbme */ -class SinglyLinkedList{ - /**Head refered to the front of the list */ - private Node head; - - /** - * Constructor of SinglyLinkedList - */ - public SinglyLinkedList(){ - head = null; - } - - /** - * This method inserts an element at the head - * - * @param x Element to be added - */ - public void insertHead(int x){ - Node newNode = new Node(x); //Create a new link with a value attached to it - newNode.next = head; //Set the new link to point to the current head - head = newNode; //Now set the new link to be the head - Node.indexCount++; //Count the all indexes of inserted values - } +class SinglyLinkedList { + /** + * Head refer to the front of the list + */ + private Node head; + /** - * Insert values at spesific position - * @param number inserted value - * @param position spesific position of inserted value + * Count of nodes */ - public void addToSpecifiedPosition(int number, int position) { - InsertNth(head, number, position); + private int count; + + /** + * This method inserts an element at the head + * + * @param x Element to be added + */ + public void insertHead(int x) { + Node newNode = new Node(x); + newNode.next = head; + head = newNode; + ++count; } - /** + /** * Inserts a new node at a specified position - * @param head head node of the linked list + * * @param data data to be stored in a new node * @param position position at which a new node is to be inserted - * @return reference of the head of the linked list */ - Node InsertNth(Node head, int data, int position) { - - Node newNode = new Node(data); - Node current = head; - int temp = position - Node.getIndexCount(); + public void insertNth(int data, int position) { + if (position < 0 || position > count) { + throw new RuntimeException("position less than zero or position more than the count of list"); + } + Node node = new Node(data); + Node dummy = new Node(-1); + dummy.next = head; + Node cur = dummy; + for (int i = 0; i < position; ++i) { + cur = cur.next; + } + node.next = cur.next; + cur.next = node; + ++count; + } - while (temp-- > 0) { - insertHead(0); - System.out.println("Do something " + Node.indexCount); + /** + * This method deletes an element at the head + * + * @return The element deleted + */ + public Node deleteHead() { + if (isEmpty()) { + throw new RuntimeException("The list is empty!"); } - newNode.next = current; - head = newNode; - insertHead(newNode.value); - return head; + Node temp = head; + head = head.next; + --count; + return temp; + } + + /** + * Checks if the list is empty + * + * @return true is list is empty + */ + public boolean isEmpty() { + return count == 0; } - /** - * This method deletes an element at the head - * - * @return The element deleted - */ - public Node deleteHead(){ - Node temp = head; - head = head.next; //Make the second element in the list the new head, the Java garbage collector will later remove the old head - --Node.indexCount; - return temp; - } - - /** - * Checks if the list is empty - * - * @return true is list is empty - */ - public boolean isEmpty(){ - return(head == null); - } - - /** - * Prints contents of the list - */ - public void display(){ - Node current = head; - while(current!=null){ - System.out.print(current.getValue()+" "); - current = current.next; - } - System.out.println(); - } - - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String args[]){ - SinglyLinkedList myList = new SinglyLinkedList(); - - System.out.println(myList.isEmpty()); //Will print true - - myList.insertHead(5); - myList.insertHead(7); - myList.insertHead(10); - - myList.display(); // 10(head) --> 7 --> 5 - - myList.deleteHead(); - - myList.display(); // 7(head) --> 5 - } + /** + * Prints contents of the list + */ + public void display() { + Node current = head; + while (current != null) { + System.out.print(current.value + " "); + current = current.next; + } + System.out.println(); + } + + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + SinglyLinkedList myList = new SinglyLinkedList(); + + assert myList.isEmpty(); + + myList.insertHead(5); + myList.insertHead(7); + myList.insertHead(10); + + myList.display(); // 10 -> 7 -> 5 + + myList.deleteHead(); + + myList.display(); // 7 -> 5 + + myList.insertNth(11, 2); + + myList.display(); // 7 -> 5 -> 11 + } } /** @@ -128,38 +125,25 @@ public static void main(String args[]){ * They consist of a value and a pointer to the node * after them. * - * @author Unknown - * + * @author yanglbme */ -class Node{ - /** The value of the node */ - public int value; +class Node { /** - * The count of Indexes + * The value of the node */ - public static int indexCount; - /** Point to the next node */ - public Node next; //This is what the link will point to - - /** - * Constructor - * - * @param valuein Value to be put in the node - */ - public Node(int valuein){ - value = valuein; - } - - /** - * Returns value of the node - */ - public int getValue(){ - return value; - } + int value; + + /** + * Point to the next node + */ + Node next; + /** - * @return the count of indexes + * Constructor + * + * @param value Value to be put in the node */ - public static int getIndexCount() { - return indexCount; + Node(int value) { + this.value = value; } } From d4f05e3af10f92d55c7e297c82bf0334d565ac24 Mon Sep 17 00:00:00 2001 From: saeed jinat Date: Wed, 30 Jan 2019 03:14:57 +0200 Subject: [PATCH 090/112] CursorLinkedList added CursorLinkedList basic implementation --- DataStructures/Lists/CursorLinkedList.java | 215 +++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 DataStructures/Lists/CursorLinkedList.java diff --git a/DataStructures/Lists/CursorLinkedList.java b/DataStructures/Lists/CursorLinkedList.java new file mode 100644 index 000000000000..04e2115df82b --- /dev/null +++ b/DataStructures/Lists/CursorLinkedList.java @@ -0,0 +1,215 @@ +public class CursorLinkedList { + + private static class Node { + + T element; + int next; + + Node(T element, int next) { + this.element = element; + this.next = next; + } + + boolean isEmpty() { + return element == null; + } + } + + + private final int os; + private int head; + private final Node[] cursorSpace; + private int count; + private final static int CURSOR_SPACE_SIZE = 100; + + + { + // init at loading time + cursorSpace = new Node[CURSOR_SPACE_SIZE]; + for (int i = 0; i < CURSOR_SPACE_SIZE; i++) { + cursorSpace[i] = new Node<>(null, i + 1); + } + cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0; + } + + + public CursorLinkedList() { + os = 0; + count = 0; + head = -1; + } + + public void printList() { + + if (head != -1) { + + + int start = head; + while (start != -1) { + + T element = cursorSpace[start].element; + System.out.println(element.toString()); + start = cursorSpace[start].next; + } + } + + } + + + /** + * @return the logical index of the element within the list , not the actual + * index of the [cursorSpace] array + */ + public int indexOf(T element) { + + + Objects.requireNonNull(element); + Node iterator = cursorSpace[head]; + for (int i = 0; i < count; i++) { + if (iterator.element.equals(element)) { + return i; + } + iterator = cursorSpace[iterator.next]; + } + + + return -1; + } + + + /** + * @param position , the logical index of the element , not the actual one + * within the [cursorSpace] array . + * this method should be used to get the index give by indexOf() method. + * @return + */ + + public T get(int position) { + + if (position >= 0 && position < count) { + + int start = head; + int counter = 0; + while (start != -1) { + + T element = cursorSpace[start].element; + if (counter == position){ + return element; + } + + start = cursorSpace[start].next; + counter++; + } + + } + + return null; + } + + + public void removeByIndex(int index){ + + if(index >= 0 && index < count){ + + T element = get(index); + remove(element); + } + + } + + public void remove(T element) { + + + Objects.requireNonNull(element); + + // case element is in the head + T temp_element = cursorSpace[head].element; + int temp_next = cursorSpace[head].next; + if (temp_element.equals(element)) { + free(head); + head = temp_next; + } else { // otherwise cases + + int prev_index = head; + int current_index = cursorSpace[prev_index].next; + + while (current_index != -1 ) { + + T current_element = cursorSpace[current_index].element; + if(current_element.equals(element)){ + cursorSpace[prev_index].next = cursorSpace[current_index].next; + free(current_index); + break; + } + + prev_index = current_index; + current_index = cursorSpace[prev_index].next; + } + + } + + + count--; + + } + + private void free(int index) { + + Node os_node = cursorSpace[os]; + int os_next = os_node.next; + cursorSpace[os].next = index; + cursorSpace[index].element = null; + cursorSpace[index].next = os_next; + + } + + + public void append(T element) { + + Objects.requireNonNull(element); + int availableIndex = alloc(); + cursorSpace[availableIndex].element = element; + + if (head == -1) { + head = availableIndex; + } + + int iterator = head; + while (cursorSpace[iterator].next != -1) { + iterator = cursorSpace[iterator].next; + } + + cursorSpace[iterator].next = availableIndex; + cursorSpace[availableIndex].next = -1; + + + count++; + } + + /** + * @return the index of the next available node + */ + private int alloc() { + + + //1- get the index at which the os is pointing + int availableNodeIndex = cursorSpace[os].next; + + if (availableNodeIndex == 0) { + throw new OutOfMemoryError(); + } + + //2- make the os point to the next of the @var{availableNodeIndex} + int availableNext = cursorSpace[availableNodeIndex].next; + cursorSpace[os].next = availableNext; + + // this to indicate an end of the list , helpful at testing since any err + // would throw an outOfBoundException + cursorSpace[availableNodeIndex].next = -1; + + return availableNodeIndex; + + } + + +} From 2c38098a1c008f2b2f7a5d2f20508d31ca74221d Mon Sep 17 00:00:00 2001 From: saeed jinat Date: Wed, 30 Jan 2019 12:09:35 +0200 Subject: [PATCH 091/112] Update README.md added Cursor Linked List to the table --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 08c79b28baf3..522a80e1b083 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,7 @@ Graphs|Heaps|Lists|Queues| [DFS](DataStructures/Graphs/DFS.java)|[Heap](DataStructures/Heaps/Heap.java)|[Doubly Linked List](DataStructures/Lists/DoublyLinkedList.java)|[Queues](DataStructures/Queues/Queues.java)| [Graphs](DataStructures/Graphs/Graphs.java)|[Heap Element](DataStructures/Heaps/HeapElement.java)|[Singly Linked List](DataStructures/Lists/SinglyLinkedList.java)| [Kruskals Algorithm](DataStructures/Graphs/KruskalsAlgorithm.java)|[Max Heap](Data%Structures/Heaps/MaxHeap.java)| +[CursorLinkedList](DataStructures/Lists/CursorLinkedList.java)| [Matrix Graphs](DataStructures/Graphs/MatrixGraphs.java)|[Min Heap](DataStructures/Heaps/MinHeap.java)| [PrimMST](DataStructures/Graphs/PrimMST.java)| From 22e7f7f147b4fcd0e142d135aa35bb988aba54d4 Mon Sep 17 00:00:00 2001 From: Ivan Kuzaev Date: Sun, 3 Feb 2019 08:50:02 +0300 Subject: [PATCH 092/112] Update PalindromicPrime.java Method prime(num) uses only odd numbers from 3 to square root of num as divisors. In method functioning(y) we iterate over odd numbers as all even numbers (except of 2) are not prime. In method functioning(y) we check at first if the number is palindrome and then if it's prime, so we don't have to call the heavy prime() method for every number. The speed of searching palindromic primes is significantly increased. --- Misc/PalindromicPrime.java | 39 ++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/Misc/PalindromicPrime.java b/Misc/PalindromicPrime.java index 866467206456..bb2c82480634 100644 --- a/Misc/PalindromicPrime.java +++ b/Misc/PalindromicPrime.java @@ -1,15 +1,16 @@ import java.util.Scanner; + public class PalindromePrime { public static void main(String[] args) { // Main funtion Scanner in = new Scanner(System.in); System.out.println("Enter the quantity of First Palindromic Primes you want"); - int n = in.nextInt(); // Input of how mant first pallindromic prime we want - funtioning(n); // calling funtion - functioning + int n = in.nextInt(); // Input of how many first pallindromic prime we want + functioning(n); // calling function - functioning } public static boolean prime(int num) { // checking if number is prime or not - for (int divisor = 2; divisor <= num / 2; divisor++) { + for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { if (num % divisor == 0) { return false; // false if not prime } @@ -17,25 +18,27 @@ public static boolean prime(int num) { // checking if number is prime or not return true; // True if prime } - public static int reverse(int n){ // Returns the reverse of the number + public static int reverse(int n) { // Returns the reverse of the number int reverse = 0; - while(n!=0){ - reverse = reverse * 10; - reverse = reverse + n%10; - n = n/10; + while(n != 0) { + reverse *= 10; + reverse += n%10; + n /= 10; } return reverse; } - public static void funtioning(int y){ - int count =0; - int num = 2; - while(count < y){ - if(prime(num) && num == reverse(num)){ // number is prime and it's reverse is same - count++; // counts check when to terminate while loop - System.out.print(num + "\n"); // Print the Palindromic Prime - } - num++; // inrease iterator value by one + public static void functioning(int y) { + if (y == 0) return; + System.out.print(2 + "\n"); // print the first Palindromic Prime + int count = 1; + int num = 3; + while(count < y) { + if(num == reverse(num) && prime(num)) { // number is prime and it's reverse is same + count++; // counts check when to terminate while loop + System.out.print(num + "\n"); // print the Palindromic Prime } + num += 2; // inrease iterator value by two + } } -}; +} From 6351bf2efcb0a07623261c3a3cb4b3de193fcc56 Mon Sep 17 00:00:00 2001 From: Bolot Bekbolotov Date: Sun, 3 Feb 2019 20:48:44 +0600 Subject: [PATCH 093/112] Added Euler's totient Function --- Others/EulersFunction.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Others/EulersFunction.java diff --git a/Others/EulersFunction.java b/Others/EulersFunction.java new file mode 100644 index 000000000000..27f4f1f739f6 --- /dev/null +++ b/Others/EulersFunction.java @@ -0,0 +1,20 @@ +//You can read more about Euler's totient function https://en.wikipedia.org/wiki/Euler%27s_totient_function +public class EulersFunction { + //This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity; + public static int getEuler(int n) { + int result = n; + for (int i = 2; i * i <= n; i++) { + if(n % i == 0) { + while (n % i == 0) n /= i; + result -= result / i; + } + } + if (n > 1) result -= result / n; + return result; + } + public static void main(String[] args) { + for(int i = 1; i < 100; i++) { + System.out.println(getEuler(i)); + } + } +} From 12215a11d3b77c45e074daf096fd1cf43a15cb93 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Mon, 4 Feb 2019 11:27:42 +0800 Subject: [PATCH 094/112] Update EulersFunction.java --- Others/EulersFunction.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Others/EulersFunction.java b/Others/EulersFunction.java index 27f4f1f739f6..01b7575d4dc5 100644 --- a/Others/EulersFunction.java +++ b/Others/EulersFunction.java @@ -1,6 +1,7 @@ -//You can read more about Euler's totient function https://en.wikipedia.org/wiki/Euler%27s_totient_function +// You can read more about Euler's totient function +// https://en.wikipedia.org/wiki/Euler%27s_totient_function public class EulersFunction { - //This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity; + // This method returns us number of x that (x < n) and gcd(x, n) == 1 in O(sqrt(n)) time complexity; public static int getEuler(int n) { int result = n; for (int i = 2; i * i <= n; i++) { @@ -13,7 +14,7 @@ public static int getEuler(int n) { return result; } public static void main(String[] args) { - for(int i = 1; i < 100; i++) { + for (int i = 1; i < 100; i++) { System.out.println(getEuler(i)); } } From cbfa8875aa2f882688685b0f5b71ad96f6c16c61 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Mon, 4 Feb 2019 16:18:12 +0800 Subject: [PATCH 095/112] Update CSVFile.java to fix #705 - Fix wrong assignation --- DataStructures/CSVFile/src/CSVFile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DataStructures/CSVFile/src/CSVFile.java b/DataStructures/CSVFile/src/CSVFile.java index 7bc6186c1daf..e838a24670ae 100644 --- a/DataStructures/CSVFile/src/CSVFile.java +++ b/DataStructures/CSVFile/src/CSVFile.java @@ -136,7 +136,7 @@ public CSVFile(char separator) { table = new ArrayList>(); trackList = new ArrayList(); pathCSVFile = ""; - this.seperator = seperator; + this.seperator = separator; } From f2f79821acde62c58671ad9990dca78e2bbbb1c0 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 5 Feb 2019 13:03:37 +0800 Subject: [PATCH 096/112] fix: remove unused imports to fix #699 - Fix #699 - Thanks @lprone --- Conversions/HexaDecimalToBinary.java | 15 +++----- Others/RootPrecision.java | 55 ++++++++++++++-------------- 2 files changed, 32 insertions(+), 38 deletions(-) diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java index 29608e1d6999..b6457beff2b6 100644 --- a/Conversions/HexaDecimalToBinary.java +++ b/Conversions/HexaDecimalToBinary.java @@ -1,18 +1,13 @@ -import java.lang.StringBuilder; -import java.util.*; -import java.util.Scanner; -import javax.swing.*; - public class HexaDecimalToBinary { - + private final int LONG_BITS = 8; public void convert(String numHex) { - //String a HexaDecimal: + // String a HexaDecimal: int conHex = Integer.parseInt(numHex, 16); - //Hex a Binary: + // Hex a Binary: String binary = Integer.toBinaryString(conHex); - //Presentation: + // Presentation: System.out.println(numHex + " = " + completeDigits(binary)); } @@ -27,7 +22,7 @@ public static void main(String[] args) { //Testing Numbers: String[] hexNums = {"1", "A1", "ef", "BA", "AA", "BB", - "19", "01", "02", "03", "04"}; + "19", "01", "02", "03", "04"}; HexaDecimalToBinary objConvert = new HexaDecimalToBinary(); for (String num : hexNums) { diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java index b792d692f675..3e3b73b82836 100644 --- a/Others/RootPrecision.java +++ b/Others/RootPrecision.java @@ -1,33 +1,32 @@ -import java.io.*; -import java.util.*; -import java.text.*; -import java.math.*; -import java.util.regex.*; +import java.util.Scanner; 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)); - } - - public static double squareRoot(int N, int P) { - double rv = 0; //rv means return value - + // take input + Scanner scn = new Scanner(System.in); + + // N is the input number + int N = scn.nextInt(); + + // P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870. + int P = scn.nextInt(); + System.out.println(squareRoot(N, P)); + } + + public static double squareRoot(int N, int P) { + // rv means return value + double rv; + double root = Math.pow(N, 0.5); - - //calculate precision to power of 10 and then multiply it with root value. - int precision = (int) Math.pow(10, P); - 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 */ - - rv = (int)root; - return (double)rv/precision; - } -} + + // calculate precision to power of 10 and then multiply it with root value. + int precision = (int) Math.pow(10, P); + 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 */ + + rv = (int) root; + return rv / precision; + } +} \ No newline at end of file From bb670a2cebd7f5af76957a5f46c962c82bf6995b Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 5 Feb 2019 13:10:40 +0800 Subject: [PATCH 097/112] fix: remove unnecesary assignation to fix #698 - Fix #698 - Thanks @lprone --- Dynamic Programming/Fibonacci.java | 72 +++++++++++++----------------- 1 file changed, 30 insertions(+), 42 deletions(-) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index d177b5bb9c5d..8f9326ba9d94 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -4,14 +4,13 @@ import java.util.Map; /** - * * @author Varun Upadhyay (https://github.com/varunu28) - * + * @author yanglbme (https://github.com/yanglbme) */ public class Fibonacci { - private static Map map = new HashMap(); + private static Map map = new HashMap<>(); public static void main(String[] args) throws Exception { @@ -26,13 +25,8 @@ public static void main(String[] args) throws Exception { * This method finds the nth fibonacci number using memoization technique * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number + * Outputs the nth fibonacci number **/ - - - - - private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); @@ -42,10 +36,9 @@ private static int fibMemo(int n) { if (n <= 2) { f = 1; - } - else { - f = fibMemo(n-1) + fibMemo(n-2); - map.put(n,f); + } else { + f = fibMemo(n - 1) + fibMemo(n - 2); + map.put(n, f); } return f; @@ -55,55 +48,50 @@ private static int fibMemo(int n) { * This method finds the nth fibonacci number using bottom up * * @param n The input n for which we have to determine the fibonacci number - * Outputs the nth fibonacci number + * Outputs the nth fibonacci number **/ - private static int fibBotUp(int n) { - Map fib = new HashMap(); + Map fib = new HashMap<>(); - for (int i=1;i + * This is optimized version of Fibonacci Program. Without using Hashmap and recursion. + * It saves both memory and time. + * Space Complexity will be O(1) + * Time Complexity will be O(n) + *

+ * Whereas , the above functions will take O(n) Space. + * @author Shoaib Rayeen (https://github.com/shoaibrayeen) **/ private static int fibOptimized(int n) { - if (n == 0) { return 0; } - int prev = 0 , res = 1 , next; - for ( int i = 2; i < n; i++) { - next = prev + res; - prev = res; - res = next; + int prev = 0, res = 1, next; + for (int i = 2; i < n; i++) { + next = prev + res; + prev = res; + res = next; } return res; } -} - +} \ No newline at end of file From 8b92c3fdbeedb7ae0d3b5b6d79871af91cf7c2ea Mon Sep 17 00:00:00 2001 From: yanglbme Date: Wed, 6 Feb 2019 10:13:55 +0800 Subject: [PATCH 098/112] fix: remove unnecesary throw to fix #704 - Fix #704 - Thanks @lprone --- DataStructures/Heaps/EmptyHeapException.java | 7 +- DataStructures/Heaps/Heap.java | 25 +- DataStructures/Heaps/HeapElement.java | 58 ++-- DataStructures/Heaps/MaxHeap.java | 94 +++--- DataStructures/Heaps/MinHeap.java | 86 ++--- DataStructures/Heaps/MinPriorityQueue.java | 42 +-- .../LongestIncreasingSubsequence.java | 29 +- Others/Dijkshtra.java | 73 ++-- Others/Dijkstra.java | 319 +++++++++--------- 9 files changed, 369 insertions(+), 364 deletions(-) diff --git a/DataStructures/Heaps/EmptyHeapException.java b/DataStructures/Heaps/EmptyHeapException.java index b7d853c56845..01668e2c849a 100644 --- a/DataStructures/Heaps/EmptyHeapException.java +++ b/DataStructures/Heaps/EmptyHeapException.java @@ -1,16 +1,15 @@ /** - * + * */ -package heaps; +package Heaps; /** * @author Nicolas Renard * Exception to be thrown if the getElement method is used on an empty heap. - * */ @SuppressWarnings("serial") public class EmptyHeapException extends Exception { - + public EmptyHeapException(String message) { super(message); } diff --git a/DataStructures/Heaps/Heap.java b/DataStructures/Heaps/Heap.java index 02b2ba270918..fe87d72a1db2 100644 --- a/DataStructures/Heaps/Heap.java +++ b/DataStructures/Heaps/Heap.java @@ -1,4 +1,4 @@ -package heaps; +package Heaps; /** * Interface common to heap data structures.
@@ -10,32 +10,31 @@ * max-heap).

*

All heap-related operations (inserting or deleting an element, extracting the min or max) are performed in * O(log n) time.

+ * * @author Nicolas Renard - * - * */ public interface Heap { - + /** - * * @return the top element in the heap, the one with lowest key for min-heap or with * the highest key for max-heap - * @throws Exception if heap is empty + * @throws EmptyHeapException if heap is empty */ - public abstract HeapElement getElement() throws EmptyHeapException; + HeapElement getElement() throws EmptyHeapException; + /** * Inserts an element in the heap. Adds it to then end and toggle it until it finds its * right position. - * + * * @param element an instance of the HeapElement class. */ - public abstract void insertElement(HeapElement element); - + void insertElement(HeapElement element); + /** * Delete an element in the heap. - * + * * @param elementIndex int containing the position in the heap of the element to be deleted. */ - public abstract void deleteElement(int elementIndex); + void deleteElement(int elementIndex); -} +} \ No newline at end of file diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index e0cc93ccbfe0..60640346b3cc 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -1,7 +1,7 @@ /** - * + * */ -package heaps; +package Heaps; import java.lang.Double; import java.lang.Object; @@ -12,116 +12,110 @@ * or double, either primitive type or object) and any kind of IMMUTABLE object the user sees fit * to carry any information he/she likes. Be aware that the use of a mutable object might * jeopardize the integrity of this information.

- * @author Nicolas Renard * + * @author Nicolas Renard */ public class HeapElement { private final double key; private final Object additionalInfo; - + // Constructors /** - * - * @param key : a number of primitive type 'double' + * @param key : a number of primitive type 'double' * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user + * additional information of use for the user */ public HeapElement(double key, Object info) { this.key = key; this.additionalInfo = info; } - + /** - * - * @param key : a number of primitive type 'int' + * @param key : a number of primitive type 'int' * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user + * additional information of use for the user */ public HeapElement(int key, Object info) { this.key = key; this.additionalInfo = info; } - + /** - * - * @param key : a number of object type 'Integer' + * @param key : a number of object type 'Integer' * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user + * additional information of use for the user */ public HeapElement(Integer key, Object info) { this.key = key; this.additionalInfo = info; } - + /** - * - * @param key : a number of object type 'Double' + * @param key : a number of object type 'Double' * @param info : any kind of IMMUTABLE object. May be null, since the purpose is only to carry - * additional information of use for the user + * additional information of use for the user */ public HeapElement(Double key, Object info) { this.key = key; this.additionalInfo = info; } - + /** - * * @param key : a number of primitive type 'double' */ public HeapElement(double key) { this.key = key; this.additionalInfo = null; } - + /** - * * @param key : a number of primitive type 'int' */ public HeapElement(int key) { this.key = key; this.additionalInfo = null; } - + /** - * * @param key : a number of object type 'Integer' */ public HeapElement(Integer key) { this.key = key; this.additionalInfo = null; } - + /** - * * @param key : a number of object type 'Double' */ public HeapElement(Double key) { this.key = key; this.additionalInfo = null; } - + // Getters + /** * @return the object containing the additional info provided by the user. */ public Object getInfo() { return additionalInfo; } + /** * @return the key value of the element */ public double getKey() { return key; } - + // Overridden object methods - + public String toString() { - return "Key: " + key + " - " +additionalInfo.toString(); + return "Key: " + key + " - " + additionalInfo.toString(); } + /** - * * @param otherHeapElement * @return true if the keys on both elements are identical and the additional info objects * are identical. diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java index 5f774e3534a8..302840c14d05 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -1,4 +1,4 @@ -package heaps; +package Heaps; import java.util.ArrayList; import java.util.List; @@ -6,66 +6,71 @@ /** * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal * to its children's. - * @author Nicolas Renard * + * @author Nicolas Renard */ public class MaxHeap implements Heap { - + private final List maxHeap; - - public MaxHeap(List listElements) throws Exception { - maxHeap = new ArrayList(); + + public MaxHeap(List listElements) { + maxHeap = new ArrayList<>(); for (HeapElement heapElement : listElements) { if (heapElement != null) insertElement(heapElement); else System.out.println("Null element. Not added to heap"); } if (maxHeap.size() == 0) System.out.println("No element has been added, empty heap."); - } - - // Get the element at a given index. The key for the list is equal to index value - 1 + } + + /** + * Get the element at a given index. The key for the list is equal to index value - 1 + * + * @param elementIndex index + * @return heapElement + */ public HeapElement getElement(int elementIndex) { - if ((elementIndex <= 0) && (elementIndex > maxHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range"); + if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) + throw new IndexOutOfBoundsException("Index out of heap range"); return maxHeap.get(elementIndex - 1); } - + // Get the key of the element at a given index private double getElementKey(int elementIndex) { return maxHeap.get(elementIndex - 1).getKey(); } - + // Swaps two elements in the heap private void swap(int index1, int index2) { HeapElement temporaryElement = maxHeap.get(index1 - 1); maxHeap.set(index1 - 1, maxHeap.get(index2 - 1)); maxHeap.set(index2 - 1, temporaryElement); } - - // Toggle an element up to its right place as long as its key is lower than its parent's + + // Toggle an element up to its right place as long as its key is lower than its parent's private void toggleUp(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex/2)) < key) { - swap(elementIndex, (int) Math.floor(elementIndex/2)); - elementIndex = (int) Math.floor(elementIndex/2); + while (getElementKey((int) Math.floor(elementIndex / 2)) < key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2)); + elementIndex = (int) Math.floor(elementIndex / 2); } } - + // Toggle an element down to its right place as long as its key is higher - // than any of its children's + // than any of its children's private void toggleDown(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size()))); - while ((2*elementIndex <= maxHeap.size()) && wrongOrder) { + boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { // Check whether it shall swap the element with its left child or its right one if any. - if ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex*2 + 1) > getElementKey(elementIndex*2))) { - swap(elementIndex, 2*elementIndex + 1); - elementIndex = 2*elementIndex + 1; + if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { + swap(elementIndex, 2 * elementIndex + 1); + elementIndex = 2 * elementIndex + 1; + } else { + swap(elementIndex, 2 * elementIndex); + elementIndex = 2 * elementIndex; } - else { - swap(elementIndex, 2*elementIndex); - elementIndex = 2*elementIndex; - } - wrongOrder = (key < getElementKey(elementIndex*2)) || (key < getElementKey(Math.min(elementIndex*2, maxHeap.size()))); - + wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + } } @@ -84,21 +89,23 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (maxHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } - if ((elementIndex > maxHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range"); + if (maxHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) + throw new IndexOutOfBoundsException("Index out of heap range"); // The last element in heap replaces the one to be deleted maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); maxHeap.remove(maxHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex); - // ... or down ? - else if (((2*elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2))) || - ((2*elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex*2)))) toggleDown(elementIndex); + if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex); + // ... or down ? + else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || + ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) + toggleDown(elementIndex); } @Override @@ -109,7 +116,4 @@ public HeapElement getElement() throws EmptyHeapException { throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } - -} - - +} \ No newline at end of file diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java index fbf2b86ffc3e..5fca978f6549 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -1,7 +1,7 @@ /** - * + * */ -package heaps; +package Heaps; import java.util.ArrayList; import java.util.List; @@ -9,66 +9,66 @@ /** * Heap tree where a node's key is higher than or equal to its parent's and lower than or equal * to its children's. - * @author Nicolas Renard * + * @author Nicolas Renard */ public class MinHeap implements Heap { - + private final List minHeap; - - public MinHeap(List listElements) throws Exception { - minHeap = new ArrayList(); + + public MinHeap(List listElements) { + minHeap = new ArrayList<>(); for (HeapElement heapElement : listElements) { if (heapElement != null) insertElement(heapElement); else System.out.println("Null element. Not added to heap"); } if (minHeap.size() == 0) System.out.println("No element has been added, empty heap."); } - + // Get the element at a given index. The key for the list is equal to index value - 1 public HeapElement getElement(int elementIndex) { - if ((elementIndex <= 0) && (elementIndex > minHeap.size())) throw new IndexOutOfBoundsException("Index out of heap range"); + if ((elementIndex <= 0) || (elementIndex > minHeap.size())) + throw new IndexOutOfBoundsException("Index out of heap range"); return minHeap.get(elementIndex - 1); } - + // Get the key of the element at a given index private double getElementKey(int elementIndex) { return minHeap.get(elementIndex - 1).getKey(); } - + // Swaps two elements in the heap private void swap(int index1, int index2) { HeapElement temporaryElement = minHeap.get(index1 - 1); minHeap.set(index1 - 1, minHeap.get(index2 - 1)); minHeap.set(index2 - 1, temporaryElement); } - - // Toggle an element up to its right place as long as its key is lower than its parent's + + // Toggle an element up to its right place as long as its key is lower than its parent's private void toggleUp(int elementIndex) { double key = minHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex/2)) > key) { - swap(elementIndex, (int) Math.floor(elementIndex/2)); - elementIndex = (int) Math.floor(elementIndex/2); + while (getElementKey((int) Math.floor(elementIndex / 2)) > key) { + swap(elementIndex, (int) Math.floor(elementIndex / 2)); + elementIndex = (int) Math.floor(elementIndex / 2); } } - + // Toggle an element down to its right place as long as its key is higher - // than any of its children's + // than any of its children's private void toggleDown(int elementIndex) { double key = minHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size()))); - while ((2*elementIndex <= minHeap.size()) && wrongOrder) { + boolean wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + while ((2 * elementIndex <= minHeap.size()) && wrongOrder) { // Check whether it shall swap the element with its left child or its right one if any. - if ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex*2 + 1) < getElementKey(elementIndex*2))) { - swap(elementIndex, 2*elementIndex + 1); - elementIndex = 2*elementIndex + 1; - } - else { - swap(elementIndex, 2*elementIndex); - elementIndex = 2*elementIndex; + if ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex * 2 + 1) < getElementKey(elementIndex * 2))) { + swap(elementIndex, 2 * elementIndex + 1); + elementIndex = 2 * elementIndex + 1; + } else { + swap(elementIndex, 2 * elementIndex); + elementIndex = 2 * elementIndex; } - wrongOrder = (key > getElementKey(elementIndex*2)) || (key > getElementKey(Math.min(elementIndex*2, minHeap.size()))); - + wrongOrder = (key > getElementKey(elementIndex * 2)) || (key > getElementKey(Math.min(elementIndex * 2, minHeap.size()))); + } } @@ -87,23 +87,25 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) { - if (minHeap.isEmpty()) - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } - if ((elementIndex > minHeap.size()) && (elementIndex <= 0)) throw new IndexOutOfBoundsException("Index out of heap range"); + if (minHeap.isEmpty()) + try { + throw new EmptyHeapException("Attempt to delete an element from an empty heap"); + } catch (EmptyHeapException e) { + e.printStackTrace(); + } + if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) + throw new IndexOutOfBoundsException("Index out of heap range"); // The last element in heap replaces the one to be deleted minHeap.set(elementIndex - 1, getElement(minHeap.size())); minHeap.remove(minHeap.size()); // Shall the new element be moved up... - if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex/2))) toggleUp(elementIndex); - // ... or down ? - else if (((2*elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2))) || - ((2*elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex*2)))) toggleDown(elementIndex); + if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex); + // ... or down ? + else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) || + ((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2)))) + toggleDown(elementIndex); } - + @Override public HeapElement getElement() throws EmptyHeapException { try { @@ -112,4 +114,4 @@ public HeapElement getElement() throws EmptyHeapException { throw new EmptyHeapException("Heap is empty. Error retrieving element"); } } -} +} \ No newline at end of file diff --git a/DataStructures/Heaps/MinPriorityQueue.java b/DataStructures/Heaps/MinPriorityQueue.java index 3dc2bd28083c..f117b932800b 100644 --- a/DataStructures/Heaps/MinPriorityQueue.java +++ b/DataStructures/Heaps/MinPriorityQueue.java @@ -1,13 +1,13 @@ - +package Heaps; /* Minimum Priority Queue -* It is a part of heap data structure -* A heap is a specific tree based data structure -* in which all the nodes of tree are in a specific order. -* that is the children are arranged in some -* respect of their parents, can either be greater -* or less than the parent. This makes it a min priority queue -* or max priority queue. -*/ + * It is a part of heap data structure + * A heap is a specific tree based data structure + * in which all the nodes of tree are in a specific order. + * that is the children are arranged in some + * respect of their parents, can either be greater + * or less than the parent. This makes it a min priority queue + * or max priority queue. + */ // Functions: insert, delete, peek, isEmpty, print, heapSort, sink @@ -16,15 +16,15 @@ public class MinPriorityQueue { private int capacity; private int size; - // calss the constructor and initializes the capacity + // calss the constructor and initializes the capacity MinPriorityQueue(int c) { this.capacity = c; this.size = 0; this.heap = new int[c + 1]; } - // inserts the key at the end and rearranges it - // so that the binary heap is in appropriate order + // inserts the key at the end and rearranges it + // so that the binary heap is in appropriate order public void insert(int key) { if (this.isFull()) return; @@ -41,41 +41,41 @@ public void insert(int key) { this.size++; } - // returns the highest priority value + // returns the highest priority value public int peek() { return this.heap[1]; } - // returns boolean value whether the heap is empty or not + // returns boolean value whether the heap is empty or not public boolean isEmpty() { if (0 == this.size) return true; return false; } - // returns boolean value whether the heap is full or not + // returns boolean value whether the heap is full or not public boolean isFull() { if (this.size == this.capacity) return true; return false; } - // prints the heap + // prints the heap public void print() { for (int i = 1; i <= this.capacity; i++) System.out.print(this.heap[i] + " "); System.out.println(); } - // heap sorting can be done by performing - // delete function to the number of times of the size of the heap - // it returns reverse sort because it is a min priority queue + // heap sorting can be done by performing + // delete function to the number of times of the size of the heap + // it returns reverse sort because it is a min priority queue public void heapSort() { for (int i = 1; i < this.capacity; i++) this.delete(); } - // this function reorders the heap after every delete function + // this function reorders the heap after every delete function private void sink() { int k = 1; while (2 * k <= this.size || 2 * k + 1 <= this.size) { @@ -103,7 +103,7 @@ private void sink() { } } - // deletes the highest priority value from the heap + // deletes the highest priority value from the heap public int delete() { int min = this.heap[1]; this.heap[1] = this.heap[this.size]; diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java index eaa574a40989..ccbb88468bd3 100644 --- a/Dynamic Programming/LongestIncreasingSubsequence.java +++ b/Dynamic Programming/LongestIncreasingSubsequence.java @@ -1,12 +1,11 @@ import java.util.Scanner; /** - * * @author Afrizal Fikri (https://github.com/icalF) - * + * @author Libin Yang (https://github.com/yanglbme) */ public class LongestIncreasingSubsequence { - public static void main(String[] args) throws Exception { + public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); @@ -20,7 +19,7 @@ public static void main(String[] args) throws Exception { } private static int upperBound(int[] ar, int l, int r, int key) { - while (l < r-1) { + while (l < r - 1) { int m = (l + r) / 2; if (ar[m] >= key) r = m; @@ -35,10 +34,12 @@ private static int LIS(int[] array) { int N = array.length; if (N == 0) return 0; - + int[] tail = new int[N]; - int length = 1; // always points empty slot in tail - + + // always points empty slot in tail + int length = 1; + tail[0] = array[0]; for (int i = 1; i < N; i++) { @@ -46,17 +47,17 @@ private static int LIS(int[] array) { if (array[i] < tail[0]) tail[0] = array[i]; - // array[i] extends largest subsequence - else if (array[i] > tail[length-1]) + // array[i] extends largest subsequence + else if (array[i] > tail[length - 1]) tail[length++] = array[i]; - // array[i] will become end candidate of an existing subsequence or - // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i] - // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it) + // array[i] will become end candidate of an existing subsequence or + // Throw away larger elements in all LIS, to make room for upcoming grater elements than array[i] + // (and also, array[i] would have already appeared in one of LIS, identify the location and replace it) else - tail[upperBound(tail, -1, length-1, array[i])] = array[i]; + tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; } - + return length; } } \ No newline at end of file diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java index e0bd6737a462..17f8391777aa 100644 --- a/Others/Dijkshtra.java +++ b/Others/Dijkshtra.java @@ -1,83 +1,82 @@ -/* -@author : Mayank K Jha +/** + * @author Mayank K Jha + */ -*/ - -import java.io.IOException; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; public class Dijkshtra { - public static void main(String[] args) throws IOException { + public static void main(String[] args) { Scanner in = new Scanner(System.in); // n = Number of nodes or vertices - int n = in.nextInt(); + int n = in.nextInt(); // m = Number of Edges - int m = in.nextInt(); + int m = in.nextInt(); // Adjacency Matrix - long w[][] = new long [n+1][n+1]; + long[][] w = new long[n + 1][n + 1]; - //Initializing Matrix with Certain Maximum Value for path b/w any two vertices + // Initializing Matrix with Certain Maximum Value for path b/w any two vertices for (long[] row : w) { - Arrays.fill(row, 1000000l); + Arrays.fill(row, 1000000L); } /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */ // Taking Input as Edge Location b/w a pair of vertices - for(int i = 0; i < m; i++) { - int x = in.nextInt(),y=in.nextInt(); - long cmp = in.nextLong(); - - //Comparing previous edge value with current value - Cycle Case - if(w[x][y] > cmp) { - w[x][y] = cmp; w[y][x] = cmp; - } + for (int i = 0; i < m; i++) { + int x = in.nextInt(), y = in.nextInt(); + long cmp = in.nextLong(); + + // Comparing previous edge value with current value - Cycle Case + if (w[x][y] > cmp) { + w[x][y] = cmp; + w[y][x] = cmp; + } } - // Implementing Dijkshtra's Algorithm - Stack t = new Stack(); + // Implementing Dijkshtra's Algorithm + Stack t = new Stack<>(); int src = in.nextInt(); - for(int i = 1; i <= n; i++) { - if(i != src) { + for (int i = 1; i <= n; i++) { + if (i != src) { t.push(i); } } - Stack p = new Stack(); + Stack p = new Stack<>(); p.push(src); w[src][src] = 0; - while(!t.isEmpty()) { + while (!t.isEmpty()) { int min = 989997979; int loc = -1; - for(int i = 0; i < t.size(); i++) { + for (int i = 0; i < t.size(); i++) { w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]); - if(w[src][t.elementAt(i)] <= min) { + if (w[src][t.elementAt(i)] <= min) { min = (int) w[src][t.elementAt(i)]; loc = i; } } p.push(t.elementAt(loc)); t.removeElementAt(loc); - } + } // Printing shortest path from the given source src - for(int i = 1; i <= n; i++) { - if(i != src && w[src][i] != 1000000l) { - System.out.print(w[src][i] + " "); + for (int i = 1; i <= n; i++) { + if (i != src && w[src][i] != 1000000L) { + System.out.print(w[src][i] + " "); + } + // Printing -1 if there is no path b/w given pair of edges + else if (i != src) { + System.out.print("-1" + " "); + } } - // Printing -1 if there is no path b/w given pair of edges - else if(i != src) { - System.out.print("-1" + " "); - } - } } -} +} \ No newline at end of file diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java index b3df65bfd2e3..e8ad2680fdbf 100644 --- a/Others/Dijkstra.java +++ b/Others/Dijkstra.java @@ -5,167 +5,174 @@ * 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.*; + +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(); - } + private static final Graph.Edge[] GRAPH = { + // Distance from node "a" to node "b" is 7. + // In the current Graph there is no way to move the other way (e,g, from "b" to "a"), + // a new edge would be needed for that + new Graph.Edge("a", "b", 7), + new Graph.Edge("a", "c", 9), + new Graph.Edge("a", "f", 14), + new Graph.Edge("b", "c", 10), + new Graph.Edge("b", "d", 15), + new Graph.Edge("c", "d", 11), + new Graph.Edge("c", "f", 2), + new Graph.Edge("d", "e", 6), + new Graph.Edge("e", "f", 9), + }; + private static final String START = "a"; + private static final String END = "e"; + + /** + * main function + * Will run the code with "GRAPH" that was defined above. + */ + public static void main(String[] args) { + Graph g = new Graph(GRAPH); + g.dijkstra(START); + g.printPath(END); + //g.printAllPaths(); + } } - + class Graph { - 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(); - } - } -} + // mapping of vertex names to Vertex objects, built from a set of Edges + private final Map graph; + + /** One edge of the graph (only used by Graph constructor) */ + public static class Edge { + public final String v1, v2; + public final int dist; + + public Edge(String v1, String v2, int dist) { + this.v1 = v1; + this.v2 = v2; + this.dist = dist; + } + } + + /** One vertex of the graph, complete with mappings to neighbouring vertices */ + public static class Vertex implements Comparable { + public final String name; + // MAX_VALUE assumed to be infinity + public int dist = Integer.MAX_VALUE; + public Vertex previous = null; + public final Map neighbours = new HashMap<>(); + + public Vertex(String name) { + this.name = name; + } + + private void printPath() { + if (this == this.previous) { + System.out.printf("%s", this.name); + } else if (this.previous == null) { + System.out.printf("%s(unreached)", this.name); + } else { + this.previous.printPath(); + System.out.printf(" -> %s(%d)", this.name, this.dist); + } + } + + public int compareTo(Vertex other) { + if (dist == other.dist) + return name.compareTo(other.name); + + return Integer.compare(dist, other.dist); + } + + @Override + public String toString() { + return "(" + name + ", " + dist + ")"; + } + } + + /** Builds a graph from a set of edges */ + public Graph(Edge[] edges) { + graph = new HashMap<>(edges.length); + + // one pass to find all vertices + for (Edge e : edges) { + if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1)); + if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2)); + } + + // another pass to set neighbouring vertices + for (Edge e : edges) { + graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist); + // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph + } + } + + /** Runs dijkstra using a specified source vertex */ + public void dijkstra(String startName) { + if (!graph.containsKey(startName)) { + System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName); + return; + } + final Vertex source = graph.get(startName); + NavigableSet q = new TreeSet<>(); + + // set-up vertices + for (Vertex v : graph.values()) { + v.previous = v == source ? source : null; + v.dist = v == source ? 0 : Integer.MAX_VALUE; + q.add(v); + } + + dijkstra(q); + } + + /** Implementation of dijkstra's algorithm using a binary heap. */ + private void dijkstra(final NavigableSet q) { + Vertex u, v; + while (!q.isEmpty()) { + // vertex with shortest distance (first iteration will return source) + u = q.pollFirst(); + if (u.dist == Integer.MAX_VALUE) + break; // we can ignore u (and any other remaining vertices) since they are unreachable + + // look at distances to each neighbour + for (Map.Entry a : u.neighbours.entrySet()) { + v = a.getKey(); // the neighbour in this iteration + + final int alternateDist = u.dist + a.getValue(); + if (alternateDist < v.dist) { // shorter path to neighbour found + q.remove(v); + v.dist = alternateDist; + v.previous = u; + q.add(v); + } + } + } + } + + /** Prints a path from the source to the specified vertex */ + public void printPath(String endName) { + if (!graph.containsKey(endName)) { + System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName); + return; + } + + graph.get(endName).printPath(); + System.out.println(); + } + + /** Prints the path from the source to every vertex (output order is not guaranteed) */ + public void printAllPaths() { + for (Vertex v : graph.values()) { + v.printPath(); + System.out.println(); + } + } +} \ No newline at end of file From 46bbfaa0e81168a1c431a6ffaf21448e21539750 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Thu, 7 Feb 2019 00:11:13 +0800 Subject: [PATCH 099/112] fix: fix wrong heaps package and close #700 - Fix #700 --- DataStructures/Heaps/EmptyHeapException.java | 2 +- DataStructures/Heaps/Heap.java | 2 +- DataStructures/Heaps/HeapElement.java | 2 +- DataStructures/Heaps/MaxHeap.java | 2 +- DataStructures/Heaps/MinHeap.java | 2 +- DataStructures/Heaps/MinPriorityQueue.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/DataStructures/Heaps/EmptyHeapException.java b/DataStructures/Heaps/EmptyHeapException.java index 01668e2c849a..38b4b756f3df 100644 --- a/DataStructures/Heaps/EmptyHeapException.java +++ b/DataStructures/Heaps/EmptyHeapException.java @@ -1,7 +1,7 @@ /** * */ -package Heaps; +package DataStructures.Heaps; /** * @author Nicolas Renard diff --git a/DataStructures/Heaps/Heap.java b/DataStructures/Heaps/Heap.java index fe87d72a1db2..0b7da3436581 100644 --- a/DataStructures/Heaps/Heap.java +++ b/DataStructures/Heaps/Heap.java @@ -1,4 +1,4 @@ -package Heaps; +package DataStructures.Heaps; /** * Interface common to heap data structures.
diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java index 60640346b3cc..6799f973f466 100644 --- a/DataStructures/Heaps/HeapElement.java +++ b/DataStructures/Heaps/HeapElement.java @@ -1,7 +1,7 @@ /** * */ -package Heaps; +package DataStructures.Heaps; import java.lang.Double; import java.lang.Object; diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java index 302840c14d05..fed09bcba045 100644 --- a/DataStructures/Heaps/MaxHeap.java +++ b/DataStructures/Heaps/MaxHeap.java @@ -1,4 +1,4 @@ -package Heaps; +package DataStructures.Heaps; import java.util.ArrayList; import java.util.List; diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java index 5fca978f6549..7b49b7512bac 100644 --- a/DataStructures/Heaps/MinHeap.java +++ b/DataStructures/Heaps/MinHeap.java @@ -1,7 +1,7 @@ /** * */ -package Heaps; +package DataStructures.Heaps; import java.util.ArrayList; import java.util.List; diff --git a/DataStructures/Heaps/MinPriorityQueue.java b/DataStructures/Heaps/MinPriorityQueue.java index f117b932800b..6da21ab5b03f 100644 --- a/DataStructures/Heaps/MinPriorityQueue.java +++ b/DataStructures/Heaps/MinPriorityQueue.java @@ -1,4 +1,4 @@ -package Heaps; +package DataStructures.Heaps; /* Minimum Priority Queue * It is a part of heap data structure * A heap is a specific tree based data structure From b73757e4bb0c30314b63c046cd92770e935ade2d Mon Sep 17 00:00:00 2001 From: Akhil <31859863+hailK11@users.noreply.github.com> Date: Sat, 16 Feb 2019 20:24:39 +0530 Subject: [PATCH 100/112] Update PriorityQueues.java Include condition to check if the queue is full when inserting values into the queue --- DataStructures/Queues/PriorityQueues.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/DataStructures/Queues/PriorityQueues.java b/DataStructures/Queues/PriorityQueues.java index acb6b552537e..3eb74ecf518e 100644 --- a/DataStructures/Queues/PriorityQueues.java +++ b/DataStructures/Queues/PriorityQueues.java @@ -37,6 +37,10 @@ public PriorityQueue(int size){ public void insert(int value){ if(nItems == 0){ queueArray[0] = value; + nItems++; + } + else if(isFull()){ //does not insert value when the queue is full + System.out.println("Queue is full"); } else{ int j = nItems; @@ -45,8 +49,8 @@ public void insert(int value){ j--; } queueArray[j] = value; //Once the correct position is found the value is inserted + nItems++; } - nItems++; } /** @@ -120,4 +124,4 @@ public static void main(String args[]){ //As you can see, a Priority Queue can be used as a sorting algotithm } -} \ No newline at end of file +} From 36d6b5133f288c60dbe0622ddbad08dde9efdf0b Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 17 Feb 2019 09:18:50 +0800 Subject: [PATCH 101/112] Update PriorityQueues.java --- DataStructures/Queues/PriorityQueues.java | 205 +++++++++++----------- 1 file changed, 103 insertions(+), 102 deletions(-) diff --git a/DataStructures/Queues/PriorityQueues.java b/DataStructures/Queues/PriorityQueues.java index 3eb74ecf518e..e709b13683a0 100644 --- a/DataStructures/Queues/PriorityQueues.java +++ b/DataStructures/Queues/PriorityQueues.java @@ -1,127 +1,128 @@ /** * This class implements a PriorityQueue. - * + *

* A priority queue adds elements into positions based on their priority. * So the most important elements are placed at the front/on the top. * In this example I give numbers that are bigger, a higher priority. * Queues in theory have no fixed size but when using an array * implementation it does. - * - * @author Unknown * */ -class PriorityQueue{ - /** The max size of the queue */ - private int maxSize; - /** The array for the queue */ - private int[] queueArray; - /** How many items are in the queue */ - private int nItems; +class PriorityQueue { + /** + * The max size of the queue + */ + private int maxSize; + /** + * The array for the queue + */ + private int[] queueArray; + /** + * How many items are in the queue + */ + private int nItems; - /** - * Constructor - * - * @param size Size of the queue - */ - public PriorityQueue(int size){ - maxSize = size; - queueArray = new int[size]; - nItems = 0; - } + /** + * Constructor + * + * @param size Size of the queue + */ + public PriorityQueue(int size) { + maxSize = size; + queueArray = new int[size]; + nItems = 0; + } - /** - * Inserts an element in it's appropriate place - * - * @param value Value to be inserted - */ - public void insert(int value){ - if(nItems == 0){ - queueArray[0] = value; - nItems++; - } - else if(isFull()){ //does not insert value when the queue is full - System.out.println("Queue is full"); - } - else{ - int j = nItems; - while(j > 0 && queueArray[j-1] > value){ - queueArray[j] = queueArray[j-1]; //Shifts every element up to make room for insertion - j--; - } - queueArray[j] = value; //Once the correct position is found the value is inserted - nItems++; - } - } + /** + * Inserts an element in it's appropriate place + * + * @param value Value to be inserted + */ + public void insert(int value) { + if (isFull()) { + throw new RuntimeException("Queue is full"); + } + if (nItems == 0) { + queueArray[0] = value; + } else { + int j = nItems; + while (j > 0 && queueArray[j - 1] > value) { + queueArray[j] = queueArray[j - 1]; // Shifts every element up to make room for insertion + j--; + } + queueArray[j] = value; // Once the correct position is found the value is inserted + } + nItems++; + } - /** - * Remove the element from the front of the queue - * - * @return The element removed - */ - public int remove(){ - return queueArray[--nItems]; - } + /** + * Remove the element from the front of the queue + * + * @return The element removed + */ + public int remove() { + return queueArray[--nItems]; + } - /** - * Checks what's at the front of the queue - * - * @return element at the front of the queue - */ - public int peek(){ - return queueArray[nItems-1]; - } + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peek() { + return queueArray[nItems - 1]; + } - /** - * Returns true if the queue is empty - * - * @return true if the queue is empty - */ - public boolean isEmpty(){ - return(nItems == 0); - } + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return (nItems == 0); + } - /** - * Returns true if the queue is full - * - * @return true if the queue is full - */ - public boolean isFull(){ - return(nItems == maxSize); - } + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull() { + return (nItems == maxSize); + } - /** - * Returns the number of elements in the queue - * - * @return number of elements in the queue - */ - public int getSize(){ - return nItems; - } + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize() { + return nItems; + } } /** * This class implements the PriorityQueue class above. - * - * @author Unknown * + * @author Unknown */ -public class PriorityQueues{ - /** - * Main method - * - * @param args Command Line Arguments - */ - public static void main(String args[]){ - PriorityQueue myQueue = new PriorityQueue(4); - myQueue.insert(10); - myQueue.insert(2); - myQueue.insert(5); - myQueue.insert(3); - //[2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top +public class PriorityQueues { + /** + * Main method + * + * @param args Command Line Arguments + */ + public static void main(String[] args) { + PriorityQueue myQueue = new PriorityQueue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + // [2, 3, 5, 10] Here higher numbers have higher priority, so they are on the top - for(int i = 3; i>=0; i--) - System.out.print(myQueue.remove() + " "); //will print the queue in reverse order [10, 5, 3, 2] + for (int i = 3; i >= 0; i--) + System.out.print(myQueue.remove() + " "); // will print the queue in reverse order [10, 5, 3, 2] - //As you can see, a Priority Queue can be used as a sorting algotithm - } + // As you can see, a Priority Queue can be used as a sorting algotithm + } } From c516834ed65a0e2cfb81bdf9f465511201438951 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Sun, 17 Feb 2019 20:52:00 +0800 Subject: [PATCH 102/112] docs(Others): update countwords.java and crc32.java - By @yanglbme --- Others/countwords.java | 36 ++++++++++++++++++------------------ Others/crc32.java | 24 +++++++++++++----------- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/Others/countwords.java b/Others/countwords.java index a93aa1a33833..da871047dd58 100644 --- a/Others/countwords.java +++ b/Others/countwords.java @@ -1,26 +1,26 @@ import java.util.Scanner; /** - * You enter a string into this program, and it will return how - * many words were in that particular string - * - * @author Marcus + * You enter a string into this program, and it will return how many words were + * in that particular string * + * @author Marcus */ - public class countwords{ +public class CountWords { - public static void main(String[] args){ - Scanner input = new Scanner(System.in); - System.out.println("Enter your text: "); - String str = input.nextLine(); - - System.out.println("Your text has " + wordCount(str) + " word(s)"); - input.close(); - } + public static void main(String[] args) { + Scanner input = new Scanner(System.in); + System.out.println("Enter your text: "); + String str = input.nextLine(); - private static int wordCount(String s){ - if(s.isEmpty() || s == null) return 0; - return s.trim().split("[\\s]+").length; - } - + System.out.println("Your text has " + wordCount(str) + " word(s)"); + input.close(); } + + private static int wordCount(String s) { + if (s == null || s.isEmpty()) + return 0; + return s.trim().split("[\\s]+").length; + } + +} diff --git a/Others/crc32.java b/Others/crc32.java index e27c247062d4..de98e4198c9b 100644 --- a/Others/crc32.java +++ b/Others/crc32.java @@ -1,27 +1,29 @@ import java.util.BitSet; -//Generates a crc32 checksum for a given string or byte array -public class crc32 { - +/** + * Generates a crc32 checksum for a given string or byte array + */ +public class CRC32 { + public static void main(String[] args) { System.out.println(Integer.toHexString(crc32("Hello World"))); } - + public static int crc32(String str) { return crc32(str.getBytes()); } - + public static int crc32(byte[] data) { BitSet bitSet = BitSet.valueOf(data); - int crc32 = 0xFFFFFFFF; //initial value - for(int i=0;i>>31)&1) != (bitSet.get(i)?1:0)) - crc32 = (crc32 << 1) ^ 0x04C11DB7; //xoring with polynomial + int crc32 = 0xFFFFFFFF; // initial value + for (int i = 0; i < data.length * 8; i++) { + if (((crc32 >>> 31) & 1) != (bitSet.get(i) ? 1 : 0)) + crc32 = (crc32 << 1) ^ 0x04C11DB7; // xor with polynomial else crc32 = (crc32 << 1); } - crc32 = Integer.reverse(crc32); //result reflect - return crc32 ^ 0xFFFFFFFF; //final xor value + crc32 = Integer.reverse(crc32); // result reflect + return crc32 ^ 0xFFFFFFFF; // final xor value } } From d434e4a4f1d3e69d29f0e1f45c7bb88f5de32ce9 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 17 Feb 2019 20:56:47 +0800 Subject: [PATCH 103/112] Update CRCAlgorithm.java --- Others/CRCAlgorithm.java | 135 +++++++++++++++++++-------------------- 1 file changed, 67 insertions(+), 68 deletions(-) diff --git a/Others/CRCAlgorithm.java b/Others/CRCAlgorithm.java index f932a9b74a73..d53e3a02c2e3 100644 --- a/Others/CRCAlgorithm.java +++ b/Others/CRCAlgorithm.java @@ -1,53 +1,53 @@ -package crcalgorithm; +package Others; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; /** - * * @author dimgrichr */ public class CRCAlgorithm { private int correctMess; - + private int wrongMess; - + private int wrongMessCaught; - + private int wrongMessNotCaught; - + private int messSize; - + private double ber; - + private boolean messageChanged; private ArrayList message; - + private ArrayList dividedMessage; - + private ArrayList p; - + private Random randomGenerator; - - + + /** * The algorithm's main constructor. * The most significant variables, used in the algorithm, * are set in their initial values. - * @param str The binary number P, in a string form, which is used by the CRC algorithm + * + * @param str The binary number P, in a string form, which is used by the CRC algorithm * @param size The size of every transmitted message - * @param ber The Bit Error Rate + * @param ber The Bit Error Rate */ - public CRCAlgorithm(String str, int size, double ber){ - messageChanged=false; + public CRCAlgorithm(String str, int size, double ber) { + messageChanged = false; message = new ArrayList<>(); messSize = size; dividedMessage = new ArrayList<>(); p = new ArrayList<>(); - for(int i=0;i(); dividedMessage = new ArrayList<>(); } - + /** * Random messages, consisted of 0's and 1's, * are generated, so that they can later be transmitted */ - public void generateRandomMess(){ - for(int i=0;i is created. * If check == true, the dividedMessaage is examined, in order to see if it contains any 1's. * If it does, the message is considered to be wrong by the receiver,so the variable wrongMessCaught changes. * If it does not, it is accepted, so one of the variables correctMess, wrongMessNotCaught, changes. - * If check == false, the diviided Message is added at the end of the ArrayList message. + * If check == false, the diviided Message is added at the end of the ArrayList message. + * * @param check the variable used to determine, if the message is going to be checked from the receiver - * if true, it is checked - * otherwise, it is not + * if true, it is checked + * otherwise, it is not */ - public void divideMessageWithP(boolean check){ + public void divideMessageWithP(boolean check) { ArrayList x = new ArrayList<>(); ArrayList k = (ArrayList) message.clone(); - if(!check){ - for(int i=0;i) x.clone(); - if(!check){ - for(int z:dividedMessage){ + if (!check) { + for (int z : dividedMessage) { message.add(z); } - } - else{ - if(dividedMessage.contains(1) && messageChanged){ + } else { + if (dividedMessage.contains(1) && messageChanged) { wrongMessCaught++; - } - else if(!dividedMessage.contains(1) && messageChanged){ + } else if (!dividedMessage.contains(1) && messageChanged) { wrongMessNotCaught++; - } - else if(!messageChanged){ + } else if (!messageChanged) { correctMess++; } } } - + /** * Once the message is transmitted, some of it's elements, * is possible to change from 1 to 0, or from 0 to 1, @@ -180,25 +181,23 @@ else if(!messageChanged){ * Based on these changes. the boolean variable messageChanged, gets the value: * true, or false. */ - public void changeMess(){ - for(int y : message){ + public void changeMess() { + for (int y : message) { double x = randomGenerator.nextDouble(); - while(x<0.0000 || x>1.00000){ + while (x < 0.0000 || x > 1.00000) { x = randomGenerator.nextDouble(); } - if(x Date: Sat, 23 Feb 2019 21:03:57 +0800 Subject: [PATCH 104/112] docs(DP): update LevenshteinDistance.java --- Dynamic Programming/LevenshteinDistance.java | 97 ++++++++++---------- 1 file changed, 48 insertions(+), 49 deletions(-) diff --git a/Dynamic Programming/LevenshteinDistance.java b/Dynamic Programming/LevenshteinDistance.java index be0e7c43f112..a196c0fe5139 100644 --- a/Dynamic Programming/LevenshteinDistance.java +++ b/Dynamic Programming/LevenshteinDistance.java @@ -1,55 +1,54 @@ /** - * * @author Kshitij VERMA (github.com/kv19971) * LEVENSHTEIN DISTANCE dyamic programming implementation to show the difference between two strings (https://en.wikipedia.org/wiki/Levenshtein_distance) - * - * */ -public class LevenshteinDistance{ - private static int minimum(int a, int b, int c){ - if(a < b && a < c){ - return a; - }else if(b < a && b < c){ - return b; - }else{ - return c; - } - } - private static int calculate_distance(String a, String b){ - int len_a = a.length() + 1; - int len_b = b.length() + 1; - int [][] distance_mat = new int[len_a][len_b]; - for(int i = 0; i < len_a; i++){ - distance_mat[i][0] = i; - } - for(int j = 0; j < len_b; j++){ - distance_mat[0][j] = j; - } - for(int i = 0; i < len_a; i++){ - for(int j = 0; i < len_b; j++){ - int cost; - if (a.charAt(i) == b.charAt(j)){ - cost = 0; - }else{ - cost = 1; - } - distance_mat[i][j] = minimum(distance_mat[i-1][j], distance_mat[i-1][j-1], distance_mat[i][j-1]) + cost; - - - } - - } - return distance_mat[len_a-1][len_b-1]; - - } - public static void main(String [] args){ - String a = ""; // enter your string here - String b = ""; // enter your string here - - System.out.print("Levenshtein distance between "+a + " and "+b+ " is: "); - System.out.println(calculate_distance(a,b)); - - - } +public class LevenshteinDistance { + private static int minimum(int a, int b, int c) { + if (a < b && a < c) { + return a; + } else if (b < a && b < c) { + return b; + } else { + return c; + } + } + + private static int calculate_distance(String a, String b) { + int len_a = a.length() + 1; + int len_b = b.length() + 1; + int[][] distance_mat = new int[len_a][len_b]; + for (int i = 0; i < len_a; i++) { + distance_mat[i][0] = i; + } + for (int j = 0; j < len_b; j++) { + distance_mat[0][j] = j; + } + for (int i = 0; i < len_a; i++) { + for (int j = 0; i < len_b; j++) { + int cost; + if (a.charAt(i) == b.charAt(j)) { + cost = 0; + } else { + cost = 1; + } + distance_mat[i][j] = minimum(distance_mat[i - 1][j], distance_mat[i - 1][j - 1], distance_mat[i][j - 1]) + cost; + + + } + + } + return distance_mat[len_a - 1][len_b - 1]; + + } + + public static void main(String[] args) { + String a = ""; // enter your string here + String b = ""; // enter your string here + + System.out.print("Levenshtein distance between " + a + " and " + b + " is: "); + System.out.println(calculate_distance(a, b)); + + + } } From 6ff87322e63e167cf62dc1bb94eb426c27a52649 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sat, 23 Feb 2019 21:06:32 +0800 Subject: [PATCH 105/112] docs(DP): update EggDropping.java --- Dynamic Programming/EggDropping.java | 98 +++++++++++++--------------- 1 file changed, 46 insertions(+), 52 deletions(-) diff --git a/Dynamic Programming/EggDropping.java b/Dynamic Programming/EggDropping.java index 382d7ea86c2c..0549f6647ad2 100644 --- a/Dynamic Programming/EggDropping.java +++ b/Dynamic Programming/EggDropping.java @@ -1,53 +1,47 @@ -//Dynamic Programming solution for the Egg Dropping Puzzle -public class EggDropping -{ - - // min trials with n eggs and m floors - - private static int minTrials(int n, int m) - { - - int eggFloor[][] = new int[n+1][m+1]; - int result, x; - - for (int i = 1; i <= n; i++) - { - eggFloor[i][0] = 0; // Zero trial for zero floor. - eggFloor[i][1] = 1; // One trial for one floor - } - - // j trials for only 1 egg - - for (int j = 1; j <= m; j++) - eggFloor[1][j] = j; - - // Using bottom-up approach in DP - - for (int i = 2; i <= n; i++) - { - for (int j = 2; j <= m; j++) - { - eggFloor[i][j] = Integer.MAX_VALUE; - for (x = 1; x <= j; x++) - { - result = 1 + Math.max(eggFloor[i-1][x-1], eggFloor[i][j-x]); - - //choose min of all values for particular x - if (result < eggFloor[i][j]) - eggFloor[i][j] = result; - } - } - } - - return eggFloor[n][m]; - } - - //testing program - public static void main(String args[]) - { - int n = 2, m = 4; - //result outputs min no. of trials in worst case for n eggs and m floors - int result = minTrials(n, m); - System.out.println(result); - } +/** + * Dynamic Programming solution for the Egg Dropping Puzzle + */ +public class EggDropping { + + // min trials with n eggs and m floors + + private static int minTrials(int n, int m) { + + int[][] eggFloor = new int[n + 1][m + 1]; + int result, x; + + for (int i = 1; i <= n; i++) { + eggFloor[i][0] = 0; // Zero trial for zero floor. + eggFloor[i][1] = 1; // One trial for one floor + } + + // j trials for only 1 egg + + for (int j = 1; j <= m; j++) + eggFloor[1][j] = j; + + // Using bottom-up approach in DP + + for (int i = 2; i <= n; i++) { + for (int j = 2; j <= m; j++) { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) { + result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); + + // choose min of all values for particular x + if (result < eggFloor[i][j]) + eggFloor[i][j] = result; + } + } + } + + return eggFloor[n][m]; + } + + public static void main(String args[]) { + int n = 2, m = 4; + // result outputs min no. of trials in worst case for n eggs and m floors + int result = minTrials(n, m); + System.out.println(result); + } } From 5ec25c167057a355f3073cfd52ca3f6d1ce2eef8 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sat, 23 Feb 2019 21:12:08 +0800 Subject: [PATCH 106/112] docs(DP): update RodCutting.java --- Dynamic Programming/RodCutting.java | 53 ++++++++++++++--------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/Dynamic Programming/RodCutting.java b/Dynamic Programming/RodCutting.java index cd2512059ae2..5ee38e0ced33 100644 --- a/Dynamic Programming/RodCutting.java +++ b/Dynamic Programming/RodCutting.java @@ -1,32 +1,31 @@ -/* A Dynamic Programming solution for Rod cutting problem - Returns the best obtainable price for a rod of - length n and price[] as prices of different pieces */ - +/** + * A Dynamic Programming solution for Rod cutting problem + * Returns the best obtainable price for a rod of + * length n and price[] as prices of different pieces + * + */ public class RodCutting { - - private static int cutRod(int price[],int n) - { - int val[] = new int[n+1]; - val[0] = 0; - for (int i = 1; i<=n; i++) - { - int max_val = Integer.MIN_VALUE; - for (int j = 0; j < i; j++) - max_val = Math.max(max_val,price[j] + val[i-j-1]); - - val[i] = max_val; - } + private static int cutRod(int[] price, int n) { + int val[] = new int[n + 1]; + val[0] = 0; + + for (int i = 1; i <= n; i++) { + int max_val = Integer.MIN_VALUE; + for (int j = 0; j < i; j++) + max_val = Math.max(max_val, price[j] + val[i - j - 1]); + + val[i] = max_val; + } - return val[n]; - } + return val[n]; + } - //main function to test - public static void main(String args[]) - { - int arr[] = new int[] {2, 5, 13, 19, 20}; - int size = arr.length; - System.out.println("Maximum Obtainable Value is " + - cutRod(arr, size)); - } + // main function to test + public static void main(String args[]) { + int[] arr = new int[]{2, 5, 13, 19, 20}; + int size = arr.length; + System.out.println("Maximum Obtainable Value is " + + cutRod(arr, size)); + } } From c725d91ecf0b4b6d62c0d054f52abb87901a3e68 Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sun, 24 Feb 2019 08:46:51 +0800 Subject: [PATCH 107/112] docs(DP): update LongestValidParentheses.java --- .../LongestValidParentheses.java | 96 +++++++++---------- 1 file changed, 46 insertions(+), 50 deletions(-) diff --git a/Dynamic Programming/LongestValidParentheses.java b/Dynamic Programming/LongestValidParentheses.java index 14c98020a126..1a42b258d144 100644 --- a/Dynamic Programming/LongestValidParentheses.java +++ b/Dynamic Programming/LongestValidParentheses.java @@ -1,63 +1,59 @@ - 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(); - - } - + 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 2b3e82fd4c76a5b9475521154f65baa86e24250c Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Mon, 25 Feb 2019 09:33:06 +0800 Subject: [PATCH 108/112] Update Queues.java --- DataStructures/Queues/Queues.java | 278 +++++++++++++++--------------- 1 file changed, 143 insertions(+), 135 deletions(-) diff --git a/DataStructures/Queues/Queues.java b/DataStructures/Queues/Queues.java index 84638cb24751..cd66d5af0118 100644 --- a/DataStructures/Queues/Queues.java +++ b/DataStructures/Queues/Queues.java @@ -1,148 +1,156 @@ /** * This implements Queues by using the class Queue. - * + *

* A queue data structure functions the same as a real world queue. * The elements that are added first are the first to be removed. * New elements are added to the back/rear of the queue. - * - * @author Unknown * + * @author Unknown */ -class Queue{ - /** Max size of the queue */ - private int maxSize; - /** The array representing the queue */ - private int[] queueArray; - /** Front of the queue */ - private int front; - /** Rear of the queue */ - private int rear; - /** How many items are in the queue */ - private int nItems; - - /** - * Constructor - * - * @param size Size of the new queue - */ - public Queue(int size){ - maxSize = size; - queueArray = new int[size]; - front = 0; - rear = -1; - nItems = 0; - } - - /** - * Inserts an element at the rear of the queue - * - * @param x element to be added - * @return True if the element was added successfully - */ - public boolean insert(int x){ - if(isFull()) - return false; - if(rear == maxSize-1) //If the back of the queue is the end of the array wrap around to the front - rear = -1; - rear++; - queueArray[rear] = x; - nItems++; - return true; - } - - /** - * Remove an element from the front of the queue - * - * @return the new front of the queue - */ - public int remove(){ //Remove an element from the front of the queue - if(isEmpty()){ - System.out.println("Queue is empty"); - return -1; - } - int temp = queueArray[front]; - front++; - if(front == maxSize) //Dealing with wrap-around again - front = 0; - nItems--; - return temp; - } - - /** - * Checks what's at the front of the queue - * - * @return element at the front of the queue - */ - public int peekFront(){ - return queueArray[front]; - } - - /** - * Checks what's at the rear of the queue - * - * @return element at the rear of the queue - */ - public int peekRear(){ - return queueArray[rear]; - } - - /** - * Returns true if the queue is empty - * - * @return true if the queue is empty - */ - public boolean isEmpty(){ - return(nItems == 0); - } - - /** - * Returns true if the queue is full - * - * @return true if the queue is full - */ - public boolean isFull(){ - return(nItems == maxSize); - } - - /** - * Returns the number of elements in the queue - * - * @return number of elements in the queue - */ - public int getSize(){ - return nItems; - } +class Queue { + /** + * Max size of the queue + */ + private int maxSize; + /** + * The array representing the queue + */ + private int[] queueArray; + /** + * Front of the queue + */ + private int front; + /** + * Rear of the queue + */ + private int rear; + /** + * How many items are in the queue + */ + private int nItems; + + /** + * Constructor + * + * @param size Size of the new queue + */ + public Queue(int size) { + maxSize = size; + queueArray = new int[size]; + front = 0; + rear = -1; + nItems = 0; + } + + /** + * Inserts an element at the rear of the queue + * + * @param x element to be added + * @return True if the element was added successfully + */ + public boolean insert(int x) { + if (isFull()) + return false; + if (rear == maxSize - 1) // If the back of the queue is the end of the array wrap around to the front + rear = -1; + rear++; + queueArray[rear] = x; + nItems++; + return true; + } + + /** + * Remove an element from the front of the queue + * + * @return the new front of the queue + */ + public int remove() { // Remove an element from the front of the queue + if (isEmpty()) { + System.out.println("Queue is empty"); + return -1; + } + int temp = queueArray[front]; + front++; + if (front == maxSize) //Dealing with wrap-around again + front = 0; + nItems--; + return temp; + } + + /** + * Checks what's at the front of the queue + * + * @return element at the front of the queue + */ + public int peekFront() { + return queueArray[front]; + } + + /** + * Checks what's at the rear of the queue + * + * @return element at the rear of the queue + */ + public int peekRear() { + return queueArray[rear]; + } + + /** + * Returns true if the queue is empty + * + * @return true if the queue is empty + */ + public boolean isEmpty() { + return (nItems == 0); + } + + /** + * Returns true if the queue is full + * + * @return true if the queue is full + */ + public boolean isFull() { + return (nItems == maxSize); + } + + /** + * Returns the number of elements in the queue + * + * @return number of elements in the queue + */ + public int getSize() { + return nItems; + } } /** * This class is the example for the Queue class - * - * @author Unknown * + * @author Unknown */ -public class Queues{ - /** - * Main method - * - * @param args Command line arguments - */ - public static void main(String args[]){ - Queue myQueue = new Queue(4); - myQueue.insert(10); - myQueue.insert(2); - myQueue.insert(5); - myQueue.insert(3); - //[10(front), 2, 5, 3(rear)] - - System.out.println(myQueue.isFull()); //Will print true - - myQueue.remove(); //Will make 2 the new front, making 10 no longer part of the queue - //[10, 2(front), 5, 3(rear)] - - myQueue.insert(7); //Insert 7 at the rear which will be index 0 because of wrap around - // [7(rear), 2(front), 5, 3] - - System.out.println(myQueue.peekFront()); //Will print 2 - System.out.println(myQueue.peekRear()); //Will print 7 - } -} \ No newline at end of file +public class Queues { + /** + * Main method + * + * @param args Command line arguments + */ + public static void main(String args[]) { + Queue myQueue = new Queue(4); + myQueue.insert(10); + myQueue.insert(2); + myQueue.insert(5); + myQueue.insert(3); + // [10(front), 2, 5, 3(rear)] + + System.out.println(myQueue.isFull()); // Will print true + + myQueue.remove(); // Will make 2 the new front, making 10 no longer part of the queue + // [10, 2(front), 5, 3(rear)] + + myQueue.insert(7); // Insert 7 at the rear which will be index 0 because of wrap around + // [7(rear), 2(front), 5, 3] + + System.out.println(myQueue.peekFront()); // Will print 2 + System.out.println(myQueue.peekRear()); // Will print 7 + } +} From 1031cfb35c593eb84166dbb0ec557fef6e0e4025 Mon Sep 17 00:00:00 2001 From: Heiko Alexander Weber Date: Tue, 26 Feb 2019 23:10:20 +0100 Subject: [PATCH 109/112] #708 (bugfix for fibonacci sequence function) o fixed function "fibMemo" according to acceptance criteria in #708 o fixed function "fibBotUp" according to acceptance criteria in #708 --- Dynamic Programming/Fibonacci.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index 8f9326ba9d94..2f65a8e9e0de 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -17,8 +17,9 @@ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); - System.out.println(fibMemo(n)); // Returns 8 for n = 6 - System.out.println(fibBotUp(n)); // Returns 8 for n = 6 + // Methods all returning [0, 1, 1, 2, 3, 5, ...] for n = [0, 1, 2, 3, 4, 5, ...] + System.out.println(fibMemo(n)); + System.out.println(fibBotUp(n)); } /** @@ -34,13 +35,12 @@ private static int fibMemo(int n) { int f; - if (n <= 2) { - f = 1; + if (n <= 1) { + f = n; } else { f = fibMemo(n - 1) + fibMemo(n - 2); map.put(n, f); } - return f; } @@ -54,10 +54,10 @@ private static int fibBotUp(int n) { Map fib = new HashMap<>(); - for (int i = 1; i < n + 1; i++) { + for (int i = 0; i <= n; i++) { int f; - if (i <= 2) { - f = 1; + if (i <= 1) { + f = i; } else { f = fib.get(i - 1) + fib.get(i - 2); } From d60f836861fb1d1237935a9c342ef492d0df8cc4 Mon Sep 17 00:00:00 2001 From: Ojas Saxena <43749506+ojasiiitd@users.noreply.github.com> Date: Mon, 4 Mar 2019 15:05:15 +0530 Subject: [PATCH 110/112] Updated StackOfLinkedList.java I made the code shorter and less prone to mistakes by removing the "size" variable altogether from the LinkedList class. I found that after each push/pop operation, changing the value of size did make the code more efficient, but made it more prone to mistakes. So, for empty stack, a simple "head == null" was enough, which has been incorporated. --- DataStructures/Stacks/StackOfLinkedList.java | 37 +++++++++++--------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java index 35052457fe1c..7b744bcb85af 100644 --- a/DataStructures/Stacks/StackOfLinkedList.java +++ b/DataStructures/Stacks/StackOfLinkedList.java @@ -25,9 +25,7 @@ public static void main(String[] args) { stack.pop(); System.out.println("Top element of stack currently is: " + stack.peek()); - } - } // A node class @@ -51,11 +49,10 @@ public Node(int data) { class LinkedListStack { Node head = null; - int size = 0; public void push(int x) { Node n = new Node(x); - if (getSize() == 0) { + if (head == null) { head = n; } else { @@ -63,47 +60,55 @@ public void push(int x) { n.next = temp; head = n; } - size++; } public void pop() { - if (getSize() == 0) { + if (head == null) { System.out.println("Empty stack. Nothing to pop"); } Node temp = head; head = head.next; - size--; - System.out.println("Popped element is: " + temp.data); } public int peek() { - if (getSize() == 0) { + if (head == null) { return -1; } - return head.data; } public void printStack() { - Node temp = head; System.out.println("Stack is printed as below: "); while (temp != null) { - System.out.println(temp.data + " "); + if(temp.next == null) { + System.out.print(temp.data); + } + else { + System.out.print(temp.data + " -> "); + } temp = temp.next; } System.out.println(); - } public boolean isEmpty() { - return getSize() == 0; + return head == null; } public int getSize() { - return size; + if(head == null) + return 0; + else { + int size = 1; + Node temp = head; + while(temp.next != null) { + temp = temp.next; + size++; + } + return size; + } } - } From 2ea534000bafe95a5c03dd6248aeda1d1ff151a7 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Tue, 5 Mar 2019 10:18:20 +0800 Subject: [PATCH 111/112] Update StackOfLinkedList.java --- DataStructures/Stacks/StackOfLinkedList.java | 24 ++++++++------------ 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java index 7b744bcb85af..d9f737040271 100644 --- a/DataStructures/Stacks/StackOfLinkedList.java +++ b/DataStructures/Stacks/StackOfLinkedList.java @@ -1,7 +1,5 @@ /** - * * @author Varun Upadhyay (https://github.com/varunu28) - * */ // An implementation of a Stack using a Linked List @@ -42,7 +40,7 @@ public Node(int data) { /** * A class which implements a stack using a linked list - * + *

* Contains all the stack methods : push, pop, printStack, isEmpty **/ @@ -54,8 +52,7 @@ public void push(int x) { Node n = new Node(x); if (head == null) { head = n; - } - else { + } else { Node temp = head; n.next = temp; head = n; @@ -73,20 +70,19 @@ public void pop() { } public int peek() { - if (head == null) { - return -1; - } - return head.data; + if (head == null) { + return -1; + } + return head.data; } public void printStack() { Node temp = head; System.out.println("Stack is printed as below: "); while (temp != null) { - if(temp.next == null) { + if (temp.next == null) { System.out.print(temp.data); - } - else { + } else { System.out.print(temp.data + " -> "); } temp = temp.next; @@ -99,12 +95,12 @@ public boolean isEmpty() { } public int getSize() { - if(head == null) + if (head == null) return 0; else { int size = 1; Node temp = head; - while(temp.next != null) { + while (temp.next != null) { temp = temp.next; size++; } From 6c4fd0efb0558a58da47b23df35bc8ed0b874ec1 Mon Sep 17 00:00:00 2001 From: Ojas Saxena <43749506+ojasiiitd@users.noreply.github.com> Date: Wed, 6 Mar 2019 15:35:04 +0530 Subject: [PATCH 112/112] Major Updates in SinglyLinkedList.java - The "count" variable made the code more prone to errors, so I removed and replaced it with another "getSize()" function. - The value of "next" was initialized to null. - Major improvements of code were given to "insertNth()" and "deleteHead()" functions for efficiency. - A new function "deleteNth()" was defined, increasing the usefulness of the program. --- DataStructures/Lists/SinglyLinkedList.java | 75 ++++++++++++++++------ 1 file changed, 54 insertions(+), 21 deletions(-) diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java index 1d61e31b2ad0..c9d2413a8375 100644 --- a/DataStructures/Lists/SinglyLinkedList.java +++ b/DataStructures/Lists/SinglyLinkedList.java @@ -17,11 +17,6 @@ class SinglyLinkedList { */ private Node head; - /** - * Count of nodes - */ - private int count; - /** * This method inserts an element at the head * @@ -31,7 +26,6 @@ public void insertHead(int x) { Node newNode = new Node(x); newNode.next = head; head = newNode; - ++count; } /** @@ -42,19 +36,20 @@ public void insertHead(int x) { */ public void insertNth(int data, int position) { - if (position < 0 || position > count) { + if (position < 0 || position > getSize()) { throw new RuntimeException("position less than zero or position more than the count of list"); } - Node node = new Node(data); - Node dummy = new Node(-1); - dummy.next = head; - Node cur = dummy; - for (int i = 0; i < position; ++i) { - cur = cur.next; + else if (position == 0) + insertHead(data); + else { + Node cur = head; + Node node = new Node(data); + for (int i = 1; i < position; ++i) { + cur = cur.next; + } + node.next = cur.next; + cur.next = node; } - node.next = cur.next; - cur.next = node; - ++count; } /** @@ -62,15 +57,30 @@ public void insertNth(int data, int position) { * * @return The element deleted */ - public Node deleteHead() { + public void deleteHead() { if (isEmpty()) { throw new RuntimeException("The list is empty!"); } - Node temp = head; head = head.next; - --count; - return temp; + } + + /** + * This method deletes an element at Nth position + */ + public void deleteNth(int position) { + if (position < 0 || position > getSize()) { + throw new RuntimeException("position less than zero or position more than the count of list"); + } + else if (position == 0) + deleteHead(); + else { + Node cur = head; + for (int i = 1; i < position; ++i) { + cur = cur.next; + } + cur.next = cur.next.next; + } } /** @@ -79,7 +89,7 @@ public Node deleteHead() { * @return true is list is empty */ public boolean isEmpty() { - return count == 0; + return getSize() == 0; } /** @@ -94,6 +104,23 @@ public void display() { System.out.println(); } + /** + * Returns the size of the linked list + */ + public int getSize() { + if (head == null) + return 0; + else { + Node current = head; + int size = 1; + while (current.next != null) { + current = current.next; + size++; + } + return size; + } + } + /** * Main method * @@ -117,6 +144,11 @@ public static void main(String args[]) { myList.insertNth(11, 2); myList.display(); // 7 -> 5 -> 11 + + myList.deleteNth(1); + + myList.display(); // 7-> 11 + } } @@ -145,5 +177,6 @@ class Node { */ Node(int value) { this.value = value; + this.next = null; } }