diff --git a/Conversions/AnyBaseToAnyBase.java b/Conversions/AnyBaseToAnyBase.java new file mode 100644 index 00000000..33c77975 --- /dev/null +++ b/Conversions/AnyBaseToAnyBase.java @@ -0,0 +1,130 @@ +import java.util.Arrays; +import java.util.HashSet; +import java.util.InputMismatchException; +import java.util.Scanner; + +/** + * Class for converting from "any" base to "any" other base, when "any" means from 2-36. + * Works by going from base 1 to decimal to base 2. Includes auxiliary method for + * determining whether a number is valid for a given base. + * + * @author Michael Rolland + * @version 2017.10.10 + * + */ +public class AnyBaseToAnyBase { + + // Smallest and largest base you want to accept as valid input + static final int MINIMUM_BASE = 2; + static final int MAXIMUM_BASE = 36; + + // Driver + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String n; + int b1=0,b2=0; + while (true) { + try { + System.out.print("Enter number: "); + n = in.next(); + System.out.print("Enter beginning base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): "); + b1 = in.nextInt(); + if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) { + System.out.println("Invalid base!"); + continue; + } + if (!validForBase(n, b1)) { + System.out.println("The number is invalid for this base!"); + continue; + } + System.out.print("Enter end base (between "+MINIMUM_BASE+" and "+MAXIMUM_BASE+"): "); + b2 = in.nextInt(); + if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) { + System.out.println("Invalid base!"); + continue; + } + break; + } catch (InputMismatchException e) { + System.out.println("Invalid input."); + in.next(); + } + } + System.out.println(base2base(n, b1, b2)); + } + + /** + * Checks if a number (as a String) is valid for a given base. + */ + public static boolean validForBase(String n, int base) { + char[] validDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', + 'W', 'X', 'Y', 'Z'}; + // digitsForBase contains all the valid digits for the base given + char[] digitsForBase = Arrays.copyOfRange(validDigits, 0, base); + + // Convert character array into set for convenience of contains() method + HashSet digitsList = new HashSet(); + for (int i=0; i9 and store it in charB2 + if (charB1 >= 'A' && charB1 <= 'Z') + charB2 = 10 + (charB1 - 'A'); + // Else, store the integer value in charB2 + else + charB2 = charB1 - '0'; + // Convert the digit to decimal and add it to the + // decimalValue of n + decimalValue = decimalValue * b1 + charB2; + } + + // Converting the decimal value to base b2: + // A number is converted from decimal to another base + // by continuously dividing by the base and recording + // the remainder until the quotient is zero. The number in the + // new base is the remainders, with the last remainder + // being the left-most digit. + + // While the quotient is NOT zero: + while (decimalValue != 0) { + // If the remainder is a digit < 10, simply add it to + // the left side of the new number. + if (decimalValue % b2 < 10) + output = Integer.toString(decimalValue % b2) + output; + // If the remainder is >= 10, add a character with the + // corresponding value to the new number. (A = 10, B = 11, C = 12, ...) + else + output = (char)((decimalValue % b2)+55) + output; + // Divide by the new base again + decimalValue /= b2; + } + return output; + } +} diff --git a/Data Structures/HashMap/HashMap.java b/Data Structures/HashMap/HashMap.java index 2c44a3e5..1cce6260 100644 --- a/Data Structures/HashMap/HashMap.java +++ b/Data Structures/HashMap/HashMap.java @@ -1,3 +1,4 @@ +<<<<<<< HEAD:Data Structures/HashMap/HashMap.java import java.util.ArrayList; @@ -139,3 +140,144 @@ public class HashMap { } } +======= +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>>>>>> 7e3a8c55c865471a33f6932a022a1059c5243fc3:data_structures/HashMap/HashMap.java diff --git a/Data Structures/Lists/CircleLinkedList.java b/Data Structures/Lists/CircleLinkedList.java index cf03cd7c..1f9a49e1 100644 --- a/Data Structures/Lists/CircleLinkedList.java +++ b/Data Structures/Lists/CircleLinkedList.java @@ -7,32 +7,44 @@ public class CircleLinkedList{ this.next = next; } } - private int size; //For better O.O design this should be private allows for better black box design - private Node head; //this will point to dummy node; - public CircleLinkedList(){ //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; - head = new Node(null,head); //creation of the dummy node + //For better O.O design this should be private allows for better black box design + private int size; + //this will point to dummy node; + private Node head; + //constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty; + public CircleLinkedList(){ + //creation of the dummy node + head = new Node(null,head); size = 0; } - public int getSize(){ return size;} // getter for the size... needed because size is private. - public void append(E value){ // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really. + // getter for the size... needed because size is private. + public int getSize(){ return size;} + // for the sake of simplistiy this class will only contain the append function or addLast other add functions can be implemented however this is the basses of them all really. + public void append(E value){ if(value == null){ - throw new NullPointerException("Cannot add null element to the list"); // we do not want to add null elements to the list. + // we do not want to add null elements to the list. + throw new NullPointerException("Cannot add null element to the list"); } - head.next = new Node(value,head); //head.next points to the last element; + //head.next points to the last element; + head.next = new Node(value,head); size++;} public E remove(int pos){ if(pos>size || pos< 0){ - throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); //catching errors + //catching errors + throw new IndexOutOfBoundsException("position cannot be greater than size or negative"); } Node iterator = head.next; - Node before = head; //we need to keep track of the element before the element we want to remove we can see why bellow. + //we need to keep track of the element before the element we want to remove we can see why bellow. + Node before = head; for(int i = 1; i<=pos; i++){ iterator = iterator.next; before = before.next; } E saved = iterator.value; - before.next = iterator.next; // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head. - iterator.next = null; // scrubbing + // assigning the next referance to the the element following the element we want to remove... the last element will be assigned to the head. + before.next = iterator.next; + // scrubbing + iterator.next = null; iterator.value = null; return saved; diff --git a/Data Structures/Stacks/Stacks.java b/Data Structures/Stacks/Stacks.java index 21585631..95469b91 100644 --- a/Data Structures/Stacks/Stacks.java +++ b/Data Structures/Stacks/Stacks.java @@ -42,7 +42,7 @@ class Stack{ top++; stackArray[top] = value; }else{ - System.out.println("The stack is full, can't insert value"); + resize(maxSize*2); } } @@ -54,7 +54,12 @@ class Stack{ public int pop(){ if(!isEmpty()){ //Checks for an empty stack return stackArray[top--]; - }else{ + } + + if(top < maxSize/4){ + resize(maxSize/2); + } + else{ System.out.println("The stack is already empty"); return -1; } @@ -74,6 +79,16 @@ class Stack{ } } + private void resize(int newSize){ + private int[] transferArray = new int[newSize]; + + for(int i = 0; i < stackArray.length(); i++){ + transferArray[i] = stackArray[i]; + stackArray = transferArray; + } + maxSize = newSize; + } + /** * Returns true if the stack is empty * diff --git a/Data Structures/Trees/TreeTraversal.java b/Data Structures/Trees/TreeTraversal.java index c4ff92d0..bd0f2f7f 100644 --- a/Data Structures/Trees/TreeTraversal.java +++ b/Data Structures/Trees/TreeTraversal.java @@ -1,37 +1,50 @@ +import java.util.LinkedList; + /** - * - * @author Varun Upadhyay (https://github.com/varunu28) - * - */ +* +* @author Varun Upadhyay (https://github.com/varunu28) +* +*/ + // Driver Program public class TreeTraversal { public static void main(String[] args) { Node tree = new Node(5); tree.insert(3); + tree.insert(2); tree.insert(7); + tree.insert(4); + tree.insert(6); + tree.insert(8); - // Prints 3 5 7 - tree.printInOrder(); - System.out.println(); - - // Prints 5 3 7 + // Prints 5 3 2 4 7 6 8 + System.out.println("Pre order traversal:"); tree.printPreOrder(); System.out.println(); - - // Prints 3 7 5 + // Prints 2 3 4 5 6 7 8 + System.out.println("In order traversal:"); + tree.printInOrder(); + System.out.println(); + // Prints 2 4 3 6 8 7 5 + System.out.println("Post order traversal:"); tree.printPostOrder(); System.out.println(); + // Prints 5 3 7 2 4 6 8 + System.out.println("Level order traversal:"); + tree.printLevelOrder(); + System.out.println(); } } /** - * The Node class which initializes a Node of a tree - * Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder - * printInOrder: LEFT -> ROOT -> RIGHT - * printPreOrder: ROOT -> LEFT -> RIGHT - * printPostOrder: LEFT -> RIGHT -> ROOT - */ +* The Node class which initializes a Node of a tree +* Consists of all 3 traversal methods: printInOrder, printPostOrder & printPreOrder +* printInOrder: LEFT -> ROOT -> RIGHT +* printPreOrder: ROOT -> LEFT -> RIGHT +* printPostOrder: LEFT -> RIGHT -> ROOT +* printLevelOrder: Prints by level (starting at root), from left to right. +*/ class Node { Node left, right; int data; @@ -88,5 +101,24 @@ class Node { } System.out.print(data + " "); } -} + /** + * O(n) time algorithm. + * Uses O(n) space to store nodes in a queue to aid in traversal. + */ + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while (queue.size() > 0) { + Node head = queue.remove(); + System.out.print(head.data + " "); + // Add children of recently-printed node to queue, if they exist. + if (head.left != null) { + queue.add(head.left); + } + if (head.right != null) { + queue.add(head.right); + } + } + } +} diff --git a/Dynamic Programming/EggDropping.java b/Dynamic Programming/EggDropping.java new file mode 100644 index 00000000..382d7ea8 --- /dev/null +++ b/Dynamic Programming/EggDropping.java @@ -0,0 +1,53 @@ +//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); + } +} diff --git a/Dynamic Programming/Fibonacci.java b/Dynamic Programming/Fibonacci.java index 17c11d8d..b2524b4d 100644 --- a/Dynamic Programming/Fibonacci.java +++ b/Dynamic Programming/Fibonacci.java @@ -11,7 +11,7 @@ import java.util.Map; public class Fibonacci { - public static Map map = new HashMap(); + private static Map map = new HashMap(); public static void main(String[] args) throws Exception { @@ -29,7 +29,7 @@ public class Fibonacci { * Outputs the nth fibonacci number **/ - public static int fibMemo(int n) { + private static int fibMemo(int n) { if (map.containsKey(n)) { return map.get(n); } @@ -54,7 +54,7 @@ public class Fibonacci { * Outputs the nth fibonacci number **/ - public static int fibBotUp(int n) { + private static int fibBotUp(int n) { Map fib = new HashMap(); diff --git a/Dynamic Programming/LevenshteinDistance.java b/Dynamic Programming/LevenshteinDistance.java index 5bff389f..8a5f7249 100644 --- a/Dynamic Programming/LevenshteinDistance.java +++ b/Dynamic Programming/LevenshteinDistance.java @@ -7,7 +7,7 @@ */ public class Levenshtein_distance{ - private int minimum(int a, int b, int c){ + private static int minimum(int a, int b, int c){ if(a < b && a < c){ return a; }else if(b < a && b < c){ @@ -16,9 +16,9 @@ public class Levenshtein_distance{ return c; } } - public int calculate_distance(String a, String b){ - len_a = a.length() + 1; - len_b = b.length() + 1; + 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; diff --git a/Dynamic Programming/LongestCommonSubsequence.java b/Dynamic Programming/LongestCommonSubsequence.java new file mode 100644 index 00000000..9e828056 --- /dev/null +++ b/Dynamic Programming/LongestCommonSubsequence.java @@ -0,0 +1,66 @@ +class LongestCommonSubsequence { + + public static String getLCS(String str1, String str2) { + + //At least one string is null + if(str1 == null || str2 == null) + return null; + + //At least one string is empty + if(str1.length() == 0 || str2.length() == 0) + return ""; + + String[] arr1 = str1.split(""); + String[] arr2 = str2.split(""); + + //lcsMatrix[i][j] = LCS of first i elements of arr1 and first j characters of arr2 + int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; + + for(int i = 0; i < arr1.length + 1; i++) + lcsMatrix[i][0] = 0; + for(int j = 1; j < arr2.length + 1; j++) + lcsMatrix[0][j] = 0; + for(int i = 1; i < arr1.length + 1; i++) { + for(int j = 1; j < arr2.length + 1; j++) { + if(arr1[i-1].equals(arr2[j-1])) { + lcsMatrix[i][j] = lcsMatrix[i-1][j-1] + 1; + } else { + lcsMatrix[i][j] = lcsMatrix[i-1][j] > lcsMatrix[i][j-1] ? lcsMatrix[i-1][j] : lcsMatrix[i][j-1]; + } + } + } + return lcsString(str1, str2, lcsMatrix); + } + + public static String lcsString (String str1, String str2, int[][] lcsMatrix) { + StringBuilder lcs = new StringBuilder(); + int i = str1.length(), + j = str2.length(); + while(i > 0 && j > 0) { + if(str1.charAt(i-1) == str2.charAt(j-1)) { + lcs.append(str1.charAt(i-1)); + i--; + j--; + } else if(lcsMatrix[i-1][j] > lcsMatrix[i][j-1]) { + i--; + } else { + j--; + } + } + return lcs.reverse().toString(); + } + + public static void main(String[] args) { + String str1 = "DSGSHSRGSRHTRD"; + String str2 = "DATRGAGTSHS"; + String lcs = getLCS(str1, str2); + + //Print LCS + if(lcs != null) { + System.out.println("String 1: " + str1); + System.out.println("String 2: " + str2); + System.out.println("LCS: " + lcs); + System.out.println("LCS length: " + lcs.length()); + } + } +} \ No newline at end of file diff --git a/Dynamic Programming/LongestIncreasingSubsequence.java b/Dynamic Programming/LongestIncreasingSubsequence.java index 1616c246..eaa574a4 100644 --- a/Dynamic Programming/LongestIncreasingSubsequence.java +++ b/Dynamic Programming/LongestIncreasingSubsequence.java @@ -31,7 +31,7 @@ public class LongestIncreasingSubsequence { return r; } - public static int LIS(int[] array) { + private static int LIS(int[] array) { int N = array.length; if (N == 0) return 0; diff --git a/Dynamic Programming/RodCutting.java b/Dynamic Programming/RodCutting.java index 3424afac..cd251205 100644 --- a/Dynamic Programming/RodCutting.java +++ b/Dynamic Programming/RodCutting.java @@ -2,8 +2,7 @@ Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */ -public class RodCutting -{ +public class RodCutting { private static int cutRod(int price[],int n) { diff --git a/Misc/Abecedarian.java b/Others/Abecedarian.java similarity index 100% rename from Misc/Abecedarian.java rename to Others/Abecedarian.java index 6507411b..acde132c 100644 --- a/Misc/Abecedarian.java +++ b/Others/Abecedarian.java @@ -12,6 +12,6 @@ class Abecedarian{ else{return false;} } - } return true; + } } diff --git a/Others/Armstrong.java b/Others/Armstrong.java new file mode 100644 index 00000000..9267d9ea --- /dev/null +++ b/Others/Armstrong.java @@ -0,0 +1,47 @@ +import java.util.Scanner; + +/** + * A utility to check if a given number is armstrong or not. Armstrong number is + * a number that is equal to the sum of cubes of its digits for example 0, 1, + * 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3 + * + * @author mani manasa mylavarapu + * + */ +public class Armstrong { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + System.out.println("please enter the number"); + int n = scan.nextInt(); + boolean isArmstrong = checkIfANumberIsAmstrongOrNot(n); + if (isArmstrong) { + System.out.println("the number is armstrong"); + } else { + System.out.println("the number is not armstrong"); + } + } + + /** + * Checks whether a given number is an armstrong number or not. Armstrong + * number is a number that is equal to the sum of cubes of its digits for + * example 0, 1, 153, 370, 371, 407 etc. + * + * @param number + * @return boolean + */ + public static boolean checkIfANumberIsAmstrongOrNot(int number) { + int remainder, sum = 0, temp = 0; + temp = number; + while (number > 0) { + remainder = number % 10; + sum = sum + (remainder * remainder * remainder); + number = number / 10; + } + if (sum == temp) { + return true; + } else { + return false; + } + + } +} \ No newline at end of file diff --git a/Misc/CountChar.java b/Others/CountChar.java similarity index 100% rename from Misc/CountChar.java rename to Others/CountChar.java diff --git a/Misc/Dijkshtra.java b/Others/Dijkshtra.java similarity index 92% rename from Misc/Dijkshtra.java rename to Others/Dijkshtra.java index 377c487e..741c9bd3 100644 --- a/Misc/Dijkshtra.java +++ b/Others/Dijkshtra.java @@ -4,6 +4,11 @@ */ +import java.io.IOException; +import java.util.Arrays; +import java.util.Scanner; +import java.util.Stack; + public class Solution { public static void main(String[] args) throws IOException { @@ -30,7 +35,7 @@ public static void main(String[] args) throws IOException { //Implementing Dijkshtra's Algorithm - Stack t=new Stack(); + Stack t=new Stack(); int src=in.nextInt(); for(int i=1;i<=n;i++){ if(i!=src){t.push(i);}} diff --git a/Misc/Factorial.java b/Others/Factorial.java similarity index 98% rename from Misc/Factorial.java rename to Others/Factorial.java index b7cc906a..11265ec0 100644 --- a/Misc/Factorial.java +++ b/Others/Factorial.java @@ -1,4 +1,3 @@ -package factorial; import java.util.Scanner; /** diff --git a/Misc/FibToN.java b/Others/FibToN.java similarity index 100% rename from Misc/FibToN.java rename to Others/FibToN.java diff --git a/Misc/FindingPrimes.java b/Others/FindingPrimes.java similarity index 100% rename from Misc/FindingPrimes.java rename to Others/FindingPrimes.java diff --git a/Others/FloydTriangle.java b/Others/FloydTriangle.java new file mode 100644 index 00000000..f655b68a --- /dev/null +++ b/Others/FloydTriangle.java @@ -0,0 +1,16 @@ +import java.util.Scanner; + +public class FloydTriangle { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter the number of rows which you want in your Floyd Triangle: "); + int r = sc.nextInt(), n = 0; + + for(int i=0; i < r; i++) { + for(int j=0; j <= i; j++) { + System.out.print(++n + " "); + } + System.out.println(); + } + } +} diff --git a/Misc/GCD.java b/Others/GCD.java similarity index 100% rename from Misc/GCD.java rename to Others/GCD.java diff --git a/Others/Huffman.java b/Others/Huffman.java new file mode 100644 index 00000000..f3ab6c6b --- /dev/null +++ b/Others/Huffman.java @@ -0,0 +1,158 @@ + +import java.util.Comparator; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Scanner; +import java.util.Stack; +/** + * + * @author Mayank Kumar (mk9440) + */ +/* +Output : + +Enter number of distinct letters +6 +Enter letters with its frequncy to encode +Enter letter : a +Enter frequncy : 45 + +Enter letter : b +Enter frequncy : 13 + +Enter letter : c +Enter frequncy : 12 + +Enter letter : d +Enter frequncy : 16 + +Enter letter : e +Enter frequncy : 9 + +Enter letter : f +Enter frequncy : 5 + +Letter Encoded Form +a 0 +b 1 0 1 +c 1 0 0 +d 1 1 1 +e 1 1 0 1 +f 1 1 0 0 + +*/ + +class Node{ +String letr=""; +int freq=0,data=0; +Node left=null,right=null; +} + +//A comparator class to sort list on the basis of their frequency +class comp implements Comparator{ + @Override + public int compare(Node o1, Node o2) { + if(o1.freq>o2.freq){return 1;} + else if(o1.freq 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){ + //Sorting list in increasing order of its letter frequency + li.sort(new comp()); + Node temp=null; + Iterator it=li.iterator(); + //System.out.println(li.size()); + //Loop for making huffman tree till only single node remains in list + while(true){ + temp=new Node(); + //a and b are Node which are to be combine to make its parent + Node a=new Node(),b=new Node(); + a=null;b=null; + //checking if list is eligible for combining or not + //here first assignment of it.next in a will always be true as list till end will + //must have atleast one node + a=(Node)it.next(); + //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 + //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 + temp.left=a;temp.right=b; + //after combing, removing first two nodes in list which are already combined + li.remove(0);//removes first element which is now combined -step1 + li.remove(0);//removes 2nd element which comes on 1st position after deleting first in step1 + li.add(temp);//adding new combined node to list + //print_list(li); //For visualizing each combination step + } + //Sorting after combining to again repeat above on sorted frequency list + li.sort(new comp()); + it=li.iterator();//resetting list pointer to first node (head/root of tree) + if(li.size()==1){return (Node)it.next();} //base condition ,returning root of huffman tree + } +} + + //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 + int freq=n.freq; // recording root freq to avoid it adding in path encoding + find_path_and_encode(st,n,ch,freq); + } + + //A simple utility function to print stack (Used for printing path) + public static void print_path(Stack st){ + for(int i=0;i st,Node root,String s,int f){ + //Base condition + if(root!= null){ + if(root.freq!=f){st.push(root);} // avoiding root to add in path/encoding bits + if(root.letr.equals(s)){print_path(st);return;} // Recursion stopping condition when path gets founded + find_path_and_encode(st,root.left,s,f); + find_path_and_encode(st,root.right,s,f); + //Popping if path not found in right or left of this node,because we previously + //pushed this node in taking a mindset that it might be in path + st.pop(); + } + } + + public static void main(String args[]){ + List li=new LinkedList<>(); + Scanner in=new Scanner(System.in); + 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"); + for(int i=0;i s = new Stack (); + Scanner tokens = new Scanner(exp); + + while (tokens.hasNext()) { + if (tokens.hasNextInt()) { + s.push(tokens.nextInt()); // If int then push to stack + } else { // else pop top two values and perform the operation + int num2 = s.pop(); + int num1 = s.pop(); + String op = tokens.next(); + + if (op.equals("+")) { + s.push(num1 + num2); + } else if (op.equals("-")) { + s.push(num1 - num2); + } else if (op.equals("*")) { + s.push(num1 * num2); + } else { + s.push(num1 / num2); + } + + // "+", "-", "*", "/" + } + } + return s.pop(); + } +} diff --git a/Misc/TowerOfHanoiUsingRecursion.java b/Others/TowerOfHanoiUsingRecursion.java similarity index 100% rename from Misc/TowerOfHanoiUsingRecursion.java rename to Others/TowerOfHanoiUsingRecursion.java diff --git a/Misc/countwords.java b/Others/countwords.java similarity index 100% rename from Misc/countwords.java rename to Others/countwords.java diff --git a/Misc/crc32.java b/Others/crc32.java similarity index 100% rename from Misc/crc32.java rename to Others/crc32.java diff --git a/Others/insert_delete_in_array.java b/Others/insert_delete_in_array.java new file mode 100644 index 00000000..12bbdc19 --- /dev/null +++ b/Others/insert_delete_in_array.java @@ -0,0 +1,46 @@ +import java.util.*; +public class Array { + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); // Input statement + System.out.println("Enter the size of the array"); + int size = s.nextInt(); + int a[] = new int[size]; + int i; + + // To enter the initial elements + for(i=0;i end){ + return -1; + } + /* First boundary: add 1/3 of length to start */ + int mid1 = start + (end - start) / 3; + /* Second boundary: add 2/3 of length to start */ + int mid2 = start + 2 * (end - start) / 3; + if (arr[mid1] == key) { + return mid1; + } + else if (arr[mid2] == key) { + return mid2; + } + + /* Search the first (1/3) rd part of the array.*/ + + else if (key < arr[mid1]) { + return ternarySearch(arr, key, start, mid1 - 1); + } + /* Search 3rd (1/3)rd part of the array */ + + else if (key > arr[mid2]) { + return ternarySearch(arr, key, mid2 + 1, end); + } + /* Search middle (1/3)rd part of the array */ + + else { + return ternarySearch(arr, key, mid1, mid2); + } + } + + public static void main(String[] args) { + Scanner s = new Scanner(System.in); + System.out.println("Enter number of elements in the array"); + int n = s.nextInt(); + int arr[] = new int[n]; + System.out.println("Enter the elements of the Sorted array"); + for (int i= 0; i < n; i++){ + arr[i] = s.nextInt(); + } + System.out.println("Enter element to search for : "); + int k = s.nextInt(); + int ans = ternarySearch(arr, k); + if (ans == -1) { + System.out.println(" The element is not present in the array."); + } + else { + System.out.println("The element is present at the position " + (ans+1)); + } + } +} \ No newline at end of file diff --git a/Sorts/BogoSort.java b/Sorts/BogoSort.java new file mode 100644 index 00000000..33787178 --- /dev/null +++ b/Sorts/BogoSort.java @@ -0,0 +1,68 @@ +package Sorts; + +import java.util.Random; + +public class BogoSort { + private static void swap(T array[], int first, int second){ + T randomElement = array[first]; + array[first] = array[second]; + array[second] = randomElement; + } + + private static > boolean isSorted(T array[]){ + for(int i = 0; i 0) return false; + } + return true; + } + + // Randomly shuffles the array + private static void nextPermutation(T array[]){ + int length = array.length; + Random random = new Random(); + + for (int i = 0; i < array.length; i++) { + int randomIndex = i + random.nextInt(length - i); + swap(array, randomIndex, i); + } + } + + public static > void bogoSort(T array[]) { + while(!isSorted(array)){ + nextPermutation(array); + } + } + + // Driver Program + public static void main(String[] args) + { + // Integer Input + int[] arr1 = {4,23,6,78,1,54,231,9,12}; + int last = arr1.length; + Integer[] array = new Integer[last]; + for (int i=0;i 1 4 6 9 12 23 54 78 231 + for(int i=0; i a b c d e + for(int i=0; i> void CS(T array[], int last) { + + // Sorting + boolean swap; + do { + swap = false; + + //front + for (int count = 0; count <= last - 2; count++) { + int comp = array[count].compareTo(array[count + 1]); + if (comp > 0) { + T aux = array[count]; + array[count] = array[count + 1]; + array[count + 1] = aux; + swap = true; + } + } + //break if no swap occurred + if (!swap) { + break; + } + swap = false; + + //back + for (int count = last - 2; count >= 0; count--) { + int comp = array[count].compareTo(array[count + 1]); + if (comp > 0) { + T aux = array[count]; + array[count] = array[count + 1]; + array[count + 1] = aux; + swap = true; + } + } + last--; + //end + } while (swap); + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + int last = arr1.length; + Integer[] array = new Integer[last]; + for (int i = 0; i < last; i++) { + array[i] = arr1[i]; + } + + CS(array, last); + + // Output => 1 4 6 9 12 23 54 78 231 + for (int i = 0; i < last; i++) { + System.out.print(array[i] + "\t"); + } + System.out.println(); + + // String Input + String[] array1 = { "c", "a", "e", "b", "d" }; + last = array1.length; + + CS(array1, last); + + // Output => a b c d e + for (int i = 0; i < last; i++) { + System.out.print(array1[i] + "\t"); + } + } +} diff --git a/Sorts/CountingSort.java b/Sorts/CountingSort.java new file mode 100644 index 00000000..e6828265 --- /dev/null +++ b/Sorts/CountingSort.java @@ -0,0 +1,90 @@ +import java.util.ArrayList; +import java.util.Map; +import java.util.TreeMap; + +/** + * + * @author Youssef Ali (https://github.com/youssefAli11997) + * + */ + +class CountingSort { + + /** + * This method implements the Generic Counting Sort + * + * @param array The array to be sorted + * @param last The count of total number of elements in array + * Sorts the array in increasing order + * It uses array elements as keys in the frequency map + **/ + + public static > void CS(T[] array, int last) { + + Map frequency = new TreeMap(); + // The final output array + ArrayList sortedArray = new ArrayList(); + + // Counting the frequency of @param array elements + for(T t : array) { + try{ + frequency.put(t, frequency.get(t)+1); + }catch(Exception e){ // new entry + frequency.put(t, 1); + } + } + + // Filling the sortedArray + for(Map.Entry element : frequency.entrySet()) { + for(int j=0; j 1 4 6 9 12 23 54 78 231 + System.out.println("After Sorting:"); + for (int i=0;i a b c d e + System.out.println("After Sorting:"); + for(int i=0; i 0; lastSortedIndex--){ - - //If our extracted element is smaller than element to the right, switch them. - if (sortedArray[lastSortedIndex-1] > extractedElement){ - //move the element to the left of extractedElement to the right in sortedArray - sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1]; - //And move the current extractedElement to the left one (since it's smaller). - sortedArray[lastSortedIndex-1] = extractedElement; - } - else{ - //insert element where it is. - sortedArray[lastSortedIndex] = extractedElement; - //Terminating loop since element is in the right spot. - break; - } - - } - - } - - return sortedArray; - - } - -} diff --git a/Sorts/radixSort.java b/Sorts/radixSort.java index 572917b5..5afacad8 100644 --- a/Sorts/radixSort.java +++ b/Sorts/radixSort.java @@ -1,5 +1,3 @@ - -import java.io.*; import java.util.*; class Radix { diff --git a/ciphers/RSA.java b/ciphers/RSA.java new file mode 100644 index 00000000..5baa61b0 --- /dev/null +++ b/ciphers/RSA.java @@ -0,0 +1,62 @@ +package ciphers; + +import java.math.BigInteger; +import java.security.SecureRandom; + +/** + * Created by Nguyen Duy Tiep on 23-Oct-17. + */ +public class RSA { + private BigInteger modulus, privateKey, publicKey; + + public RSA(int bits) { + generateKeys(bits); + } + + public synchronized String encrypt(String message) { + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); + } + + public synchronized BigInteger encrypt(BigInteger message) { + return message.modPow(publicKey, modulus); + } + + public synchronized String decrypt(String message) { + return new String((new BigInteger(message)).modPow(privateKey, modulus).toByteArray()); + } + + public synchronized BigInteger decrypt(BigInteger message) { + return message.modPow(privateKey, modulus); + } + + /** Generate a new public and private key set. */ + public synchronized void generateKeys(int bits) { + SecureRandom r = new SecureRandom(); + BigInteger p = new BigInteger(bits / 2, 100, r); + BigInteger q = new BigInteger(bits / 2, 100, r); + modulus = p.multiply(q); + + BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); + + publicKey = new BigInteger("3"); + + while (m.gcd(publicKey).intValue() > 1) { + publicKey = publicKey.add(new BigInteger("2")); + } + + privateKey = publicKey.modInverse(m); + } + + /** Trivial test program. */ + public static void main(String[] args) { + RSA rsa = new RSA(1024); + + String text1 = "This is a message"; + System.out.println("Plaintext: " + text1); + + String ciphertext = rsa.encrypt(text1); + System.out.println("Ciphertext: " + ciphertext); + + System.out.println("Plaintext: " + rsa.decrypt(ciphertext)); + } +} diff --git a/data_structures/Bags/Bag.java b/data_structures/Bags/Bag.java new file mode 100644 index 00000000..06b454ed --- /dev/null +++ b/data_structures/Bags/Bag.java @@ -0,0 +1,126 @@ +package Bags; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * Collection which does not allow removing elements (only collect and iterate) + * + * @param - the generic type of an element in this bag + */ +public class Bag implements Iterable { + + private Node firstElement; // first element of the bag + private int size; // size of bag + + private static class Node { + private Element content; + private Node nextElement; + } + + /** + * Create an empty bag + */ + public Bag() { + firstElement = null; + size = 0; + } + + /** + * @return true if this bag is empty, false otherwise + */ + public boolean isEmpty() { + return firstElement == null; + } + + /** + * @return the number of elements + */ + public int size() { + return size; + } + + /** + * @param element - the element to add + */ + public void add(Element element) { + Node oldfirst = firstElement; + firstElement = new Node<>(); + firstElement.content = element; + firstElement.nextElement = oldfirst; + size++; + } + + /** + * Checks if the bag contains a specific element + * + * @param element which you want to look for + * @return true if bag contains element, otherwise false + */ + public boolean contains(Element element) { + Iterator iterator = this.iterator(); + while(iterator.hasNext()) { + if (iterator.next().equals(element)) { + return true; + } + } + return false; + } + + /** + * @return an iterator that iterates over the elements in this bag in arbitrary order + */ + public Iterator iterator() { + return new ListIterator<>(firstElement); + } + + @SuppressWarnings("hiding") + private class ListIterator implements Iterator { + private Node currentElement; + + public ListIterator(Node firstElement) { + currentElement = firstElement; + } + + public boolean hasNext() { + return currentElement != null; + } + + /** + * remove is not allowed in a bag + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + public Element next() { + if (!hasNext()) + throw new NoSuchElementException(); + Element element = currentElement.content; + currentElement = currentElement.nextElement; + return element; + } + } + + /** + * main-method for testing + */ + public static void main(String[] args) { + Bag bag = new Bag<>(); + + bag.add("1"); + bag.add("1"); + bag.add("2"); + + System.out.println("size of bag = " + bag.size()); + for (String s : bag) { + System.out.println(s); + } + + System.out.println(bag.contains(null)); + System.out.println(bag.contains("1")); + System.out.println(bag.contains("3")); + } + +} diff --git a/data_structures/Buffers/CircularBuffer.java b/data_structures/Buffers/CircularBuffer.java new file mode 100644 index 00000000..d1f7016d --- /dev/null +++ b/data_structures/Buffers/CircularBuffer.java @@ -0,0 +1,124 @@ +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; + +public class CircularBuffer { + private char[] _buffer; + public final int _buffer_size; + private int _write_index = 0; + private int _read_index = 0; + private AtomicInteger _readable_data = new AtomicInteger(0); + + public CircularBuffer(int buffer_size) { + if(!IsPowerOfTwo(buffer_size)) { + throw new IllegalArgumentException(); + } + this._buffer_size = buffer_size; + _buffer = new char[buffer_size]; + } + + private boolean IsPowerOfTwo(int i) { + return (i & (i - 1)) == 0; + } + + private int getTrueIndex(int i) { + return i % _buffer_size; + } + + public Character readOutChar() { + Character result = null; + + //if we have data to read + if(_readable_data.get() > 0) { + result = new Character(_buffer[getTrueIndex(_read_index)]); + _readable_data.decrementAndGet(); + _read_index++; + } + + return result; + } + + public boolean writeToCharBuffer(char c) { + boolean result = false; + + //if we can write to the buffer + if(_readable_data.get() < _buffer_size) { + //write to buffer + _buffer[getTrueIndex(_write_index)] = c; + _readable_data.incrementAndGet(); + _write_index++; + result = true; + } + + return result; + } + + private static class TestWriteWorker implements Runnable { + String _alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"; + Random _random = new Random(); + CircularBuffer _buffer; + public TestWriteWorker(CircularBuffer cb) { + this._buffer = cb; + } + + private char getRandomChar() { + return _alphabet.charAt(_random.nextInt(_alphabet.length())); + } + + public void run() { + while(!Thread.interrupted()) { + if(!_buffer.writeToCharBuffer(getRandomChar())){ + Thread.yield(); + try{ + Thread.sleep(10); + } catch (InterruptedException e) { + return; + } + } + } + } + } + + private static class TestReadWorker implements Runnable { + CircularBuffer _buffer; + public TestReadWorker(CircularBuffer cb) { + this._buffer = cb; + } + + public void run() { + System.out.println("Printing Buffer:"); + while(!Thread.interrupted()) { + Character c = _buffer.readOutChar(); + if(c != null) { + System.out.print(c.charValue()); + } else { + Thread.yield(); + try { + Thread.sleep(10); + } catch (InterruptedException e) { + System.out.println(); + return; + } + } + } + } + } + + public static void main(String[] args) throws InterruptedException { + int buffer_size = 1024; + //create circular buffer + CircularBuffer cb = new CircularBuffer(buffer_size); + + //create threads that read and write the buffer. + Thread write_thread = new Thread(new TestWriteWorker(cb)); + Thread read_thread = new Thread(new TestReadWorker(cb)); + read_thread.start(); + write_thread.start(); + + //wait some amount of time + Thread.sleep(10000); + + //interrupt threads and exit + write_thread.interrupt(); + read_thread.interrupt(); + } +} diff --git a/data_structures/Graphs/Kruskal's Algorithm.java b/data_structures/Graphs/Kruskal's Algorithm.java new file mode 100644 index 00000000..6fc8412c --- /dev/null +++ b/data_structures/Graphs/Kruskal's Algorithm.java @@ -0,0 +1,174 @@ +// Java program for Kruskal's algorithm to find Minimum Spanning Tree +// of a given connected, undirected and weighted graph +import java.util.*; +import java.lang.*; +import java.io.*; + +class Graph +{ + // A class to represent a graph edge + class Edge implements Comparable + { + int src, dest, weight; + + // Comparator function used for sorting edges based on + // their weight + public int compareTo(Edge compareEdge) + { + return this.weight-compareEdge.weight; + } + }; + + // A class to represent a subset for union-find + class subset + { + int parent, rank; + }; + + int V, E; // V-> no. of vertices & E->no.of edges + Edge edge[]; // collection of all edges + + // Creates a graph with V vertices and E edges + Graph(int v, int e) + { + V = v; + E = e; + edge = new Edge[E]; + for (int i=0; i subsets[yroot].rank) + subsets[yroot].parent = xroot; + + // If ranks are same, then make one as root and increment + // its rank by one + else + { + subsets[yroot].parent = xroot; + subsets[xroot].rank++; + } + } + + // The main function to construct MST using Kruskal's algorithm + void KruskalMST() + { + Edge result[] = new Edge[V]; // Tnis will store the resultant MST + int e = 0; // An index variable, used for result[] + int i = 0; // An index variable, used for sorted edges + for (i=0; i { + ArrayList _queue = new ArrayList(); + + private boolean hasElements() { + return !_queue.isEmpty(); + } + + public T peek() { + T result = null; + if(this.hasElements()) { result = _queue.get(0); } + return result; + } + + public boolean add(T element) { + return _queue.add(element); + } + + public T poll() { + T result = null; + if(this.hasElements()) { result = _queue.remove(0); } + return result; + } + + public static void main(String[] args) { + GenericArrayListQueue queue = new GenericArrayListQueue(); + System.out.println("Running..."); + assert queue.peek() == null; + assert queue.poll() == null; + assert queue.add(1) == true; + assert queue.peek() == 1; + assert queue.add(2) == true; + assert queue.peek() == 1; + assert queue.poll() == 1; + assert queue.peek() == 2; + assert queue.poll() == 2; + assert queue.peek() == null; + assert queue.poll() == null; + System.out.println("Finished."); + } +} diff --git a/data_structures/Stacks/StackOfLinkedList.java b/data_structures/Stacks/StackOfLinkedList.java new file mode 100644 index 00000000..8903e52f --- /dev/null +++ b/data_structures/Stacks/StackOfLinkedList.java @@ -0,0 +1,98 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ + +// An implementation of a Stack using a Linked List + +class StackOfLinkedList { + + public static void main(String[] args) { + + LinkedListStack stack = new LinkedListStack(); + stack.push(1); + stack.push(2); + stack.push(3); + stack.push(4); + + stack.printStack(); + + System.out.println("Size of stack currently is: " + stack.getSize()); + + stack.pop(); + stack.pop(); + + } + +} + +// A node class + +class Node { + public int data; + public Node next; + + public Node(int data) { + this.data = data; + this.next = null; + } +} + +/** + * A class which implements a stack using a linked list + * + * Contains all the stack methods : push, pop, printStack, isEmpty + **/ + +class LinkedListStack { + + Node head = null; + int size = 0; + + public void push(int x) { + Node n = new Node(x); + if (getSize() == 0) { + head = n; + } + else { + Node temp = head; + n.next = temp; + head = n; + } + size++; + } + + public void pop() { + if (getSize() == 0) { + System.out.println("Empty stack. Nothing to pop"); + } + + Node temp = head; + head = head.next; + size--; + + System.out.println("Popped element is: " + temp.data); + } + + public void printStack() { + + Node temp = head; + System.out.println("Stack is printed as below: "); + while (temp != null) { + System.out.print(temp.data + " "); + temp = temp.next; + } + System.out.println(); + + } + + public boolean isEmpty() { + return getSize() == 0; + } + + public int getSize() { + return size; + } + +} diff --git a/data_structures/Trees/FindHeightOfTree.java b/data_structures/Trees/FindHeightOfTree.java new file mode 100644 index 00000000..675b1e8b --- /dev/null +++ b/data_structures/Trees/FindHeightOfTree.java @@ -0,0 +1,100 @@ +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * + */ +import java.util.LinkedList; + +public class FindHeightOfTree { + + // Driver Program + public static void main(String[] args) { + Node tree = new Node(5); + tree.insert(3); + tree.insert(7); + tree.insert(1); + tree.insert(-1); + tree.insert(29); + tree.insert(93); + tree.insert(6); + tree.insert(0); + tree.insert(-5); + tree.insert(-6); + tree.insert(-8); + tree.insert(-1); + + // A level order representation of the tree + tree.printLevelOrder(); + System.out.println(); + + System.out.println("Height of the tree is: " + tree.findHeight()); + } +} + +/** + * The Node class which initializes a Node of a tree + * printLevelOrder: ROOT -> ROOT's CHILDREN -> ROOT's CHILDREN's CHILDREN -> etc + * findHeight: Returns the height of the tree i.e. the number of links between root and farthest leaf + */ +class Node { + Node left, right; + int data; + + public Node(int data) { + this.data = data; + } + + public void insert (int value) { + if (value < data) { + if (left == null) { + left = new Node(value); + } + else { + left.insert(value); + } + } + else { + if (right == null) { + right = new Node(value); + } + else { + right.insert(value); + } + } + } + + public void printLevelOrder() { + LinkedList queue = new LinkedList<>(); + queue.add(this); + while(!queue.isEmpty()) { + Node n = queue.poll(); + System.out.print(n.data + " "); + if (n.left != null) { + queue.add(n.left); + } + if (n.right != null) { + queue.add(n.right); + } + } + } + + public int findHeight() { + return findHeight(this); + } + + private int findHeight(Node root) { + if (root.left == null && root.right == null) { + return 0; + } + else if (root.left != null && root.right != null) { + return 1 + Math.max(findHeight(root.left), findHeight(root.right)); + } + else if (root.left == null && root.right != null) { + return 1 + findHeight(root.right); + } + else { + return 1 + findHeight(root.left); + } + } +} + diff --git a/data_structures/Trees/Level Order Traversal(using Queue).java b/data_structures/Trees/Level Order Traversal(using Queue).java new file mode 100644 index 00000000..4f263c95 --- /dev/null +++ b/data_structures/Trees/Level Order Traversal(using Queue).java @@ -0,0 +1,62 @@ +import java.util.Queue; +import java.util.LinkedList; + +/* Class to represent Tree node */ +class Node { + int data; + Node left, right; + + public Node(int item) { + data = item; + left = null; + right = null; + } +} + +/* Class to print Level Order Traversal */ +class BinaryTree { + + Node root; + + /* Given a binary tree. Print its nodes in level order + using array for implementing queue */ + void printLevelOrder() + { + Queue queue = new LinkedList(); + queue.add(root); + while (!queue.isEmpty()) + { + + /* poll() removes the present head. + For more information on poll() visit + http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */ + Node tempNode = queue.poll(); + System.out.print(tempNode.data + " "); + + /*Enqueue left child */ + if (tempNode.left != null) { + queue.add(tempNode.left); + } + + /*Enqueue right child */ + if (tempNode.right != null) { + queue.add(tempNode.right); + } + } + } + + public static void main(String args[]) + { + /* creating a binary tree and entering + the nodes */ + BinaryTree tree_level = new BinaryTree(); + tree_level.root = new Node(1); + tree_level.root.left = new Node(2); + tree_level.root.right = new Node(3); + tree_level.root.left.left = new Node(4); + tree_level.root.left.right = new Node(5); + + System.out.println("Level order traversal of binary tree is - "); + tree_level.printLevelOrder(); + } +} \ No newline at end of file diff --git a/data_structures/Trees/Level Order Traversal.java b/data_structures/Trees/Level Order Traversal.java new file mode 100644 index 00000000..845ab376 --- /dev/null +++ b/data_structures/Trees/Level Order Traversal.java @@ -0,0 +1,78 @@ +class Node +{ + int data; + Node left, right; + public Node(int item) + { + data = item; + left = right = null; + } +} + +class BinaryTree +{ + // Root of the Binary Tree + Node root; + + public BinaryTree() + { + root = null; + } + + /* function to print level order traversal of tree*/ + void printLevelOrder() + { + int h = height(root); + int i; + for (i=1; i<=h; i++) + printGivenLevel(root, i); + } + + /* Compute the "height" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ + int height(Node root) + { + if (root == null) + 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); + } + } + + /* Print nodes at the given level */ + void printGivenLevel (Node root ,int level) + { + if (root == null) + return; + if (level == 1) + System.out.print(root.data + " "); + else if (level > 1) + { + printGivenLevel(root.left, level-1); + printGivenLevel(root.right, level-1); + } + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root= new Node(1); + tree.root.left= new Node(2); + tree.root.right= new Node(3); + tree.root.left.left= new Node(4); + tree.root.left.right= new Node(5); + + System.out.println("Level order traversal of binary tree is "); + tree.printLevelOrder(); + } +} \ No newline at end of file diff --git a/data_structures/Trees/Print Top View of Tree.java b/data_structures/Trees/Print Top View of Tree.java new file mode 100644 index 00000000..a429f8a6 --- /dev/null +++ b/data_structures/Trees/Print Top View of Tree.java @@ -0,0 +1,105 @@ +// Java program to print top view of Binary tree +import java.util.*; + +// Class for a tree node +class TreeNode +{ + // Members + int key; + TreeNode left, right; + + // Constructor + public TreeNode(int key) + { + this.key = key; + left = right = null; + } +} + +// A class to represent a queue item. The queue is used to do Level +// order traversal. Every Queue item contains node and horizontal +// distance of node from root +class QItem +{ + TreeNode node; + int hd; + public QItem(TreeNode n, int h) + { + node = n; + hd = h; + } +} + +// Class for a Binary Tree +class Tree +{ + TreeNode root; + + // Constructors + public Tree() { root = null; } + public Tree(TreeNode n) { root = n; } + + // This method prints nodes in top view of binary tree + public void printTopView() + { + // base case + if (root == null) { return; } + + // Creates an empty hashset + HashSet set = new HashSet<>(); + + // Create a queue and add root to it + Queue Q = new LinkedList(); + Q.add(new QItem(root, 0)); // Horizontal distance of root is 0 + + // Standard BFS or level order traversal loop + while (!Q.isEmpty()) + { + // Remove the front item and get its details + QItem qi = Q.remove(); + int hd = qi.hd; + TreeNode n = qi.node; + + // If this is the first node at its horizontal distance, + // then this node is in top view + if (!set.contains(hd)) + { + set.add(hd); + System.out.print(n.key + " "); + } + + // Enqueue left and right children of current node + if (n.left != null) + Q.add(new QItem(n.left, hd-1)); + if (n.right != null) + Q.add(new QItem(n.right, hd+1)); + } + } +} + +// Driver class to test above methods +public class Main +{ + public static void main(String[] args) + { + /* Create following Binary Tree + 1 + / \ + 2 3 + \ + 4 + \ + 5 + \ + 6*/ + TreeNode root = new TreeNode(1); + root.left = new TreeNode(2); + root.right = new TreeNode(3); + root.left.right = new TreeNode(4); + root.left.right.right = new TreeNode(5); + root.left.right.right.right = new TreeNode(6); + Tree t = new Tree(root); + System.out.println("Following are nodes in top view of Binary Tree"); + t.printTopView(); + } +} \ No newline at end of file diff --git a/data_structures/Trees/TrieImp.java b/data_structures/Trees/TrieImp.java new file mode 100644 index 00000000..c55586ff --- /dev/null +++ b/data_structures/Trees/TrieImp.java @@ -0,0 +1,135 @@ +//Trie Data structure implementation without any libraries */ + +/** + * + * @author Dheeraj Kumar Barnwal (https://github.com/dheeraj92) + * + */ +import java.util.Scanner; + +public class TrieImp { + + public class TrieNode { + TrieNode[] child; + boolean end; + + public TrieNode(){ + child = new TrieNode[26]; + end = false; + } + } + private final TrieNode root; + public TrieImp(){ + root = new TrieNode(); + } + + public void insert(String word){ + TrieNode currentNode = root; + for(int i=0; i < word.length();i++){ + TrieNode node = currentNode.child[word.charAt(i)-'a']; + if(node == null){ + node = new TrieNode(); + currentNode.child[word.charAt(i)-'a']=node; + } + currentNode = node; + } + currentNode.end = true; + } + public boolean search(String word){ + TrieNode currentNode = root; + for(int i=0;i= min and <= max. */ + boolean isBSTUtil(Node node, int min, int max) + { + /* an empty tree is BST */ + if (node == null) + return true; + + /* false if this node violates the min/max constraints */ + if (node.data < min || node.data > max) + return false; + + /* otherwise check the subtrees recursively + tightening the min/max constraints */ + // Allow only distinct values + return (isBSTUtil(node.left, min, node.data-1) && + isBSTUtil(node.right, node.data+1, max)); + } + + /* Driver program to test above functions */ + public static void main(String args[]) + { + BinaryTree tree = new BinaryTree(); + tree.root = new Node(4); + tree.root.left = new Node(2); + tree.root.right = new Node(5); + tree.root.left.left = new Node(1); + tree.root.left.right = new Node(3); + + if (tree.isBST()) + System.out.println("IS BST"); + else + System.out.println("Not a BST"); + } +} \ No newline at end of file