From 3b98e0fc903d1f671415fadc741167933e39fa18 Mon Sep 17 00:00:00 2001 From: Sanjeev Date: Fri, 2 Mar 2018 01:54:29 +0530 Subject: [PATCH] Added 20+ implementations in Java and python --- .../Cpp/generate_all_parentheses_II | Bin 0 -> 31184 bytes .../Cpp/generate_all_parentheses_II.cpp | 52 +++++++ .../Java/Valid_Parenthesis.java | 54 +++++++ .../c++/generate_all_parentheses_II.cpp | 44 ------ .../knightsTour/Java/KnightsTour.java | 90 ++++++++++++ .../m-coloring/Java/mColoringProblem.java | 114 +++++++++++++++ backtracking/m-coloring/Python/mColoring.py | 48 ++++++ dp/EditDistance/Java/EDIST.java | 45 ++++++ dp/EditDistance/Python/EditDistance.py | 34 +++++ dp/Lowest_Common_Ancestor/Java/LCA.java | 91 ++++++++++++ dp/Lowest_Common_Ancestor/Python/lcs.py | 72 +++++++++ dp/egg_dropping_puzzle/Java/eggDropping.java | 58 ++++++++ dp/egg_dropping_puzzle/Python/EggDropping.py | 39 +++++ dp/kadane-_algorithm/Java/kadane.java | 30 ++++ .../Java/LongestCommonSubsequence.java | 39 +++++ .../Java/LongestPalindromicSubsequence.java | 46 ++++++ dp/longest_repeating_subsequence/CPP/lrs.cpp | 47 ++++++ .../Java/LRS.java | 41 ++++++ graph/Java/BFS.java | 81 +++++++++++ graph/Java/DFS.java | 74 ++++++++++ graph/Python/BFS.py | 60 ++++++++ graph/Python/DFS.py | 56 +++++++ greedy/huffman_coding/Java/HuffmanCoding.java | 137 ++++++++++++++++++ 23 files changed, 1308 insertions(+), 44 deletions(-) create mode 100755 backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II create mode 100644 backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp create mode 100644 backtracking/generate_all_parentheses_II/Java/Valid_Parenthesis.java delete mode 100644 backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp create mode 100644 backtracking/knightsTour/Java/KnightsTour.java create mode 100644 backtracking/m-coloring/Java/mColoringProblem.java create mode 100644 backtracking/m-coloring/Python/mColoring.py create mode 100644 dp/EditDistance/Java/EDIST.java create mode 100644 dp/EditDistance/Python/EditDistance.py create mode 100644 dp/Lowest_Common_Ancestor/Java/LCA.java create mode 100644 dp/Lowest_Common_Ancestor/Python/lcs.py create mode 100644 dp/egg_dropping_puzzle/Java/eggDropping.java create mode 100644 dp/egg_dropping_puzzle/Python/EggDropping.py create mode 100644 dp/kadane-_algorithm/Java/kadane.java create mode 100644 dp/longest_common_subsequence/Java/LongestCommonSubsequence.java create mode 100644 dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java create mode 100644 dp/longest_repeating_subsequence/CPP/lrs.cpp create mode 100644 dp/longest_repeating_subsequence/Java/LRS.java create mode 100644 graph/Java/BFS.java create mode 100644 graph/Java/DFS.java create mode 100644 graph/Python/BFS.py create mode 100644 graph/Python/DFS.py create mode 100644 greedy/huffman_coding/Java/HuffmanCoding.java diff --git a/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II new file mode 100755 index 0000000000000000000000000000000000000000..7898a66367e41b0747c81ec53d8d19e708f1ff76 GIT binary patch literal 31184 zcmeHwd30RGmG|pz$ri?z7W35ZZd)C+Mcwii zOiX0J9odXnhByqIC>g?-2?EiYJ}ISiwG6CAUg#K{oS!X^=f5G5hj_q(^M zUcY|o=1YW_zg$Op_tm|(Zr!?d>sGz3`m3Jm)pnarQ^~Gfr%}#5-OVU*)U?4bb5`O? zwDUB#=F}EwlYq&@zndup#hHR5QnZ3ulFtE{f&UV_K$O_se4^ldfz}jM8WN=X63H!3 z1zcMovI=U@k`k38UE`}LN3byoW|2ZjK0~;Z^Q0b?%es!UfQ@{j;ILFoLDfEL8~xYI z_SM_n$Wh)+K&#|q0unDJ->;%UIv-xlSwJ_RC^%orQ&5%r0?Lt|e{ITgM3m=5TB0mZe)tmM>jioF8e+FXVQUeB!-fO#|1Y?C3;}be@fW zGC9!~?%Vgs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zBopdlI^`4(X z(fb|d@=?2+Nl`lk-d9YViKDfACD7O=u1&HV-&5?B2=$&6UeD!(*GiMp8szAmN>yHc zcQL3C4#AGsY}rn#JYKuvbPJBeqS)2<8H2Jy^?j1yPQ0J4@^|8dz7104)ps0c z$*A;Kd^HUA`V=K9t9ifJbS$hzHy77V31A#mIR&R!%B$~8PPs)9rKb|0%Bej4z9r!d z`;|2^Y1qxc_`P6}(=?|#k#LTzzrcc5<%=zNuyayy269H-l1AX!c9FSQF-n>x%eJ!& n5$4P*69sx?9KdUhS`q$L`&Im-;gPET{XS9tBPwW0*82Y+pK!te literal 0 HcmV?d00001 diff --git a/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp new file mode 100644 index 0000000000..3c37cb1562 --- /dev/null +++ b/backtracking/generate_all_parentheses_II/Cpp/generate_all_parentheses_II.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +void call (vector& ans, string st, int A, int cur){ + + if(cur==0 && A==0){ + ans.push_back(st); + return ; + } + + if(cur==0){ + st+='('; + call(ans,st,A-1,1); + return ; + } + + if(A){ + call(ans,st+'(',A-1,cur+1); + call(ans,st+')',A,cur-1); + return ; + } + + while(cur){ + st= st+')'; + cur--; + } + + ans.push_back(st); + return ; +} + +vector generateParenthesis(int A) { + + vector ans; + string st; + call(ans, st, A, 0); + return ans; +} + +int main() +{ + cout<<"Enter the number: "; + + int n; + cin>>n; + + vector ans=generateParenthesis(n); + + for(int i=0;i ans = generateParanthesis(n); + for (String an : ans) { + System.out.println(an); + } + } + + private static ArrayList generateParanthesis(int n){ + char[] str = new char[n*2]; + ArrayList list = new ArrayList<>(); + addParen(list, n, n, str, 0); + return list; + } + + private static void addParen(ArrayList list, int leftRem, int rightRem, char[] str, int index) { + + if(leftRem < 0 || rightRem < leftRem) //Invalid State + return; + + if(leftRem == 0 && rightRem == 0) //Out of left and right parenthesis + list.add(String.copyValueOf(str)); + + else{ + str[index] = '('; //Add left Parenthesis and recurse + addParen(list, leftRem-1, rightRem, str, index+1); + + str[index] = ')'; //Add right Parenthesis and recurse + addParen(list, leftRem, rightRem-1, str, index+1); + } + } +} + diff --git a/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp b/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp deleted file mode 100644 index 2594bde2ff..0000000000 --- a/backtracking/generate_all_parentheses_II/c++/generate_all_parentheses_II.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include -using namespace std; -void call (vector& ans, string st, int A,int cur){ - - if(cur==0&&A==0){ - ans.push_back(st); - return ; - } - if(cur==0){ - st+='('; - call(ans,st,A-1,1); - return ; - } - if(A){ - call(ans,st+'(',A-1,cur+1); - call(ans,st+')',A,cur-1); - return ; - } - while(cur){ - st= st+')'; - cur--; - } - ans.push_back(st); - return ; - -} -vector generateParenthesis(int A) { - -vector ans; -string st; -call(ans, st, A,0); - return ans; -} -int main() -{ - cout<<"Enter the number: "; - int n; - cin>>n; -vector ans=generateParenthesis(n); - -for(int i=0;i= 0 && x < N && y >= 0 && + y < N && sol[x][y] == -1); + } + + /* A utility function to print solution + matrix sol[N][N] */ + static void printSolution(int sol[][]) { + for (int x = 0; x < N; x++) { + for (int y = 0; y < N; y++) + System.out.print(sol[x][y] + " "); + System.out.println(); + } + } + + /* This function solves the Knight Tour problem + using Backtracking. This function mainly + uses solveKTUtil() to solve the problem. It + returns false if no complete tour is possible, + otherwise return true and prints the tour. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions. */ + static boolean solveKT() { + int sol[][] = new int[8][8]; + + /* Initialization of solution matrix */ + for (int x = 0; x < N; x++) + for (int y = 0; y < N; y++) + sol[x][y] = -1; + + /* xMove[] and yMove[] define next move of Knight. + xMove[] is for next value of x coordinate + yMove[] is for next value of y coordinate */ + int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2}; + int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1}; + + // Since the Knight is initially at the first block + sol[0][0] = 0; + + /* Start from 0,0 and explore all tours using + solveKTUtil() */ + if (!solveKTUtil(0, 0, 1, sol, xMove, yMove)) { + System.out.println("Solution does not exist"); + return false; + } else + printSolution(sol); + + return true; + } + + /* A recursive utility function to solve Knight + Tour problem */ + static boolean solveKTUtil(int x, int y, int movei, + int sol[][], int xMove[], + int yMove[]) { + int k, next_x, next_y; + if (movei == N * N) + return true; + + /* Try all next moves from the current coordinate + x, y */ + for (k = 0; k < 8; k++) { + next_x = x + xMove[k]; + next_y = y + yMove[k]; + if (isSafe(next_x, next_y, sol)) { + sol[next_x][next_y] = movei; + if (solveKTUtil(next_x, next_y, movei + 1, + sol, xMove, yMove)) + return true; + else + sol[next_x][next_y] = -1;// backtracking + } + } + + return false; + } + + /* Driver program to test above functions */ + public static void main(String args[]) { + solveKT(); + } +} + diff --git a/backtracking/m-coloring/Java/mColoringProblem.java b/backtracking/m-coloring/Java/mColoringProblem.java new file mode 100644 index 0000000000..caa5eaa69d --- /dev/null +++ b/backtracking/m-coloring/Java/mColoringProblem.java @@ -0,0 +1,114 @@ + +public class mColoringProblem { + final int V = 4; + int color[]; + + /* A utility function to check if the current + color assignment is safe for vertex v */ + boolean isSafe(int v, int graph[][], int color[], + int c) + { + for (int i = 0; i < V; i++) + if (graph[v][i] == 1 && c == color[i]) + return false; + return true; + } + + /* A recursive utility function to solve m + coloring problem */ + boolean graphColoringUtil(int graph[][], int m, + int color[], int v) + { + /* base case: If all vertices are assigned + a color then return true */ + if (v == V) + return true; + + /* Consider this vertex v and try different + colors */ + for (int c = 1; c <= m; c++) + { + /* Check if assignment of color c to v + is fine*/ + if (isSafe(v, graph, color, c)) + { + color[v] = c; + + /* recur to assign colors to rest + of the vertices */ + if (graphColoringUtil(graph, m, + color, v + 1)) + return true; + + /* If assigning color c doesn't lead + to a solution then remove it */ + color[v] = 0; + } + } + + /* If no color can be assigned to this vertex + then return false */ + return false; + } + + /* This function solves the m Coloring problem using + Backtracking. It mainly uses graphColoringUtil() + to solve the problem. It returns false if the m + colors cannot be assigned, otherwise return true + and prints assignments of colors to all vertices. + Please note that there may be more than one + solutions, this function prints one of the + feasible solutions.*/ + boolean graphColoring(int graph[][], int m) + { + // Initialize all color values as 0. This + // initialization is needed correct functioning + // of isSafe() + color = new int[V]; + for (int i = 0; i < V; i++) + color[i] = 0; + + // Call graphColoringUtil() for vertex 0 + if (!graphColoringUtil(graph, m, color, 0)) + { + System.out.println("Solution does not exist"); + return false; + } + + // Print the solution + printSolution(color); + return true; + } + + /* A utility function to print solution */ + void printSolution(int color[]) + { + System.out.println("Solution Exists: Following" + + " are the assigned colors"); + for (int i = 0; i < V; i++) + System.out.print(" " + color[i] + " "); + System.out.println(); + } + + // driver program to test above function + public static void main(String args[]) + { + mColoringProblem Coloring = new mColoringProblem(); + /* Create following graph and test whether it is + 3 colorable + (3)---(2) + | / | + | / | + | / | + (0)---(1) + */ + int graph[][] = {{0, 1, 1, 1}, + {1, 0, 1, 0}, + {1, 1, 0, 1}, + {1, 0, 1, 0}, + }; + int m = 3; // Number of colors + Coloring.graphColoring(graph, m); + } +} + diff --git a/backtracking/m-coloring/Python/mColoring.py b/backtracking/m-coloring/Python/mColoring.py new file mode 100644 index 0000000000..648e6e1976 --- /dev/null +++ b/backtracking/m-coloring/Python/mColoring.py @@ -0,0 +1,48 @@ + + +class Graph(): + + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)]\ + for row in range(vertices)] + + # A utility function to check if the current color assignment + # is safe for vertex v + def isSafe(self, v, colour, c): + for i in range(self.V): + if self.graph[v][i] == 1 and colour[i] == c: + return False + return True + + # A recursive utility function to solve m + # coloring problem + def graphColourUtil(self, m, colour, v): + if v == self.V: + return True + + for c in range(1, m+1): + if self.isSafe(v, colour, c) == True: + colour[v] = c + if self.graphColourUtil(m, colour, v+1) == True: + return True + colour[v] = 0 + + def graphColouring(self, m): + colour = [0] * self.V + if self.graphColourUtil(m, colour, 0) == False: + return False + + # Print the solution + print "Solution exist and Following are the assigned colours:" + for c in colour: + print c, + return True + +# Driver Code +g = Graph(4) +g.graph = [[0,1,1,1], [1,0,1,0], [1,1,0,1], [1,0,1,0]] +m=3 +g.graphColouring(m) + + diff --git a/dp/EditDistance/Java/EDIST.java b/dp/EditDistance/Java/EDIST.java new file mode 100644 index 0000000000..a9dea8d2b8 --- /dev/null +++ b/dp/EditDistance/Java/EDIST.java @@ -0,0 +1,45 @@ + +class EDIST +{ + static int min(int x,int y,int z) + { + if (x<=y && x<=z) return x; + if (y<=x && y<=z) return y; + else return z; + } + + static int editDist(String str1 , String str2 , int m ,int n) + { + // If first string is empty, the only option is to + // insert all characters of second string into first + if (m == 0) return n; + + // If second string is empty, the only option is to + // remove all characters of first string + if (n == 0) return m; + + // If last characters of two strings are same, nothing + // much to do. Ignore last characters and get count for + // remaining strings. + if (str1.charAt(m-1) == str2.charAt(n-1)) + return editDist(str1, str2, m-1, n-1); + + // If last characters are not same, consider all three + // operations on last character of first string, recursively + // compute minimum cost for all three operations and take + // minimum of three values. + return 1 + min ( editDist(str1, str2, m, n-1), // Insert + editDist(str1, str2, m-1, n), // Remove + editDist(str1, str2, m-1, n-1) // Replace + ); + } + + public static void main(String args[]) + { + String str1 = "sunday"; + String str2 = "saturday"; + + System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) ); + } +} + diff --git a/dp/EditDistance/Python/EditDistance.py b/dp/EditDistance/Python/EditDistance.py new file mode 100644 index 0000000000..af4bc57786 --- /dev/null +++ b/dp/EditDistance/Python/EditDistance.py @@ -0,0 +1,34 @@ + +def editDistance(str1, str2, m , n): + + # If first string is empty, the only option is to + # insert all characters of second string into first + if m==0: + return n + + # If second string is empty, the only option is to + # remove all characters of first string + if n==0: + return m + + # If last characters of two strings are same, nothing + # much to do. Ignore last characters and get count for + # remaining strings. + if str1[m-1]==str2[n-1]: + return editDistance(str1,str2,m-1,n-1) + + # If last characters are not same, consider all three + # operations on last character of first string, recursively + # compute minimum cost for all three operations and take + # minimum of three values. + return 1 + min(editDistance(str1, str2, m, n-1), # Insert + editDistance(str1, str2, m-1, n), # Remove + editDistance(str1, str2, m-1, n-1) # Replace + ) + +# Driver program to test the above function +str1 = "sunday" +str2 = "saturday" +print editDistance(str1, str2, len(str1), len(str2)) + + diff --git a/dp/Lowest_Common_Ancestor/Java/LCA.java b/dp/Lowest_Common_Ancestor/Java/LCA.java new file mode 100644 index 0000000000..3081b77442 --- /dev/null +++ b/dp/Lowest_Common_Ancestor/Java/LCA.java @@ -0,0 +1,91 @@ +import java.util.ArrayList; +import java.util.List; + +class Node { + int data; + Node left, right; + + Node(int value) { + data = value; + left = right = null; + } +} + +public class BT_NoParentPtr_Solution1 +{ + + Node root; + private List path1 = new ArrayList<>(); + private List path2 = new ArrayList<>(); + + int findLCA(int n1, int n2) { + path1.clear(); + path2.clear(); + return findLCAInternal(root, n1, n2); + } + + private int findLCAInternal(Node root, int n1, int n2) { + + if (!findPath(root, n1, path1) || !findPath(root, n2, path2)) { + System.out.println((path1.size() > 0) ? "n1 is present" : "n1 is missing"); + System.out.println((path2.size() > 0) ? "n2 is present" : "n2 is missing"); + return -1; + } + + int i; + for (i = 0; i < path1.size() && i < path2.size(); i++) { + // System.out.println(path1.get(i) + " " + path2.get(i)); + if (!path1.get(i).equals(path2.get(i))) + break; + } + + return path1.get(i-1); + } + + private boolean findPath(Node root, int n, List path) + { + if (root == null) { + return false; + } + + path.add(root.data); + + if (root.data == n) { + return true; + } + + if (root.left != null && findPath(root.left, n, path)) { + return true; + } + + if (root.right != null && findPath(root.right, n, path)) { + return true; + } + + path.remove(path.size()-1); + + return false; + } + + public static void main(String[] args) + { + BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1(); + 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); + tree.root.right.left = new Node(6); + tree.root.right.right = new Node(7); + + System.out.println("LCA(4, 5): " + tree.findLCA(4,5)); + System.out.println("LCA(4, 6): " + tree.findLCA(4,6)); + System.out.println("LCA(3, 4): " + tree.findLCA(3,4)); + System.out.println("LCA(2, 4): " + tree.findLCA(2,4)); + /* System.out.println("LCA(4, 7): " + tree.findLCA(4,7)); + System.out.println("LCA(4, 8): " + tree.findLCA(4,8)); + System.out.println("LCA(1, 1): " + tree.findLCA(1,1)); */ + } +} +// This code is contributed by Sreenivasulu Rayanki. + diff --git a/dp/Lowest_Common_Ancestor/Python/lcs.py b/dp/Lowest_Common_Ancestor/Python/lcs.py new file mode 100644 index 0000000000..998fff8da7 --- /dev/null +++ b/dp/Lowest_Common_Ancestor/Python/lcs.py @@ -0,0 +1,72 @@ + +class Node: + # Constructor to create a new binary node + def __init__(self, key): + self.key = key + self.left = None + self.right = None + +# Finds the path from root node to given root of the tree. +# Stores the path in a list path[], returns true if path +# exists otherwise false +def findPath( root, path, k): + + # Baes Case + if root is None: + return False + + # Store this node is path vector. The node will be + # removed if not in path from root to k + path.append(root.key) + + # See if the k is same as root's key + if root.key == k : + return True + + # Check if k is found in left or right sub-tree + if ((root.left != None and findPath(root.left, path, k)) or + (root.right!= None and findPath(root.right, path, k))): + return True + + # If not present in subtree rooted with root, remove + # root from path and return False + + path.pop() + return False + +# Returns LCA if node n1 , n2 are present in the given +# binary tre otherwise return -1 +def findLCA(root, n1, n2): + + # To store paths to n1 and n2 fromthe root + path1 = [] + path2 = [] + + # Find paths from root to n1 and root to n2. + # If either n1 or n2 is not present , return -1 + if (not findPath(root, path1, n1) or not findPath(root, path2, n2)): + return -1 + + # Compare the paths to get the first different value + i = 0 + while(i < len(path1) and i < len(path2)): + if path1[i] != path2[i]: + break + i += 1 + return path1[i-1] + + +# Driver program to test above function +# Let's create the Binary Tree shown in above diagram +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.left.right = Node(5) +root.right.left = Node(6) +root.right.right = Node(7) + +print "LCA(4, 5) = %d" %(findLCA(root, 4, 5,)) +print "LCA(4, 6) = %d" %(findLCA(root, 4, 6)) +print "LCA(3, 4) = %d" %(findLCA(root,3,4)) +print "LCA(2, 4) = %d" %(findLCA(root,2, 4)) diff --git a/dp/egg_dropping_puzzle/Java/eggDropping.java b/dp/egg_dropping_puzzle/Java/eggDropping.java new file mode 100644 index 0000000000..ec54aa45a9 --- /dev/null +++ b/dp/egg_dropping_puzzle/Java/eggDropping.java @@ -0,0 +1,58 @@ + +class EggDrop +{ + // A utility function to get maximum of two integers + static int max(int a, int b) { return (a > b)? a: b; } + + /* Function to get minimum number of trials needed in worst + case with n eggs and k floors */ + static int eggDrop(int n, int k) + { + /* A 2D table where entery eggFloor[i][j] will represent minimum + number of trials needed for i eggs and j floors. */ + int eggFloor[][] = new int[n+1][k+1]; + int res; + int i, j, x; + + // We need one trial for one floor and0 trials for 0 floors + for (i = 1; i <= n; i++) + { + eggFloor[i][1] = 1; + eggFloor[i][0] = 0; + } + + // We always need j trials for one egg and j floors. + for (j = 1; j <= k; j++) + eggFloor[1][j] = j; + + // Fill rest of the entries in table using optimal substructure + // property + for (i = 2; i <= n; i++) + { + for (j = 2; j <= k; j++) + { + eggFloor[i][j] = Integer.MAX_VALUE; + for (x = 1; x <= j; x++) + { + res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]); + if (res < eggFloor[i][j]) + eggFloor[i][j] = res; + } + } + } + + // eggFloor[n][k] holds the result + return eggFloor[n][k]; + + } + + /* Driver program to test to pront printDups*/ + public static void main(String args[] ) + { + int n = 2, k = 10; + System.out.println("Minimum number of trials in worst case with "+n+" eggs and "+k+ + " floors is "+eggDrop(n, k)); + } +} + + diff --git a/dp/egg_dropping_puzzle/Python/EggDropping.py b/dp/egg_dropping_puzzle/Python/EggDropping.py new file mode 100644 index 0000000000..64b1bf1042 --- /dev/null +++ b/dp/egg_dropping_puzzle/Python/EggDropping.py @@ -0,0 +1,39 @@ + +INT_MAX = 32767 + +# Function to get minimum number of trials needed in worst +# case with n eggs and k floors +def eggDrop(n, k): + # A 2D table where entery eggFloor[i][j] will represent minimum + # number of trials needed for i eggs and j floors. + eggFloor = [[0 for x in range(k+1)] for x in range(n+1)] + + # We need one trial for one floor and0 trials for 0 floors + for i in range(1, n+1): + eggFloor[i][1] = 1 + eggFloor[i][0] = 0 + + # We always need j trials for one egg and j floors. + for j in range(1, k+1): + eggFloor[1][j] = j + + # Fill rest of the entries in table using optimal substructure + # property + for i in range(2, n+1): + for j in range(2, k+1): + eggFloor[i][j] = INT_MAX + for x in range(1, j+1): + res = 1 + max(eggFloor[i-1][x-1], eggFloor[i][j-x]) + if res < eggFloor[i][j]: + eggFloor[i][j] = res + + # eggFloor[n][k] holds the result + return eggFloor[n][k] + +# Driver program to test to pront printDups +n = 2 +k = 36 +print("Minimum number of trials in worst case with" + str(n) + "eggs and " + + str(k) + " floors is " + str(eggDrop(n, k))) + + diff --git a/dp/kadane-_algorithm/Java/kadane.java b/dp/kadane-_algorithm/Java/kadane.java new file mode 100644 index 0000000000..1aa8eb343f --- /dev/null +++ b/dp/kadane-_algorithm/Java/kadane.java @@ -0,0 +1,30 @@ +import java.io.*; + +import java.util.*; + +class kadane +{ + public static void main (String[] args) + { + int [] a = {-2, -3, 4, -1, -2, 1, 5, -3}; + System.out.println("Maximum contiguous sum is " + + maxSubArraySum(a)); + } + + static int maxSubArraySum(int a[]) + { + int size = a.length; + int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; + + for (int i = 0; i < size; i++) + { + max_ending_here = max_ending_here + a[i]; + if (max_so_far < max_ending_here) + max_so_far = max_ending_here; + if (max_ending_here < 0) + max_ending_here = 0; + } + return max_so_far; + } +} + diff --git a/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java b/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java new file mode 100644 index 0000000000..1861fe282a --- /dev/null +++ b/dp/longest_common_subsequence/Java/LongestCommonSubsequence.java @@ -0,0 +1,39 @@ + +public class LongestCommonSubsequence +{ + +/* Returns length of LCS for X[0..m-1], Y[0..n-1] */ +int lcs( char[] X, char[] Y, int m, int n ) +{ + if (m == 0 || n == 0) + return 0; + if (X[m-1] == Y[n-1]) + return 1 + lcs(X, Y, m-1, n-1); + else + return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); +} + +/* Utility function to get max of 2 integers */ +int max(int a, int b) +{ + return (a > b)? a : b; +} + +public static void main(String[] args) +{ + LongestCommonSubsequence lcs = new LongestCommonSubsequence(); + String s1 = "AGGTAB"; + String s2 = "GXTXAYB"; + + char[] X=s1.toCharArray(); + char[] Y=s2.toCharArray(); + int m = X.length; + int n = Y.length; + + System.out.println("Length of LCS is" + " " + + lcs.lcs( X, Y, m, n ) ); +} + +} + + diff --git a/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java b/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java new file mode 100644 index 0000000000..9b41f2a8e5 --- /dev/null +++ b/dp/longest_palidromic_subsequence/Java/LongestPalindromicSubsequence.java @@ -0,0 +1,46 @@ + +class LPS +{ + + // A utility function to get max of two integers + static int max (int x, int y) { return (x > y)? x : y; } + + // Returns the length of the longest palindromic subsequence in seq + static int lps(String seq) + { + int n = seq.length(); + int i, j, cl; + int L[][] = new int[n][n]; // Create a table to store results of subproblems + + // Strings of length 1 are palindrome of lentgh 1 + for (i = 0; i < n; i++) + L[i][i] = 1; + + + for (cl=2; cl<=n; cl++) + { + for (i=0; i +#include +using namespace std; + +// This function mainly returns LCS(str, str) +// with a condition that same characters at +// same index are not considered. +int findLongestRepeatingSubSeq(string str) +{ + int n = str.length(); + + // Create and initialize DP table + int dp[n+1][n+1]; + for (int i=0; i<=n; i++) + for (int j=0; j<=n; j++) + dp[i][j] = 0; + + // Fill dp table (similar to LCS loops) + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + // If characters match and indexes are + // not same + if (str[i-1] == str[j-1] && i != j) + dp[i][j] = 1 + dp[i-1][j-1]; + + // If characters do not match + else + dp[i][j] = max(dp[i][j-1], dp[i-1][j]); + } + } + return dp[n][n]; +} + +// Driver Program +int main() +{ + string str = "aabb"; + cout << "The length of the largest subsequence that" + " repeats itself is : " + << findLongestRepeatingSubSeq(str); + return 0; +} + diff --git a/dp/longest_repeating_subsequence/Java/LRS.java b/dp/longest_repeating_subsequence/Java/LRS.java new file mode 100644 index 0000000000..af1843e30f --- /dev/null +++ b/dp/longest_repeating_subsequence/Java/LRS.java @@ -0,0 +1,41 @@ + +import java.io.*; +import java.util.*; + +class LRS +{ + // Function to find the longest repeating subsequence + static int findLongestRepeatingSubSeq(String str) + { + int n = str.length(); + + // Create and initialize DP table + int[][] dp = new int[n+1][n+1]; + + // Fill dp table (similar to LCS loops) + for (int i=1; i<=n; i++) + { + for (int j=1; j<=n; j++) + { + // If characters match and indexes are not same + if (str.charAt(i-1) == str.charAt(j-1) && i!=j) + dp[i][j] = 1 + dp[i-1][j-1]; + + // If characters do not match + else + dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]); + } + } + return dp[n][n]; + } + + // driver program to check above function + public static void main (String[] args) + { + String str = "aabb"; + System.out.println("The length of the largest subsequence that" + +" repeats itself is : "+findLongestRepeatingSubSeq(str)); + } +} + + diff --git a/graph/Java/BFS.java b/graph/Java/BFS.java new file mode 100644 index 0000000000..1a9b664e1c --- /dev/null +++ b/graph/Java/BFS.java @@ -0,0 +1,81 @@ + +import java.io.*; +import java.util.*; + +// This class represents a directed graph using adjacency list +// representation +class Graph +{ + private int V; // No. of vertices + private LinkedList adj[]; //Adjacency Lists + + // Constructor + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i queue = new LinkedList(); + + // Mark the current node as visited and enqueue it + visited[s]=true; + queue.add(s); + + while (queue.size() != 0) + { + // Dequeue a vertex from queue and print it + s = queue.poll(); + System.out.print(s+" "); + + // Get all adjacent vertices of the dequeued vertex s + // If a adjacent has not been visited, then mark it + // visited and enqueue it + Iterator i = adj[s].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + { + visited[n] = true; + queue.add(n); + } + } + } + } + + // Driver method to + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Breadth First Traversal "+ + "(starting from vertex 2)"); + + g.BFS(2); + } +} + diff --git a/graph/Java/DFS.java b/graph/Java/DFS.java new file mode 100644 index 0000000000..9a756679f2 --- /dev/null +++ b/graph/Java/DFS.java @@ -0,0 +1,74 @@ + +import java.io.*; +import java.util.*; + +// This class represents a directed graph using adjacency list +// representation +class Graph +{ + private int V; // No. of vertices + + // Array of lists for Adjacency List Representation + private LinkedList adj[]; + + // Constructor + Graph(int v) + { + V = v; + adj = new LinkedList[v]; + for (int i=0; i i = adj[v].listIterator(); + while (i.hasNext()) + { + int n = i.next(); + if (!visited[n]) + DFSUtil(n, visited); + } + } + + // The function to do DFS traversal. It uses recursive DFSUtil() + void DFS(int v) + { + // Mark all the vertices as not visited(set as + // false by default in java) + boolean visited[] = new boolean[V]; + + // Call the recursive helper function to print DFS traversal + DFSUtil(v, visited); + } + + public static void main(String args[]) + { + Graph g = new Graph(4); + + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + System.out.println("Following is Depth First Traversal "+ + "(starting from vertex 2)"); + + g.DFS(2); + } +} + diff --git a/graph/Python/BFS.py b/graph/Python/BFS.py new file mode 100644 index 0000000000..bdc3775d87 --- /dev/null +++ b/graph/Python/BFS.py @@ -0,0 +1,60 @@ + +from collections import defaultdict + +# This class represents a directed graph using adjacency +# list representation +class Graph: + + # Constructor + def __init__(self): + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self,u,v): + self.graph[u].append(v) + + # Function to print a BFS of graph + def BFS(self, s): + + # Mark all the vertices as not visited + visited = [False]*(len(self.graph)) + + # Create a queue for BFS + queue = [] + + # Mark the source node as visited and enqueue it + queue.append(s) + visited[s] = True + + while queue: + + # Dequeue a vertex from queue and print it + s = queue.pop(0) + print s, + + # Get all adjacent vertices of the dequeued + # vertex s. If a adjacent has not been visited, + # then mark it visited and enqueue it + for i in self.graph[s]: + if visited[i] == False: + queue.append(i) + visited[i] = True + + +# Driver code +# Create a graph given in the above diagram +g = Graph() +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) + +print "Following is Breadth First Traversal (starting from vertex 2)" +g.BFS(2) + + + diff --git a/graph/Python/DFS.py b/graph/Python/DFS.py new file mode 100644 index 0000000000..beeaec7f6d --- /dev/null +++ b/graph/Python/DFS.py @@ -0,0 +1,56 @@ + +from collections import defaultdict + +# This class represents a directed graph using +# adjacency list representation +class Graph: + + # Constructor + def __init__(self): + + # default dictionary to store graph + self.graph = defaultdict(list) + + # function to add an edge to graph + def addEdge(self,u,v): + self.graph[u].append(v) + + # A function used by DFS + def DFSUtil(self,v,visited): + + # Mark the current node as visited and print it + visited[v]= True + print v, + + # Recur for all the vertices adjacent to this vertex + for i in self.graph[v]: + if visited[i] == False: + self.DFSUtil(i, visited) + + + # The function to do DFS traversal. It uses + # recursive DFSUtil() + def DFS(self,v): + + # Mark all the vertices as not visited + visited = [False]*(len(self.graph)) + + # Call the recursive helper function to print + # DFS traversal + self.DFSUtil(v,visited) + + +# Driver code +# Create a graph given in the above diagram +g = Graph() +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) + +print "Following is DFS from (starting from vertex 2)" +g.DFS(2) + + diff --git a/greedy/huffman_coding/Java/HuffmanCoding.java b/greedy/huffman_coding/Java/HuffmanCoding.java new file mode 100644 index 0000000000..e2063a1465 --- /dev/null +++ b/greedy/huffman_coding/Java/HuffmanCoding.java @@ -0,0 +1,137 @@ +import java.util.PriorityQueue; +import java.util.Scanner; +import java.util.Comparator; + +// node class is the basic structure +// of each node present in the huffman - tree. +class HuffmanNode { + + int data; + char c; + + HuffmanNode left; + HuffmanNode right; +} + +// comparator class helps to compare the node +// on the basis of one of its attribute. +// Here we will be compared +// on the basis of data values of the nodes. +class MyComparator implements Comparator { + public int compare(HuffmanNode x, HuffmanNode y) + { + + return x.data - y.data; + } +} + +public class Huffman { + + // recursive function to print the + // huffman-code through the tree traversal. + // Here s is the huffman - code generated. + public static void printCode(HuffmanNode root, String s) + { + + // base case; if the left and right are null + // then its a leaf node and we print + // the code s generated by traversing the tree. + if (root.left + == null + && root.right + == null + && Character.isLetter(root.c)) { + + // c is the character in the node + System.out.println(root.c + ":" + s); + + return; + } + + // if we go to left then add "0" to the code. + // if we go to the right add"1" to the code. + + // recursive calls for left and + // right sub-tree of the generated tree. + printCode(root.left, s + "0"); + printCode(root.right, s + "1"); + } + + // main function + public static void main(String[] args) + { + + Scanner s = new Scanner(System.in); + + // number of characters. + int n = 6; + char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' }; + int[] charfreq = { 5, 9, 12, 13, 16, 45 }; + + // creating a priority queue q. + // makes a min-priority queue(min-heap). + PriorityQueue q + = new PriorityQueue(n, new MyComparator()); + + for (int i = 0; i < n; i++) { + + // creating a huffman node object + // and adding it to the priority-queue. + HuffmanNode hn = new HuffmanNode(); + + hn.c = charArray[i]; + hn.data = charfreq[i]; + + hn.left = null; + hn.right = null; + + // add functions adds + // the huffman node to the queue. + q.add(hn); + } + + // create a root node + HuffmanNode root = null; + + // Here we will extract the two minimum value + // from the heap each time until + // its size reduces to 1, extract until + // all the nodes are extracted. + while (q.size() > 1) { + + // first min extract. + HuffmanNode x = q.peek(); + q.poll(); + + // second min extarct. + HuffmanNode y = q.peek(); + q.poll(); + + // new node f which is equal + HuffmanNode f = new HuffmanNode(); + + // to the sum of the frequency of the two nodes + // assigning values to the f node. + f.data = x.data + y.data; + f.c = '-'; + + // first extracted node as left child. + f.left = x; + + // second extracted node as the right child. + f.right = y; + + // marking the f node as the root node. + root = f; + + // add this node to the priority-queue. + q.add(f); + } + + // print the codes by traversing the tree + printCode(root, ""); + } +} + +// This code is contributed by Kunwar Desh Deepak Singh +