filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.go | /* Part of Cosmos by OpenGenus Foundation */
package main
import "fmt"
/*
Expect Output
The length of LCS of ABCDEFGHIJKLMNOPQRABCEDG adn DEFNMJABCDEG is 9
*/
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
func LCS(str1, str2 string) int {
len1 := len(str1)
len2 := len(str2)
dp := make([]... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.java | // Part of Cosmos by OpenGenus Foundation
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 ) {
int L[][] = new int[m+1][n+1];
//L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++) {
for ... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.php | <?php
function longestCommonSubsequence($x , $y)
{
$x_len = strlen($x);
$y_len = strlen($y) ;
for ($i = 0; $i <= $x_len; $i++)
{
for ($j = 0; $j <= $y_len; $j++)
{
if ($i == 0 || $j == 0)
$dp[$i][$j] = 0;
else if ($x[$i - 1] == $y[$j - ... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.py | # Part of Cosmos by OpenGenus Foundation
def lcs(X, Y):
m = len(X)
n = len(Y)
dp = [[0] * (n + 1) for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif X[i - 1] == Y[j - 1]:
dp[i][j] = d... |
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence_rec.java | // Part of Cosmos by OpenGenus Foundation
class LongestCommonSubsequenceRec {
int lcs( char[] X, char[] Y, int m, int n) {
if (m == 0 || n == 0) { // base case
return 0;
}
if (X[m-1] == Y[n-1]) { // if common element is found increase lcs length by 1
return 1 + lcs(X, Y, m-1, n-1);
} else { // rec... |
code/dynamic_programming/src/longest_common_subsequence_substring/longest_common_subsequence_substring_problem.cpp | // This is a new dynamic programming problem. I have published a research paper
// about this problem under the guidance of Professor Rao Li (University of
// South Carolina, Aiken) along with my friend. The paper has been accepted by
// the Journal of Mathematics and Informatics.The problem is a variation of the
// st... |
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring.java | // Space Complexity: O(n)
// Time Complexity: O(m*n)
import java.util.*;
public class Longest_Common_Substring {
static String LongestCommonSubstring(String str1, String str2) {
String temp;
// longest string is str1 and the smallest string is str2
if (str2.length() > str1.length()){
... |
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring.py | def LongestCommonSubstring(
string1,
string2
):
# longest string is string1 and the smallest string is string2
if len(string2) > len(string1):
temp = string2
string2 = string1
string1 = temp
m = len(string1)
n = len(string2)
consqRow = []
for i in range(2):
... |
code/dynamic_programming/src/longest_common_substring/Longest_Common_Substring_rename.cpp | // Space Complexity: O(n)
// Time Complexity: O(m*n)
#include <iostream>
#include <vector>
std::string LongestCommonSubstring(std::string string1, std::string string2)
{
std::string temp;
// longest string is string1 and the smallest string is string2
if (string2.size() > string1.size())
{
tem... |
code/dynamic_programming/src/longest_common_substring/longest_common_substring_2.cpp | /*
* Part of Cosmos by OpenGenus Foundation
* finding longest common substring between two strings by dynamic programming
*/
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
int longestCommonSubString(string s1, string s2)
{
int T[600][600]; //array lengt... |
code/dynamic_programming/src/longest_increasing_subsequence/README.md | # Longest Increasing Subsequence
## Description
Given an array of integers `A`, find the length of the longest subsequence such
that all the elements in the subsequence are sorted in increasing order.
Examples:
The lenght of LIS for `{3, 10, 2, 1, 20}` is 3, that is `{3, 10, 20}`.
The lenght of LIS for `{10, 22, 9... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.c | /* Part of Cosmos by OpenGenus Foundation */
// LIS implementation in C
#include<stdio.h>
// Max function
int
max(int a, int b)
{
return (a > b ? a : b);
}
// O(n^2) approach
int
lis(int arr[], int n)
{
int dp[n], ans = 0 , i = 0, j = 0;
for (i = 0; i < n; ++i) {
dp[i] = 1;
for (j = 0;... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Bottom-up O(n^2) approach
int lis(int v[], int n)
{
int dp[n], ans = 0;
for (int i = 0; i < n; ++i)
{
dp[i] = 1;
for (int j = 0; j < i; ++j)
if (v[j... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.go | /* Part of Cosmos by OpenGenus Foundation */
package main
import "fmt"
/*
Expteced output
The length of longest_increasing_subsequece in [10 23 5 81 36 37 12 38 51 92] is 7
*/
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
//O(n^2) approach
func LIS(data []int) int {
dp := make([]int, len(d... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.java | /* Part of Cosmos by OpenGenus Foundation */
import java.lang.Math;
class LIS
{
// returns size of the longest increasing subsequence within the given array
// O(n^2) approach
static int lis(int arr[], int n)
{
int dp[] = new int[n];
int ans = 0;
for(int i=0; i<n; i++)
{
dp[i] = 1;
for(int j=0; j... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Method that returns the length of the Longest Increasing Subsequence for the input array
* @param {array} inputArray
*/
function longestIncreasingSubsequence(inputArray) {
// Get the length of the array
let arrLength = inputArray.length;
let i, j;
let... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence.py | """LIS implementation in Python"""
# Part of Cosmos by OpenGenus Foundation
# Time Complexity: O(nlogn)
def length_of_lis(nums):
"""Return the length of the Longest increasing subsequence"""
tails = [0] * len(nums)
size = 0
for x in nums:
i, j = 0, size
while i != j:
m = int... |
code/dynamic_programming/src/longest_increasing_subsequence/longest_increasing_subsequence_using_segment_tree.cpp | /* Part of Cosmos by OpenGenus Foundation */
// Finding the Longest Increasing Subsequence using Segment Tree
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
// function to compare two pairs
int compare(pair<int, int> p1, pair<int, int> p2)
{
... |
code/dynamic_programming/src/longest_independent_set/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/longest_palindromic_sequence/README.md | # Longest Palindromic Sequence
## Description
Given a string `S`, find the length of the longest subsequence of `S` that is also a palindrome.
Examples:
The length of the longest palindromic sequence of `bbabcbcab` is 7 (`babcbab` or `bacbcab`).
The length of the longest palindromic sequence of `abbaab` is 4 (`abb... |
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.c | /*
* Part of Cosmos by OpenGenus Foundation
* @Author: Ayush Garg
* @Date: 2017-10-13 23:11:52
* @Last Modified by: Ayush Garg
* @Last Modified time: 2017-10-13 23:23:10
*/
#include <stdio.h>
#include <string.h>
#define MAX 1010
int dp[MAX][MAX]; // used to memoize
// utility function to get max
int max(int... |
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1010;
int memo[MAX][MAX]; // used to store subproblems answers
/**
* Return the longest palindromic subsequence
* in s[i...j] in a top-down approach.
* Time complexity: O(n^2), n = length ... |
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.js | /* Part of Cosmos by OpenGenus Foundation */
function longest_palindrome(str) {
let longest = []; // A table to store results of subproblems
// Strings of length 1 are palindrome of lentgh 1
for (let i = 0; i < str.length; i++) {
(longest[i] = longest[i] || [])[i] = 1;
}
for (let cl = 2; cl <= str.leng... |
code/dynamic_programming/src/longest_palindromic_sequence/longest_palindromic_sequence.py | # Part of Cosmos by OpenGenus Foundation
def longest_palindrome(text):
""" Find the maximum length of a palindrome subsequence
Dynamic Programming approach on solving the longest palindromic sequence.
Time complexity: O(n^2), n = length of text.
Args:
text: string which will be processed
... |
code/dynamic_programming/src/longest_palindromic_substring/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/longest_palindromic_substring/longest_palindromic_substring.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string>
using namespace std;
int longestPalSubstr(string str)
{
int n = str.size();
bool ispal[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
ispal[i][j] = false;
// All substrings of len... |
code/dynamic_programming/src/longest_palindromic_substring/longest_palindromic_substring.py | def longest_pal(test_num):
num = str(test_num)
# booleanArray with [start][end]
pal_boolean_array = [[False for e in range(len(num))] for s in range(len(num))]
# all one-letter substrings are palindromes
for s in range(len(num)): # length one substrings are all palindromes
pal_boolean_array... |
code/dynamic_programming/src/longest_repeating_subsequence/longest_repeating_subsequence.cpp | // Part of Cosmos by OpenGenus Foundation
//dynamic programming || Longest repeating subsequence
#include <iostream>
#include <string>
#include <vector>
int longestRepeatingSubsequence(std::string s)
{
int n = s.size(); // Obtaining the length of the string
std::vector<std::vector<int>>dp(n + 1, std::vector... |
code/dynamic_programming/src/matrix_chain_multiplication/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
#define inf_ll 2000000000000000000LL
#define inf 1000000000
#define eps 1e-8
#define mod 1000000007
#define ff first
#define ss second
#define N 3456789
typedef long long int ll;
ll dp[987][987];
ll ar[N];
/*
Matrix Chain Multiplication Problem
You are ... |
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.cpp | #include <climits>
#include <cstdio>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
int MatrixChainOrder(int p[], int n)
{
/* For simplicity of the program, one extra row and one
* extra column are allocated in m[][]. 0th row and 0th
... |
code/dynamic_programming/src/matrix_chain_multiplication/matrix_chain_multiplication.py | # Part of Cosmos by OpenGenus Foundation
# Dynamic Programming Python implementation of Matrix Chain Multiplication.
import sys
import numpy as np
# Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
def MatrixChainOrder(p, n):
m = [[0 for x in range(n)] for x in range(n)]
for i in range(1, n):
m[i][i]... |
code/dynamic_programming/src/matrix_chain_multiplication/matrixchainmultiplication.java | // Dynamic Programming Python implementation of Matrix
// Chain Multiplication.
// Part of Cosmos by OpenGenus Foundation
class MatrixChainMultiplication
{
// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n
static int MatrixChainOrder(int p[], int n)
{
/* For simplicity of the program, one extra ... |
code/dynamic_programming/src/maximum_product_subarray/maximum_product_subarray.cpp | /*
Read Problem Description Here - https://leetcode.com/problems/maximum-product-subarray/
Test Cases -
Input: [2,3,-2,4]
Output: 6
Input: [-2,0,-1]
Output: 0
*/
#include<iostream>
#include<climits>
using namespace std;
int maxProdSub(int* arr, int n)
{
int positiveProd = 1, negativeProd = 1;
int ans = INT_MI... |
code/dynamic_programming/src/maximum_subarray_sum/maximum_subarray_sum.cpp | #include <bits/stdc++.h>
using namespace std;
int maxSubArraySum(int a[], int size)
{ // kedane algorithm
int max_sum = INT_MIN, current_sum = 0;
for (int i = 0; i < size; i++)
{
current_sum = current_sum + a[i];
if (max_sum < current_sum)
max_sum = current_sum;
if (cu... |
code/dynamic_programming/src/maximum_sum_increasing_subsequence/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/maximum_sum_increasing_subsequence/maximum_sum_increasing_subsequence.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
int
maxSum(int arr[], int n)
{
int i, j, max = 0;
int MSis[n];
for (i = 0; i <= n; i++)
MSis[i] = arr[i];
/* Compute maximum sum values in bottom up manner */
for (i = 1; i < n; i++)
for(j = 0; j < i; j++)
if(arr[j] < ... |
code/dynamic_programming/src/maximum_sum_increasing_subsequence/maximum_sum_increasing_subsequence.cpp | #include <bits/stdc++.h>
#include <vector>
using namespace std;
int maxSum(int arr[], int n){
int i, j, max = 0;
vector<int> dp(n);
for (i = 0; i < n; i++){
dp[i] = arr[i];
}
for (i = 1; i < n; i++ ){
for (j = 0; j < i; j++ ){
if (arr[i] > arr[j] && dp[i] < dp[j] + arr[i]){
dp[i] = dp[j] + arr[i];
... |
code/dynamic_programming/src/maximum_sum_sub_matrix/maximum_sum_sub_matrix.cpp | // Part of Cosmos by OpenGenus Foundation
// Author: Karan Chawla
// 15th Oct '17
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
//Utility function to apply kadane's algorithm
//Returns the maximum sub in an array
int kadane(vector<int> &nums, int &start)
{
//Initialize variables
... |
code/dynamic_programming/src/maximum_sum_sub_matrix/maximum_sum_sub_matrix.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.*;
import java.lang.*;
import java.io.*;
/**
* Given a 2D array, find the maximum sum subarray in it
*/
public class MaximumSubMatrixSum
{
public static void main (String[] args) throws java.lang.Exception
{
findMaxSubMatrix(new int[][] ... |
code/dynamic_programming/src/maximum_weight_independent_set_of_path_graph/maximum_weight_independent_set_of_path_graph.cpp | #include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the number of vertices of the path graph : ";
cin >> n;
int g[n];
cout << "Enter the vertices of the graph : ";
for (int i = 0; i < n; i++)
cin >> g[i];
int sol[n + 1];
sol[0] = 0;
sol[1] = g[0];
... |
code/dynamic_programming/src/min_cost_path/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/min_cost_path/min_cost_path.c | #include <stdio.h>
#define ROWS 3
#define COLUMNS 3
int
min(int x, int y, int z)
{
if (x < y)
return ((x < z)? x : z);
else
return ((y < z)? y : z);
}
int
minCost(int cost[ROWS][COLUMNS], int m, int n)
{
int i, j;
int travellingCost[ROWS][COLUMNS];
travellingCost[0][0] = cost[... |
code/dynamic_programming/src/min_cost_path/min_cost_path.cpp | #include <cstdio>
using namespace std;
#define R 3
#define C 3
// Part of Cosmos by OpenGenus Foundation
int min(int x, int y, int z);
int minCost(int cost[R][C], int m, int n)
{
int i, j;
// Instead of following line, we can use int tc[m+1][n+1] or
// dynamically allocate memoery to save space. The follo... |
code/dynamic_programming/src/min_cost_path/min_cost_path.java | // Part of Cosmos by OpenGenus Foundation
// Given a cost matrix and calculate the minimum cost path to reach (m, n)
// from (0, 0)
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class MinCostPath {
static int minCost(int costMatrix[][], int m, int n) {
int i,j;
int tc[][] = new ... |
code/dynamic_programming/src/min_cost_path/min_cost_path.py | # Part of Cosmos by OpenGenus Foundation
def minCost(costMatrix, m, n, traceback=True):
"""Given a cost matrix and calculate the minimum cost path to reach (m, n)
from (0, 0).
"""
tc = [[0 for x in range(m + 1)] for y in range(n + 1)]
tc[0][0] = costMatrix[0][0]
# Initialize first column o... |
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.go | import "fmt"
func main() {
fmt.Println(minTimeToVisitAllPoints([][]int{{1, 1}, {3, 4}, {-1, 0}}))
fmt.Println(minTimeToVisitAllPoints([][]int{{3, 2}, {-2, 2}}))
}
func minTimeToVisitAllPoints(points [][]int) int {
n := len(points)
if n == 0 {
return 0
}
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i]... |
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.java | class DPprob {
public int minSkips(int[] A, int s, int target) {
int n = A.length, dp[] = new int[n + 1];
for (int i = 0; i < n; ++i) {
for (int j = n; j >= 0; --j) {
dp[j] += A[i];
if (i < n - 1)
dp[j] = (dp[j] + s - 1) / s * s; // tak... |
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/Minimum Skips to Arrive at Meeting On Time.py | def minSkips(self, A, s, target):
n = len(A)
dp = [0] * (n + 1)
for i, a in enumerate(A):
for j in range(n, -1, -1):
dp[j] += a
if i < n - 1:
dp[j] = (dp[j] + s - 1) / s * s
if j:
dp[j] = min(dp[j], dp[j - 1] + a)
for i in range... |
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/README.md | # Minimum Rests Skipped to Reach on Time
## Description
You have to travel to your office in `reachTime` time by travelling on `n` roads given as array `dist` where `dist[i]` is the length of ith road. You have a constant speed `Speed`. After you travel road `i`, you must rest and wait for the next integer hour befor... |
code/dynamic_programming/src/min_rests_skipped_to_reach_on_time/min_skips.cpp | // Part of Cosmos by OpenGenus Foundation
#include<bits/stdc++.h>
int minSkips(vector<int>& dist, int speed, int reachTime)
{
/*
dist: array containing lengths of roads
speed: the constant speed of travel
reachTime: the time before/at which you have to reach the office.
You start at time=0.
... |
code/dynamic_programming/src/minimum_cost_polygon_triangulation/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/minimum_insertion_palindrome/minimum_insertions_palindrome_using_lcs.cpp | /* Part of Cosmos by OpenGenus Foundation */
//Number of insertion required to make a string palindrome using dynamic programming
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int LCS(char *s, string r, int n, int m)
{
int d[n + 1][m + 1];//d[i][j] contains length of LCS of s[0.... |
code/dynamic_programming/src/newman_conway/newman_conway_dp.cpp | #include <iostream>
class NewmanConwaySequence
{
public:
NewmanConwaySequence(unsigned int n) : n(n) {}
void calculateNewmanConwaySequenceTermDP(bool flag);
private:
unsigned int n;
};
void NewmanConwaySequence::calculateNewmanConwaySequenceTermDP(bool flag)
{
if(flag == true)
{
unsigned i... |
code/dynamic_programming/src/no_consec_ones/README.md | # Cosmos
## No Consecutive Ones
### Problem Statement
```
Given a length `n`, determine the number of binary strings of length `n` that have no consecutive ones.
For example, for `n=3`, the strings of length `3` that have no consecutive ones are `000,001,010,100,101`,
so the algorithm would return `5`.
Expected t... |
code/dynamic_programming/src/no_consec_ones/no_consec_1.cpp | #include <iostream>
#include <vector>
using namespace std;
int countNonConsecutiveOnes(int n)
{
vector<int> endingZero(n), endingOne(n);
endingZero[0] = endingOne[0] = 1;
for (int i = 1; i < n; i++)
{
endingZero[i] = endingZero[i - 1] + endingOne[i - 1];
endingOne[i] = endingZero[i - 1]... |
code/dynamic_programming/src/no_consec_ones/no_consec_ones.py | # Part of Cosmos by Open Genus Foundation
# Code contributed by Shamama Zehra
# A dynamic programming solution for no Conseuctive Ones in Binary String problem
def noConsecOnes(n):
a = [0 for x in range(n)] # number of strings ending with 0
b = [0 for x in range(n)] # number of strings ending with 1
a... |
code/dynamic_programming/src/number_of_dice_rolls_with_target_sum/NumberOfDiceRollsWithTargetSum.java | public class NumberOfDiceRollsWithTargetSum {
public static void main(String[] args) {
// Test case 1
System.out.println(numRollsToTarget(1, 6, 3)); // it should output 1
// Test case 2
System.out.println(numRollsToTarget(30, 30, 500)); //it should output 222616187
}
... |
code/dynamic_programming/src/number_of_substring_divisible_by_8_but_not_3/README.md | # Number of substrings divisible by 8 but not 3
We are interested to find number of substrings of a given string which are divisible by 8 but not 3.
For example, in "556", possible substrings are "5", "6", "55", "56" and "556". Amongst which only 56 is divisible by 8 and is not divisible by 3. Therefore, answer should ... |
code/dynamic_programming/src/number_of_substring_divisible_by_8_but_not_3/number_of_substrings.cpp | #include <bits/stdc++.h>
using namespace std;
int no_of_substr(string str, int len, int k)
{
int count = 0;
// iterate over the string
for (int i = 0; i < len; i++) {
int n = 0;
// consider every substring starting from index 'i'
for (int j = i; j < len; j++) {
... |
code/dynamic_programming/src/numeric_keypad_problem/numeric_keypad_problem.cpp | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> nums;
void populate()
{
nums.resize(10);
nums[0].push_back(0);
nums[0].push_back(8);
nums[1].push_back(1);
nums[1].push_back(2);
nums[1].push_back(4);
nums[2].push_back(1);
nums[2].push_back(2);
nums[2].push_back(3);... |
code/dynamic_programming/src/optimal_binary_search_tree/optimal_bst.py | # Given keys and frequency, calculate the most optimal binary search tree that can be created making use of minimum cost
keys = list(map(int, input("Enter the list of keys").split()))
freq = list(map(int, input("Enter the list of frequencies").split()))
z = []
n = len(keys)
for i in range(n):
z += [[keys[i], freq[... |
code/dynamic_programming/src/palindrome_partition/README.md | # Palindrome Partitioning
## Description
Given a string `S`, determine the minimum number of cuts necessary to partition `S` in a set of palindromes.
For example, for string `aaabbba`, minimum cuts needed is `1`, making `aa | abba`.
## Solution
First we need to know for each substring of `S`, whether it is a pali... |
code/dynamic_programming/src/palindrome_partition/palindrome_partition.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <cstring>
#include <string>
#define MAX 1010
using namespace std;
int isPal[MAX][MAX], memo[MAX];
/*
* Checks if s[i...j] is palindrome
* in a top-down fashion. Result is
* stored in isPal matrix.
* Time complexity: O(n^2)
*/
int is... |
code/dynamic_programming/src/palindrome_partition/palindrome_partition.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Method which returns the Minimum Cuts to perform Palindrome Partioning
* @param {string} inputString
*/
function palindromePartioning(inputString) {
// Get the length of the string
let strLength = inputString.length;
let minCuts = 0;
let i, L, j;
/*... |
code/dynamic_programming/src/rod_cutting/README.md | # Rod Cutting
Given a rod of length n units and an array of prices p<sub>i</sub> for rods of length i = 1, 2, . . . ,n. Determine the maximum revenue r <sub>n</sub> obtainable by cutting the rod and selling the pieces.
## Explanation
Let the table of prices be -
length (i) | 1|2|3|4|5|6|7|8|9|10
-----------|--|... |
code/dynamic_programming/src/rod_cutting/rod_cutting.c | #include <stdio.h>
#define INT_MIN -32767
#define max(a, b) (((a) > (b)) ? (a) : (b))
int
cutRod(int price[], int length_of_rod)
{
if (length_of_rod <= 0)
return (0);
int max_val = INT_MIN, i;
for (i = 0; i < length_of_rod; i++)
max_val = max(max_val, price[i] + cutRod(price, length_of_rod ... |
code/dynamic_programming/src/rod_cutting/rod_cutting.cpp | #include <iostream>
#include <vector>
// Part of Cosmos by OpenGenus Foundation
// Use bottom-up DP, O(n^2) time, O(n) space.
using namespace std;
int rodCutting(int rod_length, vector<int> prices)
{
vector<int> best_price(rod_length + 1, 0);
best_price[0] = 0;
for (int i = 1; i <= rod_length; ++i)
{
... |
code/dynamic_programming/src/rod_cutting/rod_cutting.go | // Part of Cosmos by OpenGenus Foundation
// Code contributed by Marc Tibbs
// A Dynamic Programming solution for Rod Cutting problem
package main
import (
"fmt"
"math"
)
const min float64 = -1 << 63
func rodCut(price []float64, n int) float64 {
val := []float64{0}
val = append(val, price...)
for i := 1; i <... |
code/dynamic_programming/src/rod_cutting/rod_cutting.hs | import Data.Array
rodCutting :: Int -> [Int] -> Int
-- Part of Cosmos by OpenGenus Foundation
-- NOTE: great article on lazy DP http://jelv.is/blog/Lazy-Dynamic-Programming/
rodCutting x priceList | x < 0 = 0
| otherwise = r!x
where priceArray = listArray (0, length priceList) priceList --... |
code/dynamic_programming/src/rod_cutting/rod_cutting.py | # Part of Cosmos by OpenGenus Foundation
# Code contributed by Debajyoti Halder
# A Dynamic Programming solution for Rod cutting problem
INT_MIN = -32767
def cutRod(price, n):
val = [0 for x in range(n + 1)]
val[0] = 0
for i in range(1, n + 1):
max_val = INT_MIN
for j in range(i):
... |
code/dynamic_programming/src/shortest_common_supersequence/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/shortest_common_supersequence/scs.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.*;
import java.lang.*;
import java.io.*;
/* A DP based program to find length
of the shortest supersequence */
public class SCS {
// Returns length of the shortest supersequence of X and Y
static int superSequence(String X, String Y, int m, ... |
code/dynamic_programming/src/shortest_common_supersequence/shortest_common_supersequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1010;
int memo[MAX][MAX]; // used for memoization
// Function to find length of shortest common supersequence
// between sequences X[0..m-1] and Y[0..n-1]
int SCSLength(string& X, string& Y, int... |
code/dynamic_programming/src/shortest_common_supersequence/shortest_common_supersequence.py | # Part of Cosmos by OpenGenus Foundation
# shortest common supersequence using dp
def min(a, b):
if a > b:
return b
else:
return a
def superSeq(X, Y, m, n):
dp = []
for i in range(m + 1):
l2 = []
for j in range(n + 1):
if not (i):
l2.append(... |
code/dynamic_programming/src/subset_sum/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/subset_sum/subset_sum.cpp | /* Part of Cosmos by OpenGenus Foundation */
#ifndef SUBSET_SUM
#define SUBSET_SUM
#include <iterator>
/*
* Check whether is possible to
* get value sum from a subset
* of the [begin:end)
*/
// complexity: time: O(sum * n), space: O(sum)
template<typename _BidirectionalIter,
typename _ValueType = typ... |
code/dynamic_programming/src/subset_sum/subset_sum.go | /* Part of Cosmos by OpenGenus Foundation */
package main
import "fmt"
const TargetSize int = 200
/*
Expected Output:
Current subset is [1 4 8 9 34 23 17 32]
We can't get sum 113 from set
We can get sum 9 from set
We can't get sum 15 from set
We can't get sum 20 from set
We can get sum 31 from set
*/
func subSetSum(... |
code/dynamic_programming/src/subset_sum/subset_sum.java | /* Part of Cosmos by OpenGenus Foundation */
// A Java programm for subset sum problem using Dynamic Programming.
class subset_sum
{
static boolean isSubsetSum(int set[], int n, int sum)
{
boolean subset[][] = new boolean[sum+1][n+1];
for (int i = 0; i <= n; i++)
subset[0][i] = true;
for (int i = 1... |
code/dynamic_programming/src/subset_sum/subset_sum.py | # Part of Cosmos by OpenGenus Foundation
def can_get_sum(items, target):
dp = (target + 1) * [False]
reachable = (target + 1) * [0]
reachable[0] = 0
dp[0] = True
reachable[1] = 1
i = 0
q = 1
while i < len(items) and not dp[target]:
aux = q
for j in range(0, aux):
... |
code/dynamic_programming/src/tiling_problem/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/tiling_problem/tiling_problem.c | #include <stdio.h>
long long int
tiling(int n)
{
long long int tile[n + 1];
int i;
tile[0] = 1;
tile[1] = 1;
tile[2] = 2;
for (i = 3; i <= n; i++)
tile[i] = tile[i - 1] + tile[i - 2];
return (tile[n]);
}
int
main()
{
int n;
printf("Enter Number of tiles: ");
scanf("%d", &n);
printf("Number of wa... |
code/dynamic_programming/src/tiling_problem/tiling_problem.cpp | #include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
long long tiling(int n)
{
vector<long long int> tile(n + 1);
tile[0] = 1;
tile[1] = 1;
tile[2] = 2;
for (int i = 3; i <= n; i++)
tile[i] = tile[i - 1] + tile[i - 2];
return tile[n];
}
i... |
code/dynamic_programming/src/tiling_problem/tiling_problem.py | def tiling(n):
tile = [0 for i in range(n + 1)]
tile[0] = 1
tile[1] = 1
tile[2] = 2
for i in range(3, n + 1):
tile[i] = tile[i - 1] + tile[n - 2]
return tile[n]
if __name__ == "__main__":
n = 10
print(tiling(n))
|
code/dynamic_programming/src/trapping_rain_water/rainwater_trapping.cpp | #include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int left_highest[n];
int right_highest[n];
int l_high=arr[0];
int i=0;
int r_high=arr[n-1];
for(i=0;i<n;i++){
if(arr[i]>=l_high){
left_highest[i]=arr[i];
l_high=arr[i];
}
else
... |
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.cpp | /*
Problem Description - https://leetcode.com/problems/trapping-rain-water/description/
Test Cases -
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
*/
#include<iostream>
#include<vector>
using namespace std;
int trapRainWater(int *arr, int n)
{
if(n < 3)
return 0;
vector<pair<int,int>>indexes;
... |
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.java | public class Main {
public static void main(String args[]) {
int[] heightArray = {1, 2, 1, 3, 1, 2, 1, 4, 1, 0, 0, 2, 1, 4};
System.out.println(trap_rain_water(heightArray));
}
public static int trap_rain_water(int[] height) {
int result = 0;
if(height==null) {
... |
code/dynamic_programming/src/trapping_rain_water/trapping_rain_water.py | # Python3 implementation of the approach
# Function to return the maximum
# water that can be stored
def maxWater(arr, n) :
# To store the maximum water
# that can be stored
res = 0;
# For every element of the array
for i in range(1, n - 1) :
# Find the maximum elemen... |
code/dynamic_programming/src/unique_paths/unique_paths.cpp | // Part of Cosmos by OpenGenus Foundation
#include<bits/stdc++.h>
using namespace std;
//Tabulation method
// Time complexity: O(m*n)
int uniquePaths(int m, int n) {
int dp[m][n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0 || j==0)
... |
code/dynamic_programming/src/weighted_job_scheduling/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/dynamic_programming/src/weighted_job_scheduling/weighted_job_scheduling.cpp | /*
* Part of Cosmos by OpenGenus Foundation
* C++ program for weighted job scheduling using Dynamic Programming and Binary Search
*/
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// A job has start time, finish time and profit.
//index is used to store its given position as we wi... |
code/dynamic_programming/src/weighted_job_scheduling/weighted_job_scheduling.py | # Python3 program for weighted job scheduling using
# Naive Recursive Method
# Importing the following module to sort array
# based on our custom comparison function
from functools import cmp_to_key
# A job has start time, finish time and profit
class Job:
def __init__(self, start, finish, profit):
self.start... |
code/dynamic_programming/src/wildcard_matching/wildcard.cpp | //Part of Cosmos by OpenGenus Foundation
bool isMatch(string s, string p) {
/*
s is the string
p is the pattern containing '?' and '*' apart from normal characters.
*/
int m=s.length(), n=p.length();
bool dp[m+1][n+1];
// Initialise each cell of the dp table with false
for(int... |
code/dynamic_programming/src/wildcard_matching/wildcard.md | # Wildcard Matching
Learn more: [Wildcard Pattern Matching (Dynamic Programming)](https://iq.opengenus.org/wildcard-pattern-matching-dp/)
## Description
You have a string `s` of length `m` and a pattern `p` of length `n`. With wildcard matching enabled ie. character `?` in `p` can replace 1 character of `s` and a `*... |
code/dynamic_programming/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/dynamic_programming/test/longest_repeating_subsequence/longest_repeating_subsequence_test.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string>
#include <cassert>
#include "../../src/longest_repeating_subsequence/longest_repeating_subsequence.cpp"
int main()
{
using namespace std;
std::string s1 = "aab";
assert(longestRepeatingSubsequence(s1) == 1);
}
|
code/dynamic_programming/test/subset_sum/test_subset_sum.cpp | /* Part of Cosmos by OpenGenus Foundation */
#ifndef SUBSET_SUM_TEST
#define SUBSET_SUM_TEST
#include <iostream>
#include <list>
#include <cassert>
#include "../../src/subset_sum/subset_sum.cpp"
int
main()
{
using namespace std;
int vz[0];
int v[] = {1, 2, 15, 8, 5};
list<int> l{1, 2, 15, 8, 5};
... |
code/filters/src/gaussian_filter/gaussian_filter.py | ##Author - Sagar Vakkala (@codezoned)
from PIL import Image
import numpy
def main():
##Load the Image (Change source.jpg with your image)
image = Image.open("source.jpg")
##Get the width and height
width, height = image.size
##Initialise a null matrix
pix = numpy.zeros(shape=(width, height, ... |
code/filters/src/median_filter/median_filter.py | ##Author - Sagar Vakkala (@codezoned)
import numpy
from PIL import Image
def median_filter(data, filter_size):
temp_arr = []
index = filter_size // 2
data_final = []
data_final = numpy.zeros((len(data), len(data[0])))
for i in range(len(data)):
# Iterate over the Image Array
for j... |
code/game_theory/src/expectimax/expectimax.py | """
Expectimax game playing algorithm
Alex Day
Part of Cosmos by OpenGenus Foundation
"""
from abc import ABC, abstractmethod
import math
from random import choice
class Board(ABC):
@abstractmethod
def terminal():
"""
Determine if the current state is terminal
Returns
-------
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.