filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.c | /*
* dynamic programming | binomial coefficient | C
* Part of Cosmos by OpenGenus Foundation
* A DP based solution that uses table C[][] to calculate the Binomial Coefficient
*/
#include <stdio.h>
// A utility function to return minimum of two integers
int
min(int a, int b)
{
return (a < b ? a : b);
}
// Returns value of Binomial Coefficient C(n, k)
int
binomialCoeff(int n, int k)
{
int C[n + 1][k + 1];
int i, j;
// Caculate value of Binomial Coefficient in bottom up manner
for (i = 0; i <= n; i++) {
for (j = 0; j <= min(i, k); j++) {
// Base Cases
if (j == 0 || j == i) {
C[i][j] = 1;
}
// Calculate value using previosly stored values
else {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
return C[n][k];
}
int main() {
int n = 5, k = 2;
printf ("Value of C(%d, %d) is %d \n", n, k, binomialCoeff(n, k) );
return (0);
}
|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.cpp | // dynamic programming | binomial coefficient | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
using namespace std;
/*
* Computes C(n,k) via dynamic programming
* C(n,k) = C(n-1, k-1) + C(n-1, k)
* Time complexity: O(n*k)
* Space complexity: O(k)
*/
long long binomialCoefficient(int n, int k)
{
long long C[k + 1];
for (int i = 0; i < k + 1; ++i)
C[i] = 0;
C[0] = 1;
for (int i = 1; i <= n; ++i)
for (int j = min(i, k); j > 0; --j)
C[j] = C[j] + C[j - 1];
return C[k];
}
/*
* More efficient algorithm to compute binomial coefficient
* Time complexity: O(k)
* Space complexity: O(1)
*/
long long binomialCoefficient_2(int n, int k)
{
long long answer = 1;
k = min(k, n - k);
for (int i = 1; i <= k; ++i, --n)
{
answer *= n;
answer /= i;
}
return answer;
}
void test(vector< pair<int, int>>& testCases)
{
for (auto test : testCases)
cout << "C(" << test.first << "," << test.second << ") = "
<< binomialCoefficient(test.first, test.second) << " = "
<< binomialCoefficient_2(test.first, test.second) << '\n';
}
int main()
{
vector< pair<int, int>> testCases = {
{5, 2},
{6, 6},
{7, 5},
{10, 6},
{30, 15}
};
test(testCases);
return 0;
}
|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.ex | defmodule BinomialCoefficient do
def binn_coef(n, k) do
cond do
n <= 0 or k <= 0 ->
{:error, :non_positive}
n < k ->
{:error, :k_greater}
true ->
p = n - k
{rem_fact_n, div_fact} =
if p > k do
{
n..(p + 1)
|> Enum.reduce(1, &(&1 * &2)),
2..k
|> Enum.reduce(1, &(&1 * &2))
}
else
{
n..(k + 1)
|> Enum.reduce(1, &(&1 * &2)),
2..p
|> Enum.reduce(1, &(&1 * &2))
}
end
rem_fact_n / div_fact
end
end
end
# This code is contributed by ryguigas0
|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.java | // dynamic programming | binomial coefficient | Java
// Part of Cosmos by OpenGenus Foundation
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class BinomialCoefficient{
static int binomialCoeff(int n, int k) {
if (k>n) {
return 0;
}
int c[] = new int[k+1];
int i, j;
c[0] = 1;
for (i=0; i<=n; i++) {
for (j=min(i,k); j>0; j--) {
c[j] = c[j] + c[j-1];
}
}
return c[k];
}
static int min(int a, int b) {
return (a<b)? a: b;
}
//test case
public static void main(String args[]) {
int n = 5, k = 2;
System.out.println("Value of C("+n+","+k+") is "+binomialCoeff(n, k));
}
}
|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.js | // dynamic programming | binomial coefficient | javascript js
// Part of Cosmos by OpenGenus Foundation
/*Call the function with desired values of n and k.
'ar' is the array name.*/
function binomialCoefficient(n, k) {
if (k > n) {
console.log("Not possible.");
return;
}
const ar = [n + 1];
for (let i = 0; i < n + 1; i++) {
ar[i] = [n + 1];
}
for (i = 0; i < n + 1; i++) {
for (let j = 0; j < n + 1; j++) {
if (i == j || j == 0) {
ar[i][j] = 1;
} else if (j > i) {
break;
} else {
ar[i][j] = ar[i - 1][j - 1] + ar[i - 1][j];
}
}
}
console.log(ar[n][k]);
}
|
code/dynamic_programming/src/binomial_coefficient/binomial_coefficient.py | # dynamic programming | binomial coefficient | Python
# Part of Cosmos by OpenGenus Foundation
import numpy as np
# implementation using dynamic programming
def binomialCoefficient(n, k, C=None):
if k < 0 or n < 0:
raise ValueError("n,k must not be less than 0")
if k > n:
return 0
k = min(k, n - k)
if C is None:
C = np.zeros((n + 1, k + 1))
if k == 0:
C[n, k] = 1
if C[n, k] == 0:
C[n, k] = binomialCoefficient(n - 1, k, C=C) + binomialCoefficient(
n - 1, k - 1, C=C
)
return C[n, k]
# test
# print(binomialCoefficient(10,3))
# print(binomialCoefficient(10,6))
# print(binomialCoefficient(10,4))
# print(binomialCoefficient(1,1))
# print(binomialCoefficient(0,0))
# print(binomialCoefficient(0,1))
# print(binomialCoefficient(-1,1))
|
code/dynamic_programming/src/bitmask_dp/README.md | # Bitmask DP
Bitmask DP is commonly used when we have smaller constraints and it's easier to try out all the possibilities to arrive at the solution.
Please feel free to add more explaination and problems for this topic! |
code/dynamic_programming/src/bitmask_dp/bitmask_dp_prob#1.cpp | /* Part of Cosmos by OpenGenus Foundation */
/* Problem Statement:
There are k types ties, uniquely identified by id from 1 to k. n ppl are
invited to a party. Each of them have a collection of ties. To look unique,
they decide that none of them will wear same type of tie. Count the number
of ways this is possible.
Constraints:
1<=k<=100
1<=n<=10
*/
#include <iostream>
#include <vector>
using namespace std;
long long mod = 1e9 + 7;
vector<int>tieList[105]; //stores list of ppl having tie with id i
vector<vector<long long> >dp(1030,vector<long long>(15,-1));
int total;
//mask = set of ppl, curTie = current tie-id
long long countWays(int mask, int curTie){
if(total == mask)//found a way to assign unique ties to different ppl
return 1;
if(curTie > 100)//if tie id exceeds the highest available tie-id
return 0;
//if the query is already processed
if(dp[mask][curTie]!=-1)
return dp[mask][curTie];
long long notTake = countWays(mask,curTie+1)%mod; //number of ways to not take the curTie
long long take;
//trying all possible ways to take the curTie
for(auto p : tieList[curTie]){
if(mask & (1<<p)) //if p is already wearing a tie, he cannot wear the curTie
continue;
take+=countWays(mask|(1<<p), curTie+1);
take%=mod;
}
long long totWays = (take + notTake)%mod;
return dp[mask][curTie] = totWays;
}
void solve(int n){
total = (1<<n) - 1;
int x,m;
for(int i=0;i<n;i++){
cin>>m; //number of types of ties available with i-th person
for(int j=0;j<m;j++){
cin>>x; //tie id
tieList[x].push_back(i);
}
}
long long ans = countWays(0, 1);
cout<<ans<<"\n";
}
int main(){
int n; cin>>n;
solve(n);
return 0;
}
|
code/dynamic_programming/src/boolean_parenthesization/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/boolean_parenthesization/boolean_parenthesization.c | /*
* dynamic programming | boolean parenthesization | C
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
int
boolean_parenthesization(char c[], char o[], int n)
{
int i, j, k, a, t[n][n], f[n][n];
for (i = 0; i < n; i++) {
if (c[i] == 'T') {
t[i][i] = 1;
f[i][i] = 0;
}
else {
t[i][i] = 0;
f[i][i] = 1;
}
}
for (i = 1; i < n; ++i) {
for (j = 0, k = i; k <n; ++j,++k) {
t[j][k] = 0;
f[j][k] = 0;
for (a = 0; a < i; a++) {
int b = j + a;
int d = t[j][b] + f[j][b];
int e = t[b + 1][k] + f[b + 1][k];
if (o[b] == '|') {
t[j][k] += d * e - f[j][b] * f[b + 1][k];
f[j][k] += f[j][b] * f[b + 1][k];
}
else if (o[b] == '&') {
t[j][k] += t[j][b] * t[b + 1][k];
f[j][k] += d * e - t[j][b] * t[b + 1][k];
}
else {
t[j][k] += f[j][b] * t[b + 1][k] + t[j][b] * f[b + 1][k];
f[j][k] += t[j][b] * t[b + 1][k] + f[j][b] * f[b + 1][k];
}
}
}
}
return t[0][n - 1];
}
int main()
{
char c[] = "TFTTF";
char s[] = "|&|^";
int n = sizeof(c)-1 / sizeof(c[0]);
printf("%d\n", boolean_parenthesization(c, s, n));
return (0);
}
|
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.cpp | // dynamic programming | boolean parenthesization | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <cstring>
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
int boolean_parenthesization(char c[], char o[], int n)
{
int t[n][n], f[n][n];
for (int i = 0; i < n; ++i)
{
if (c[i] == 'T')
{
t[i][i] = 1;
f[i][i] = 0;
}
else
{
t[i][i] = 0;
f[i][i] = 1;
}
}
for (int i = 1; i < n; ++i)
for (int j = 0, k = i; k < n; ++j, ++k)
{
t[j][k] = 0;
f[j][k] = 0;
for (int a = 0; a < i; ++a)
{
int b = j + a;
int d = t[j][b] + f[j][b];
int e = t[b + 1][k] + f[b + 1][k];
if (o[b] == '|')
{
t[j][k] += d * e - f[j][b] * f[b + 1][k];
f[j][k] += f[j][b] * f[b + 1][k];
}
else if (o[b] == '&')
{
t[j][k] += t[j][b] * t[b + 1][k];
f[j][k] += d * e - t[j][b] * t[b + 1][k];
}
else
{
t[j][k] += f[j][b] * t[b + 1][k] + t[j][b] * f[b + 1][k];
f[j][k] += t[j][b] * t[b + 1][k] + f[j][b] * f[b + 1][k];
}
}
}
return t[0][n - 1];
}
int main()
{
char c[] = "TFTTF";
char s[] = "|&|^";
int n = sizeof(c) - 1 / sizeof(c[0]);
std::cout << boolean_parenthesization(c, s, n);
return 0;
}
|
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.java | // dynamic programming | boolean parenthesization | Java
// Part of Cosmos by OpenGenus Foundation
/*** Dynamic programming implementation of the boolean
* parenthesization problem using 'T' and 'F' as characters
* and '&', '|' and '^' as the operators
***/
class boolean_parenthesization{
public static int boolean_parenthesization_(String symbols, String operators) {
int noOfSymbols = symbols.length();
int[][] trueMatrix = new int[noOfSymbols][noOfSymbols], falseMatrix = new int[noOfSymbols][noOfSymbols];
for (int index=0; index < noOfSymbols; index++) {
if (symbols.charAt(index) == 'T') {
trueMatrix[index][index] = 1;
falseMatrix[index][index] = 0;
}else {
trueMatrix[index][index] = 0;
falseMatrix[index][index] = 1;
}
}
for (int loopVar1=1; loopVar1 < noOfSymbols; loopVar1++) {
for (int innerLoopVar1=0, innerLoopVar2=loopVar1; innerLoopVar2 < noOfSymbols; innerLoopVar1++, innerLoopVar2++) {
trueMatrix[innerLoopVar1][innerLoopVar2] = 0;
falseMatrix[innerLoopVar1][innerLoopVar2] = 0;
int b, d, e;
for (int a=0; a < loopVar1; a++){
b = innerLoopVar1 + a;
d = trueMatrix[innerLoopVar1][b] + falseMatrix[innerLoopVar1][b];
e = trueMatrix[b+1][innerLoopVar2] + falseMatrix[b+1][innerLoopVar2];
switch (operators.charAt(b)) {
case '|':
trueMatrix[innerLoopVar1][innerLoopVar2] += d * e - falseMatrix[innerLoopVar1][b] * falseMatrix[b+1][innerLoopVar2];
falseMatrix[innerLoopVar1][innerLoopVar2] += falseMatrix[innerLoopVar1][b] * falseMatrix[b+1][innerLoopVar2];
break;
case '&':
trueMatrix[innerLoopVar1][innerLoopVar2] += trueMatrix[innerLoopVar1][b] * trueMatrix[b+1][innerLoopVar2];
falseMatrix[innerLoopVar1][innerLoopVar2] += d * e - trueMatrix[innerLoopVar1][b] * trueMatrix[b+1][innerLoopVar2];
break;
case '^':
trueMatrix[innerLoopVar1][innerLoopVar2] += falseMatrix[innerLoopVar1][b] * trueMatrix[b+1][innerLoopVar2] + trueMatrix[innerLoopVar1][b] * falseMatrix[b+1][innerLoopVar2];
falseMatrix[innerLoopVar1][innerLoopVar2] += trueMatrix[innerLoopVar1][b] * trueMatrix[b+1][innerLoopVar2] + falseMatrix[innerLoopVar1][b] * falseMatrix[b+1][innerLoopVar2];;
break;
}
}
}
}
return trueMatrix[0][noOfSymbols - 1];
}
public static void main(String[] args){
String symbols = "TFTTF";
String operators = "|&|^";
System.out.println(boolean_parenthesization_(symbols, operators));
}
}
|
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.py | # dynamic programming | boolean parenthesization | Python
# Part of Cosmos by OpenGenus Foundation
# Dynamic programming implementation of the boolean
# parenthesization problem using 'T' and 'F' as characters
# and '&', '|' and '^' as the operators
def boolean_parenthesization(c, o, n):
t = [[0 for i in range(n)] for j in range(n)]
f = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
if c[i] == "T":
t[i][i] = 1
f[i][i] = 0
else:
t[i][i] = 0
f[i][i] = 1
for i in range(1, n):
j, k = 0, i
while k < n:
t[j][k] = 0
f[j][k] = 0
for a in range(i):
b = j + a
d = t[j][b] + f[j][b]
e = t[b + 1][k] + f[b + 1][k]
if o[b] == "|":
t[j][k] += d * e - f[j][b] * f[b + 1][k]
f[j][k] += f[j][b] * f[b + 1][k]
elif o[b] == "&":
t[j][k] += t[j][b] * t[b + 1][k]
f[j][k] += d * e - t[j][b] * t[b + 1][k]
else:
t[j][k] += f[j][b] * t[b + 1][k] + t[j][b] * f[b + 1][k]
f[j][k] += t[j][b] * t[b + 1][k] + f[j][b] * f[b + 1][k]
j += 1
k += 1
return t[0][n - 1]
def main():
c = "TFTTF"
s = "|&|^"
n = len(c)
print(boolean_parenthesization(c, s, n))
if __name__ == "__main__":
main()
|
code/dynamic_programming/src/boolean_parenthesization/boolean_parenthesization.swift | // dynamic programming | boolean parenthesization | Swift
// Part of Cosmos by OpenGenus Foundation
// Dynamic programming implementation of the boolean
// parenthesization problem using 'T' and 'F' as characters
// and '&', '|' and '^' as the operators
class BooleanParenthesization {
private var characters = [Character]()
private var operators = [Character]()
private var memo = [[(Int, Int)]]()
public func booleanParenthesization(_ expression: String) -> Int {
parse(expression)
memo = [[(Int, Int)]](repeating: [(Int, Int)](repeating: (-1, -1),
count: characters.count), count: characters.count)
return solve(0, characters.count - 1).0
}
private func parse(_ expression: String) {
characters = []
operators = []
for char in expression {
if char == "T" || char == "F" {
characters.append(char)
}
else if char == "&" || char == "|" || char == "^" {
operators.append(char)
}
}
}
private func solve(_ i: Int, _ j: Int) -> (Int, Int) {
if(i == j) {
return characters[i] == "T" ? (1, 0) : (0, 1)
}
if(memo[i][j] > (-1, -1)) {
return memo[i][j]
}
var total = (0, 0)
for k in i..<j {
let left = solve(i, k)
let right = solve(k+1, j)
var answer = (0, 0)
if operators[k] == "&" {
answer.0 = left.0 * right.0
answer.1 = left.0 * right.1 + left.1 * right.0 + left.1 * right.1
}
else if operators[k] == "|" {
answer.0 = left.0 * right.0 + left.0 * right.1 + left.1 * right.0
answer.1 = left.1 * right.1
}
else if operators[k] == "^" {
answer.0 = left.0 * right.1 + left.1 * right.0
answer.1 = left.0 * right.0 + left.1 * right.1
}
total.0 += answer.0
total.1 += answer.1
}
memo[i][j] = total
return total
}
}
func test() {
let solution = BooleanParenthesization()
let testCases = [
"T|T&F^T", // 4
"T^F|F", // 2
"T&F^F|T", // 5
]
for test in testCases {
print(solution.booleanParenthesization(test))
}
}
test()
|
code/dynamic_programming/src/box_stacking/README.md | # Box Stacking
## Description
Given a set of n types of 3D rectangular boxes, find the maximum height
that can be reached stacking instances of these boxes. Some onservations:
- A box can be stacked on top of another box only if the dimensions of the
2D base of the lower box are each strictly larger than those of the 2D base
of the higher box.
- The boxes can be rotated so that any side functions as its base.
- It is allowable to use multiple instances of the same type of box.
## Solution
This problem can be seen as a variation of the dynamic programming
problem LIS (longest increasing sequence). The steps to solve the problem are:
1) Compute the rotations of the given types of boxes.
2) Sort the boxes by decreasing order of area.
3) Find the longest increasing sequence of boxes.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/box_stacking/box_stacking.cpp | // dynamic programming | box stacking | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Struct to represent the boxes
struct Box
{
int height, width, length;
// Initializer
Box()
{
}
Box(int h, int w, int l) : height(h), width(w), length(l)
{
}
// Return the area of the box
int area() const
{
return this->width * this->length;
}
// Return true if current box can be put
// on the other, and false otherwise
bool fitOn(const struct Box other)
{
return min(this->width, this->length) < min(other.width, other.length) &&
max(this->width, this->length) < max(other.width, other.length);
}
// Compare the boxes based on their area
bool operator<(const struct Box other) const
{
return this->area() < other.area();
}
};
/**
* Return the maximum height that can be
* obtained by stacking the available boxes.
* Time complexity: O(n^2), n = size of boxes
*/
int maxHeight(vector<Box> boxes)
{
// Get the rotations of current boxes
for (int i = 0, n = boxes.size(); i < n; ++i)
{
boxes.push_back(Box(boxes[i].width, boxes[i].length, boxes[i].height));
boxes.push_back(Box(boxes[i].length, boxes[i].height, boxes[i].width));
}
// Sort the boxes by decreasing order of area
sort(boxes.rbegin(), boxes.rend());
int dp[boxes.size()], ans = 0;
// Find the longest increasing sequence of boxes
for (size_t i = 0; i < boxes.size(); ++i)
{
dp[i] = boxes[i].height;
for (size_t j = 0; j < i; ++j)
if (boxes[i].fitOn(boxes[j]))
dp[i] = max(dp[i], boxes[i].height + dp[j]);
ans = max(ans, dp[i]);
}
return ans;
}
int main()
{
// Using C++11 initializer
vector<Box> boxes1 = {
Box(4, 6, 7),
Box(1, 2, 3),
Box(4, 5, 6),
Box(10, 12, 32)
};
vector<Box> boxes2 = {
Box(1, 2, 3),
Box(4, 5, 6),
Box(3, 4, 1)
};
cout << maxHeight(boxes1) << endl; // Expected output: 60
cout << maxHeight(boxes2) << endl; // Expected output: 15
}
|
code/dynamic_programming/src/box_stacking/box_stacking.java | // dynamic programming | box stacking | Java
// Part of Cosmos by OpenGenus Foundation
import java.util.Arrays;
public class BoxStacking {
public int maxHeight(Dimension[] input) {
//get all rotations of box dimension.
//e.g if dimension is 1,2,3 rotations will be 2,1,3 3,2,1 3,1,2 . Here length is always greater
//or equal to width and we can do that without loss of generality.
Dimension[] allRotationInput = new Dimension[input.length * 3];
createAllRotation(input, allRotationInput);
//sort these boxes in non increasing order by their base area.(length X width)
Arrays.sort(allRotationInput);
//apply longest increasing subsequence kind of algorithm on these sorted boxes.
int T[] = new int[allRotationInput.length];
int result[] = new int[allRotationInput.length];
for (int i = 0; i < T.length; i++) {
T[i] = allRotationInput[i].height;
result[i] = i;
}
for (int i = 1; i < T.length; i++) {
for (int j = 0; j < i; j++) {
if (allRotationInput[i].length < allRotationInput[j].length
&& allRotationInput[i].width < allRotationInput[j].width) {
if( T[j] + allRotationInput[i].height > T[i]){
T[i] = T[j] + allRotationInput[i].height;
result[i] = j;
}
}
}
}
//find max in T[] and that will be our max height.
//Result can also be found using result[] array.
int max = Integer.MIN_VALUE;
for(int i=0; i < T.length; i++){
if(T[i] > max){
max = T[i];
}
}
return max;
}
//create all rotations of boxes, always keeping length greater or equal to width
private void createAllRotation(Dimension[] input,
Dimension[] allRotationInput) {
int index = 0;
for (int i = 0; i < input.length; i++) {
allRotationInput[index++] = Dimension.createDimension(
input[i].height, input[i].length, input[i].width);
allRotationInput[index++] = Dimension.createDimension(
input[i].length, input[i].height, input[i].width);
allRotationInput[index++] = Dimension.createDimension(
input[i].width, input[i].length, input[i].height);
}
}
public static void main(String args[]) {
BoxStacking bs = new BoxStacking();
Dimension input[] = { new Dimension(3, 2, 5), new Dimension(1, 2, 4) };
int maxHeight = bs.maxHeight(input);
System.out.println("Max height is " + maxHeight);
assert 11 == maxHeight;
}
}
class Dimension implements Comparable<Dimension> {
int height;
int length;
int width;
Dimension(int height, int length, int width) {
this.height = height;
this.length = length;
this.width = width;
}
Dimension() {
}
static Dimension createDimension(int height, int side1, int side2) {
Dimension d = new Dimension();
d.height = height;
if (side1 >= side2) {
d.length = side1;
d.width = side2;
} else {
d.length = side2;
d.width = side1;
}
return d;
}
/**
* Sorts by base area(length X width)
*/
@Override
public int compareTo(Dimension d) {
if (this.length * this.width >= d.length * d.width) {
return -1;
} else {
return 1;
}
}
@Override
public String toString() {
return "Dimension [height=" + height + ", length=" + length
+ ", width=" + width + "]";
}
}
|
code/dynamic_programming/src/box_stacking/box_stacking.py | """
dynamic programming | box stacking | Python
Part of Cosmos by OpenGenus Foundation
"""
from collections import namedtuple
from itertools import permutations
dimension = namedtuple("Dimension", "height length width")
def create_rotation(given_dimensions):
"""
A rotation is an order wherein length is greater than or equal to width. Having this constraint avoids the
repetition of same order, but with width and length switched.
For e.g (height=3, width=2, length=1) is same the same box for stacking as (height=3, width=1, length=2).
:param given_dimensions: Original box dimensions
:return: All the possible rotations of the boxes with the condition that length >= height.
"""
for current_dim in given_dimensions:
for (height, length, width) in permutations(
(current_dim.height, current_dim.length, current_dim.width)
):
if length >= width:
yield dimension(height, length, width)
def sort_by_decreasing_area(rotations):
return sorted(rotations, key=lambda dim: dim.length * dim.width, reverse=True)
def can_stack(box1, box2):
return box1.length < box2.length and box1.width < box2.width
def box_stack_max_height(dimensions):
boxes = sort_by_decreasing_area(
[rotation for rotation in create_rotation(dimensions)]
)
num_boxes = len(boxes)
T = [rotation.height for rotation in boxes]
R = [idx for idx in range(num_boxes)]
for i in range(1, num_boxes):
for j in range(0, i):
if can_stack(boxes[i], boxes[j]):
stacked_height = T[j] + boxes[i].height
if stacked_height > T[i]:
T[i] = stacked_height
R[i] = j
max_height = max(T)
start_index = T.index(max_height)
# Prints the dimensions which were stored in R list.
while True:
print(boxes[start_index])
next_index = R[start_index]
if next_index == start_index:
break
start_index = next_index
return max_height
if __name__ == "__main__":
d1 = dimension(3, 2, 5)
d2 = dimension(1, 2, 4)
assert 11 == box_stack_max_height([d1, d2])
|
code/dynamic_programming/src/catalan/catalan_number.go | package dynamic
import "fmt"
var errCatalan = fmt.Errorf("can't have a negative n-th catalan number")
// NthCatalan returns the n-th Catalan Number
// Complexity: O(n²)
func NthCatalanNumber(n int) (int64, error) {
if n < 0 {
//doesn't accept negative number
return 0, errCatalan
}
var catalanNumberList []int64
catalanNumberList = append(catalanNumberList, 1) //first value is 1
for i := 1; i <= n; i++ {
catalanNumberList = append(catalanNumberList, 0) //append 0 and calculate
for j := 0; j < i; j++ {
catalanNumberList[i] += catalanNumberList[j] * catalanNumberList[i-j-1]
}
}
return catalanNumberList[n], nil
} |
code/dynamic_programming/src/coin_change/README.md | # Coin Change
## Description
Given a set of coins `S` with values `{ S1, S2, ..., Sm }`,
find the number of ways of making the change to a certain value `N`.
There is an infinite quantity of coins and the order of the coins doesn't matter.
For example:
For `S = {1, 2, 3}` and `N = 4`, the number of possibilities is 4, that are:
`{1,1,1,1}`, `{1,1,2}`, `{2,2}` and `{1,3}`. Note that the sets `{1,2,1}`, `{2,1,1}`
and `{3,1}` don't count to solution as they are permutations of the other ones.
## Solution
For each set of coins, there are two possibilities for each coin:
- The coin is not present in the set.
- At least one coin is present.
So, being `f(S[], i, N)` the number of possibilities of making change to `N`
with coins from `S[0]` to `S[i]`, it can be computed by summing the number
of possibilities of getting `N` without using `S[i]`, that is `f(S[], i-1, N)`,
and the number of possibilities that uses `S[i]`, that is `f(S[], i, N - S[i])`.
So, we can compute `f(S[], i, N)` by doing the following:
```
f(S[], i, 0) = 1 // if N reaches 0, than we found a valid solution
f(S[], i, N) = 0, if i < 0 or N < 0
f(S[], i-1, N) + f(S[], i, N - S[i]), otherwise
```
Applying memoization to above solution, the time complexity of the algorithm
becomes O(N * m), where m is the number of elements in `S`.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/coin_change/coin_change.java | // dynamic programming | coin change | Java
// Part of Cosmos by OpenGenus Foundation
public class WaysToCoinChange {
public static int dynamic(int[] v, int amount) {
int[][] solution = new int[v.length + 1][amount + 1];
// if amount=0 then just return empty set to make the change
for (int i = 0; i <= v.length; i++) {
solution[i][0] = 1;
}
// if no coins given, 0 ways to change the amount
for (int i = 1; i <= amount; i++) {
solution[0][i] = 0;
}
// now fill rest of the matrix.
for (int i = 1; i <= v.length; i++) {
for (int j = 1; j <= amount; j++) {
// check if the coin value is less than the amount needed
if (v[i - 1] <= j) {
// reduce the amount by coin value and
// use the subproblem solution (amount-v[i]) and
// add the solution from the top to it
solution[i][j] = solution[i - 1][j]
+ solution[i][j - v[i - 1]];
} else {
// just copy the value from the top
solution[i][j] = solution[i - 1][j];
}
}
}
return solution[v.length][amount];
}
public static void main(String[] args) {
int amount = 5;
int[] v = { 1, 2, 3 };
System.out.println("By Dynamic Programming " + dynamic(v, amount));
}
}
|
code/dynamic_programming/src/coin_change/coin_change.py | #################
## dynamic programming | coin change | Python
## Part of Cosmos by OpenGenus Foundation
#################
def coin_change(coins, amount):
# init the dp table
tab = [0 for i in range(amount + 1)]
tab[0] = 1 # base case
for j in range(len(coins)):
for i in range(1, amount + 1):
if coins[j] <= i:
# if coins[j] < i then add no. of ways -
# - to form the amount by using coins[j]
tab[i] += tab[i - coins[j]]
# final result at tab[amount]
return tab[amount]
def main():
coins = [1, 2, 3, 8] # coin denominations
amount = 3 # amount of money
print("No. of ways to change - {}".format(coin_change(coins, amount)))
return
if __name__ == "__main__":
main()
|
code/dynamic_programming/src/coin_change/coinchange.c | // dynamic programming | coin change | C
// Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
int
count( int S[], int m, int n )
{
int i, j, x, y;
// We need n+1 rows as the table is consturcted in bottom up manner using
// the base case 0 value case (n = 0)
int table[n + 1][m];
// Fill the enteries for 0 value case (n = 0)
for (i = 0; i < m; i++)
table[0][i] = 1;
// Fill rest of the table enteries in bottom up manner
for (i = 1; i < n + 1; i++) {
for (j = 0; j < m; j++) {
// Count of solutions including S[j]
x = (i - S[j] >= 0) ? table[i - S[j]][j] : 0;
// Count of solutions excluding S[j]
y = (j >= 1) ? table[i][j - 1]: 0;
// total count
table[i][j] = x + y;
}
}
return (table[n][m - 1]);
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;++i)
cin>>arr[i];
cin>>m;
printf(" %d ", count(arr, n, m));
return (0);
}
|
code/dynamic_programming/src/coin_change/coinchange.cpp | // dynamic programming | coin change | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <vector>
using namespace std;
int coinWays(int amt, vector<int>& coins) {
// init the dp table
vector<int> dp(amt+1, 0);
int n = coins.size();
dp[0] = 1; // base case
for (int j = 0; j < n; ++j)
for (int i = 1; i <= amt; ++i)
if (i - coins[j] >= 0)
// if coins[j] < i then add no. of ways -
// - to form the amount by using coins[j]
dp[i] += dp[i - coins[j]];
// final result at dp[amt]
return dp[amt];
}
int main() {
vector<int> coins = {1, 2, 3}; // coin denominations
int amount = 4; // amount
cout << coinWays(amount, coins) << '\n';
return 0;
}
|
code/dynamic_programming/src/coin_change/coinchange.go | /*
* dynamic programming | coin change | Go
* Part of Cosmos by OpenGenus Foundation
*/
package main
import "fmt"
/*
There are 22 ways to combine 8 from [1 2 3 4 5 6 7 8 9 10]
*/
//DP[i] += DP[i-coint[i]]
//j = coinset,
//i = for each money
func solveCoinChange(coins []int, target int) int {
dp := make([]int, target+1)
dp[0] = 1 //basic
for _, v := range coins {
for i := 1; i <= target; i++ {
if i >= v {
dp[i] += dp[i-v]
}
}
}
return dp[target]
}
func main() {
coins := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
target := 8
way := solveCoinChange(coins, target)
fmt.Printf("There are %d ways to combine %d from %v\n", way, target, coins)
}
|
code/dynamic_programming/src/coin_change/mincoinchange.cpp | // dynamic programming | coin change | C++
// Part of Cosmos by OpenGenus Foundation
// A C++ program to find the minimum number of coins required from the list of given coins to make a given value
// Given a value V, if we want to make change for V cents, and we have infinite supply of each of C = { C1, C2, .. , Cm}
// valued coins, what is the minimum number of coins to make the change?
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t; // no. of test cases
while (t--)
{
int v, n;
cin >> v >> n; // v is value to made and n is the number of given coins
int c[n + 1];
for (int i = 0; i < n; i++)
cin >> c[i]; // c[i] holds denomination or value of different coins
long long int dp[v + 1];
long long int m = 100000000;
dp[0] = 0;
for (int i = 1; i <= v; i++)
dp[i] = m;
for (int i = 0; i <= n - 1; i++)
for (int j = 1; j <= v; j++)
if (c[i] <= j)
if (1 + dp[j - c[i]] < dp[j])
dp[j] = 1 + dp[j - c[i]];
if (dp[v] == m)
cout << "-1" << endl; // prints -1 if it is not possible to make given amount v
else
cout << dp[v] << endl; // dp[v] gives the min coins required to make amount v
}
}
|
code/dynamic_programming/src/die_simulation/README.md | ## Description
There is a dice simulator which generates random numbers from 0 to 5. You are given an array `constraints` where `constraints[i]` denotes the
maximum number of consecutive times the ith number can be rolled. You are also given `n`, the number of times the dice is to be rolled ie. the number of simulations. Find the total number of distinct sequences of length `n` which can be generated by the simulator.
Two sequences are considered different if at least one element differs from each other.
## Thought Process
This question is tough, no doubt. So, I suggest you start with a paper and pen. Take the example `n = 3, constraints = [1,1,1,2,2,3]`. Draw three dashes for the 3 simulations (a roll of the die), \_ \_ \_ and start building the sequence in an algorithmic (repetitive steps) manner.
<details>
<summary>How to fill the dashes?</summary>
</br>
You start filling in increasing order. <br/>
1=> You fill 0 _ _ . <br/>
2=> For the second dash, you notice that 0 can occur only 1 consecutive time. Hence you can't fill a 0 again. So you fill, 0 1 _ . <br/>
3=> For third blank we can choose 0. Hence 0, 1, 0. That's one sequence. <br/>
4=> Now, 1 can't occur more than 1 consecutive time. So you fill 2. 0 1 2. That's one sequence. <br/>
5=> Now you put 3 inplace of 2. So now your sequence is 0 1 3. That's another valid sequence. <br/>
6=> Similarly you put 4 and 5 to form 0 1 4 and 0 1 5. <br/>
7=> Now, you come back to 2nd place and put in 2 (recall we already considered 0). 0 2 _ . <br/>
8=> Can't put 2 again. Hence, we put 0, 1, 3, 4 and 5 to form 0 2 0, 0 2 1, 0 2 3, 0 2 4, 0 2 5. <br/>
9=> For 3, 4, 5 in 2nd place, we repeat the steps. <br/>
10=> Come back to 1st place. Put in 1. Now the sequence is 1 _ _ . <br/>
11=> In the second place, we can't put in 1. So we put 0. Do the same as above. <br/>
12=> After that consider 1 2 _ . But wait! Have we seen this <b>subproblem</b> somewhere before? <br/>The subproblem of 2 in the second place has occurred before.
We found that 2 0, 2 1, 2 3, 2 4, and 2 5 (but not 2 2) were the allowed sequences after it. Since we only need the count of total sequences, it would be good
if we record it. Hence let's assume we recorded (and we would btw) that with 2 in the 2nd place, we could form 5 distinct sequences after it. Thus while
forming 1 _ _ , for 1 2 _ , we need not calculate further. We know that 5 sequences are on their way. <br/>
13=> So we try 1 3 _ . But again! We've encountered even this subsequence before in step 9! Similarly for 1 4, 1 5. <br/>
</details>
<details>
<summary>Solution</summary>
</br>
We'll recurse over each dash(simulation) and do dp with memoization
</details>
<details>
<summary>What's the time complexity?</summary>
</br>
Filling each cell takes O(1) time (Filling some cell require us to recurse but we can view that as filling other cells).
There are a total of n*m*p cells where n is number of simulations, m is the length of constraint array (6 in our case) and p is the maximum constraint value,
it takes O(6 * np) = O(np) time.
</details>
|
code/dynamic_programming/src/die_simulation/die_simulation.cpp | // Part of OpenGenus cosmos
#define ll long long
const int mod = 1e9+7;
// Function to add in presence of modulus. We find the modded answer
// as the number of sequences becomes exponential fairly quickly
ll addmod(ll a, ll b)
{
return (a%mod + b%mod) % mod;
}
ll dieSimulator_util(int dex, vector<int>& maxroll, int noOfTimes, int prev, vector<vector<vector<ll> > >& dp, int n){
// Simulations are 0 indexed ie. 0 to n-1. Hence return 1 when n is reached
if(dex==n)
return 1;
// If for the dex'th simulation, the number of sequences has already been found, return it.
if(dp[dex][noOfTimes][prev] != -1)
return dp[dex][noOfTimes][prev]%mod;
// Initialise answer to 0.
int ans=0;
// Put all the digits in the dex'th simulation and for each of them,
// move forward ie. do (dex+1)th simulation.
for(int i=0;i<6;i++)
{
// Check if the current digit is the same as previous one
if(i == prev)
{
/*
Check if the number of times it has occurred has become equal to the allowed number of times. If yes, then
don't put that digit, otherwise put that digit, add one to the noOfTimes it has occurred and move on.
*/
if(noOfTimes < maxroll[i])
ans = addmod(ans, dieSimulator_util(dex + 1, maxroll, noOfTimes + 1, prev, dp, n));
}
else
{
ans = addmod(ans, dieSimulator_util(dex + 1, maxroll, 1, i, dp, n));
}
}
// Record the answer
dp[dex][noOfTimes][prev] = ans;
return ans;
}
int dieSimulator(int n, vector<int>& maxRolls) {
// Loop over maxRolls array to find the maximum number of times a digit can be rolled.
int maxi = 0;
for(int i=0;i<maxRolls.size();i++)
{
if(maxRolls[i] > maxi)
maxi = maxRolls[i];
}
/*
Initialise a 3d DP table with -1 where the row denotes the ith roll simulation, the
column denotes the number of consecutive times the digit in depth has occurred and the
depth denotes the number of distinct digits.
*/
vector<vector<vector<ll> > > dp(n, vector<vector<ll> >(maxi+1, vector<ll>(7, -1)));
/*
For the first call,
current index = 0
noOfTimes it has occurred = 0
no of simulation = 6
*/
return dieSimulator_util(0, maxRolls, 0, 6, dp, n);
}
|
code/dynamic_programming/src/digit_dp/DigitDP.java | /* Part of Cosmos by OpenGenus Foundation */
/* How many numbers x are there in the range a to b?
* where the digit d occurs exactly k times in x?
*/
import java.util.Arrays;
public class DigitDP {
private static int d = 3;
private static int k = 5;
private static int[][][] dp = new int[25][25][2];
/* dp[pos][count][f] = Number of valid numbers <= b from this state
* pos = current position from left side (zero based)
* count = number of times we have placed the digit d so far
* f = the number we are building has already become smaller than b? [0 = no, 1 = yes]
*/
public static void main(String args[]) {
String a = "100";
String b = "100000000";
int ans = solve(b) - solve(a) + check(a);
System.out.println(ans);
}
private static int check(String num) {
int count = 0;
for(int i = 0; i < num.length(); ++i)
if (num.charAt(i) - '0' == d)
count++;
if (count == k)
return 1;
return 0;
}
private static int solve(String num) {
for(int[][] rows: dp)
for(int[] cols: rows)
Arrays.fill(cols, -1);
int ret = digit_dp(num, 0, 0, 0);
return ret;
}
private static int digit_dp(String num, int pos, int count, int f) {
if (count > k)
return 0;
if (pos == num.length()) {
if (count == k)
return 1;
return 0;
}
if (dp[pos][count][f] != -1)
return dp[pos][count][f];
int res = 0;
int limit;
if (f == 0) {
/* Digits we placed so far matches with the prefix of b
* So if we place any digit > num[pos] in the current position, then
* the number will become greater than b
*/
limit = num.charAt(pos) - '0';
} else {
/* The number has already become smaller than b.
* We can place any digit now.
*/
limit = 9;
}
// Try to place all the valid digits such that the number does not exceed b
for(int dgt = 0; dgt <= limit; ++dgt) {
int fNext = f;
int countNext = count;
// The number is getting smaller at this position
if (f == 0 && dgt < limit)
fNext = 1;
if (dgt == d)
countNext++;
if (countNext <= k)
res += digit_dp(num, pos + 1, countNext, fNext);
}
dp[pos][count][f] = res;
return dp[pos][count][f];
}
}
|
code/dynamic_programming/src/digit_dp/digit_dp.cpp | /* Part of Cosmos by OpenGenus Foundation
* By: Sibasish Ghosh (https://github.com/sibasish14)
*/
/* How many numbers x are there in the range a to b?
* where the digit d occurs exactly k times in x?
*/
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
long d = 3;
long k = 5;
long dp[25][25][2];
/* dp[pos][count][f] = Number of valid numbers <= b from this state
* pos = current position from left side (zero based)
* count = number of times we have placed the digit d so far
* f = the number we are building has already become smaller than b? [0 = no, 1 = yes]
*/
long digit_dp(string num, long pos, long count, long f)
{
if (count > k)
return 0;
if (pos == num.size())
{
if (count == k)
return 1;
return 0;
}
if (dp[pos][count][f] != -1)
return dp[pos][count][f];
long result = 0;
long limit;
if (f == 0)
/* Digits we placed so far matches with the prefix of b
* So if we place any digit > num[pos] in the current position, then
* the number will become greater than b
*/
limit = num[pos] - '0';
else
/* The number has already become smaller than b.
* We can place any digit now.
*/
limit = 9;
// Try to place all the valid digits such that the number doesn't exceed b
for (long dgt = 0; dgt <= limit; dgt++)
{
long fNext = f;
long countNext = count;
// The number is getting smaller at this position
if (f == 0 && dgt < limit)
fNext = 1;
if (dgt == d)
countNext++;
if (countNext <= k)
result += digit_dp(num, pos + 1, countNext, fNext);
}
return dp[pos][count][f] = result;
}
long solve(string num)
{
memset(dp, -1, sizeof(dp));
long result = digit_dp(num, 0, 0, 0);
return result;
}
bool check(string num)
{
long count = 0;
for (long i = 0; i < num.size(); i++)
if (num[i] - '0' == d)
count++;
if (count == k)
return true;
else
return false;
}
int main()
{
string a = "100", b = "100000000";
long ans = solve(b) - solve(a) + check(a);
cout << ans << "\n";
return 0;
}
|
code/dynamic_programming/src/edit_distance/README.md | # Edit distance
## Description
Edit distance is a way of quantifying how dissimilar two strings (e.g., words) are to one another by counting the minimum number of operations required to transform one string into the other. Edit distances find applications in natural language processing, where automatic spelling correction can determine candidate corrections for a misspelled word by selecting words from a dictionary that have a low distance to the word in question. In bioinformatics, it can be used to quantify the similarity of DNA sequences, which can be viewed as strings of the letters A, C, G and T.
## Example
The Levenshtein distance between "kitten" and "sitting" is 3. A minimal edit script that transforms the former into the latter is:
kitten → sitten (substitution of "s" for "k")
sitten → sittin (substitution of "i" for "e")
sittin → sitting (insertion of "g" at the end).
LCS distance (insertions and deletions only) gives a different distance and minimal edit script:
delete k at 0
insert s at 0
delete e at 4
insert i at 4
insert g at 6
for a total cost/distance of 5 operations.
---
<p align="center">
A massive collaborative effort by <a href=https://github.com/OpenGenus/cosmos>OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/edit_distance/edit_distance.c | /*
* dynamic programming | edit distance | C
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int MAX = 1010;
int memo[MAX][MAX]; /* used for memoization */
int
mn(int x, int y)
{
return x < y ? x : y;
}
/* Utility function to find minimum of three numbers */
int
min(int x, int y, int z)
{
return mn(x, mn(y, z));
}
int
editDist(char str1[], char 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 this state has already been computed, get its value */
if (memo[m][n] > -1) return memo[m][n];
/*
* 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 memo[m][n] = 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 memo[m][n] = 1 + min ( editDist(str1, str2, m, n-1), /* Insert */
editDist(str1, str2, m-1, n), /* Remove */
editDist(str1, str2, m-1, n-1) /* Replace */
);
}
/* Driver program */
int
main()
{
char str1[] = "sunday";
char str2[] = "saturday";
int str1Length = sizeof(str1) / sizeof(str1[0]);
int str2Length = sizeof(str2) / sizeof(str2[0]);
memset(memo, -1 ,sizeof memo);
int minimum = editDist(str1, str2, str1Length, str2Length);
printf("%d\n", minimum);
return 0;
}
|
code/dynamic_programming/src/edit_distance/edit_distance.cpp | // dynamic programming | edit distance | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#define MAX 1010
using namespace std;
int memo[MAX][MAX];
/*
* A recursive approach to the edit distance problem.
* Returns the edit distance between a[0...i] and b[0...j]
* Time complexity: O(n*m)
*/
int editDistance(string& a, string& b, int i, int j)
{
if (i < 0)
return j + 1;
if (j < 0)
return i + 1;
if (memo[i][j] > -1)
return memo[i][j];
if (a[i] == b[j])
return memo[i][j] = editDistance(a, b, i - 1, j - 1);
int c1 = editDistance(a, b, i - 1, j - 1); // replacing
int c2 = editDistance(a, b, i - 1, j); // removing
int c3 = editDistance(a, b, i, j - 1); // inserting
return memo[i][j] = 1 + min(c1, min(c2, c3));
}
int main()
{
string a = "opengenus", b = "cosmos";
for (size_t i = 0; i < MAX; ++i)
for (size_t j = 0; j < MAX; ++j)
memo[i][j] = -1;
// memset(memo, -1, sizeof memo);
cout << editDistance(a, b, a.length() - 1, b.length() - 1) << '\n';
}
|
code/dynamic_programming/src/edit_distance/edit_distance.go | /*
* dynamic programming | edit distance | Go
* Part of Cosmos by OpenGenus Foundation
*
* Compile: go build edit_distance.go
*/
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("Wrong input, write input next to the program call")
fmt.Println("Example: ./edit_distance string1 string2")
return
}
str1 := os.Args[1]
str2 := os.Args[2]
//str1 := "sunday"
//str2 := "saturday"
min := editDistance(str1, str2, len(str1), len(str2))
fmt.Println(min)
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func editDistance(str1 string, str2 string, m int, n int) int {
// Create table to store results of DP subproblems
store := make([][]int, m+1)
for i := range store {
store[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
for j := 0; j <= n; j++ {
if i == 0 {
// When i is zero we must insert all (j) characters to get the second string
store[i][j] = j
} else if j == 0 {
// Remove all characters in first string
store[i][j] = i
} else if str1[i-1] == str2[j-1] {
// Last characters are equal, make recursion without last char
store[i][j] = store[i-1][j-1]
} else {
// find minimum over all possibilities
store[i][j] = 1 + min(min(store[i][j-1], store[i-1][j]), store[i-1][j-1])
}
}
}
return store[m][n]
}
|
code/dynamic_programming/src/edit_distance/edit_distance.hs | --- dynamic programming | edit distance | Haskell
--- Part of Cosmos by OpenGenus
--- Adapted from http://jelv.is/blog/Lazy-Dynamic-Programming/
module EditDistance where
import Data.Array
editDistance :: String -> String -> Int
editDistance a b = d m n
where (m, n) = (length a, length b)
a' = listArray (1, m) a -- 1-indexed to simplify arithmetic below
b' = listArray (1, n) b
d i 0 = i
d 0 j = j
d i j
| a' ! i == b' ! j = table ! (i - 1, j - 1)
| otherwise = minimum [ table ! (i - 1, j) + 1
, table ! (i, j - 1) + 1
, table ! (i - 1, j - 1) + 1
]
table = listArray bounds
[d i j | (i, j) <- range bounds] -- 2D array to store intermediate results
bounds = ((0, 0), (m, n))
main = print $ editDistance "sunday" "saturday" == 3
|
code/dynamic_programming/src/edit_distance/edit_distance.java | // dynamic programming | edit distance | Java
// Part of Cosmos by OpenGenus Foundation
import java.util.Scanner;
public class edit_distance {
public static int edit_DP(String s,String t){
int l1 = s.length();
int l2 = t.length();
int dp[][] = new int[l1+1][l2+1];
for(int i=0; i<=l2; i++)
dp[0][i] = i;
for(int i=0; i<=l1; i++)
dp[i][0] = i;
for(int i=1; i<=l1; i++){
for(int j=1; j<=l2; j++){
if(s.charAt(l1-i) == t.charAt(l2-j))
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = 1 + Math.min( dp[i-1][j-1] , Math.min (dp[i-1][j] , dp[i][j-1]) );
}
}
return dp[l1][l2];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string >> ");
String a = sc.next();
System.out.print("Enter second string >> ");
String b = sc.next();
System.out.println("Edit Distance : " + edit_DP(a,b));
}
}
|
code/dynamic_programming/src/edit_distance/edit_distance.php | <?php
// dynamic programming | edit distance | PHP
// Part of Cosmos by OpenGenus Foundation
function editDistance($str1, $str2)
{
$lenStr1 = strlen($str1);
$lenStr2 = strlen($str2);
if ($lenStr1 == 0) {
return $lenStr2;
}
if ($lenStr2 == 0) {
return $lenStr1;
}
$distanceVectorInit = [];
$distanceVectorFinal = [];
for ($i = 0; $i < $lenStr1 + 1; $i++) {
$distanceVectorInit[$i] = $i;
$distanceVectorFinal[] = 0;
}
for ($i = 0; $i < $lenStr2; $i++) {
$distanceVectorFinal[0] = $i + 1;
// use formula to fill in the rest of the row
for ($j = 0; $j < $lenStr1; $j++) {
$substitutionCost = 0;
if ($str1[$j] == $str2[$i]) {
$substitutionCost = $distanceVectorInit[$j];
} else {
$substitutionCost = $distanceVectorInit[$j] + 1;
}
$distanceVectorFinal[$j+1] = min($distanceVectorInit[$j+1] + 1, min($distanceVectorFinal[$j] + 1, $substitutionCost));
}
$distanceVectorInit = $distanceVectorFinal;
}
return $distanceVectorFinal[$lenStr1];
}
echo editDistance("hello", "hallo");
|
code/dynamic_programming/src/edit_distance/edit_distance.py | # dynamic programming | edit distance | Python
# Part of Cosmos by OpenGenus Foundation
# A top-down DP Python program to find minimum number
# of operations to convert str1 to str2
def editDistance(str1, str2):
def editDistance(str1, str2, m, n, memo):
# 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 this state has already been computed, just return it
if memo[m][n] > -1:
return memo[m][n]
# 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]:
memo[m][n] = editDistance(str1, str2, m - 1, n - 1, memo)
return memo[m][n]
# 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.
memo[m][n] = 1 + min(
editDistance(str1, str2, m, n - 1, memo), # Insert
editDistance(str1, str2, m - 1, n, memo), # Remove
editDistance(str1, str2, m - 1, n - 1, memo), # Replace
)
return memo[m][n]
size = max(len(str1), len(str2)) + 1
memo = [[-1 for _ in range(size)] for _ in range(size)]
return editDistance(str1, str2, len(str1), len(str2), memo)
# Driver program to test the above function
str1 = "sunday"
str2 = "saturday"
print(editDistance(str1, str2))
|
code/dynamic_programming/src/edit_distance/edit_distance.rs | // dynamic programming | edit distance | Rust
// Part of Cosmos by OpenGenus Foundation
use std::cmp;
fn edit_distance(str1: &String, str2: &String) -> usize {
let len_str1 = str1.len();
let len_str2 = str2.len();
if len_str1 == 0 {
return len_str2;
}
if len_str2 == 0 {
return len_str1;
}
let mut distance_vector_init = vec![0; len_str1+1];
let mut distance_vector_final = vec![0; len_str1+1];
for i in 0..len_str1+1 {
distance_vector_init[i] = i;
}
for i in 0..len_str2 {
distance_vector_final[0] = i+1;
// use formula to fill in the rest of the row
for j in 0..len_str1 {
let mut substitution_cost;
let mut iter1 = str1.chars();
let mut iter2 = str2.chars();
let e1 = iter1.nth(j);
let e2 = iter2.nth(i);
if e1.is_some() && e2.is_some() && e1.unwrap() == e2.unwrap() {
substitution_cost = distance_vector_init[j];
} else {
substitution_cost = distance_vector_init[j] + 1
};
distance_vector_final[j + 1] = cmp::min(distance_vector_init[j+1] + 1, cmp::min(distance_vector_final[j] + 1, substitution_cost));
}
distance_vector_init = distance_vector_final.clone();
}
distance_vector_final[len_str1]
}
fn main() {
println!("edit_distance(saturday, sunday) = {}", edit_distance(&String::from("sunday"), &String::from("saturday")));
println!("edit_distance(sitten, kitten) = {}", edit_distance(&String::from("kitten"), &String::from("sitten")));
println!("edit_distance(gumbo, gambol) = {}", edit_distance(&String::from("gambol"), &String::from("gumbo")));
} |
code/dynamic_programming/src/edit_distance/edit_distance_backtracking.cpp | // dynamic programming | edit distance | C++
// Part of Cosmos by OpenGenus Foundation
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
class Alignment {
std::string sx, sy, sa, sb;
std::vector<std::vector<int>> A;
int sxL, syL;
int cost = 0;
//insertion cost
inline int insC()
{
return 4;
}
//deletion cost
inline int delC()
{
return 4;
}
//modification cost
inline int modC(char fr, char to)
{
if (fr == to)
return 0;
return 3;
}
public:
//constructor
Alignment(std::string s1, std::string s2) : sx(s1), sy(s2),
sxL(s1.length()), syL(s2.length())
{
//allocating size to array needed
A.resize(s2.length() + 4, std::vector<int>(s1.length() + 4, 0));
}
//recurrence
int rec(int i, int j)
{
return std::min(modC(sx[i - 1], sy[j - 1]) + A[i - 1][j - 1],
std::min(delC() + A[i - 1][j], insC() + A[i][j - 1]));
//i-1, j-1 in sx, sy b/c of 0-indexing in string
}
//building array of cost
void form_array()
{
//initialising the base needed in dp
//building up the first column, consider taking first string sx and second as null
for (int i = 0; i <= sxL; i++)
A[i][0] = i * (delC());
//building up the first row, consider taking first string null and second as string sy
for (int i = 0; i <= syL; i++)
A[0][i] = i * (insC());
//building up whole array from previously known values
for (int i = 1; i <= sxL; i++)
for (int j = 1; j <= syL; j++)
A[i][j] = rec(i, j);
cost = A[sxL][syL];
}
//finding the alignment
void trace_back(int i, int j)
{
while (true)
{
if (i == 0 || j == 0)
break;
//A[i][j] will have one of the three above values from which it is derived
//so comparing from each one
if (i >= 0 && j >= 0 && rec(i, j) == modC(sx[i - 1], sy[j - 1]) + A[i - 1][j - 1])
{
sa.push_back(sx[i - 1]);
sb.push_back(sy[j - 1]);
i--, j--;
}
else if ((i - 1) >= 0 && j >= 0 && rec(i, j) == delC() + A[i - 1][j])
{
sa.push_back(sx[i - 1]); //0-indexing of string
sb.push_back('-');
i -= 1;
}
else if (i >= 0 && (j - 1) >= 0)
{
sa.push_back('-'); //0-indexing of string
sb.push_back(sy[j - 1]);
j -= 1;
}
}
if (i != 0)
while (i)
{
sa.push_back(sx[i - 1]);
sb.push_back('-');
i--;
}
else
while (j)
{
sa.push_back('-');
sb.push_back(sy[j - 1]);
j--;
}
}
//returning the alignment
std::pair<std::string, std::string> alignst()
{
//reversing the alignments because we have formed the
//alignments from backward(see: trace_back, i, j started from m, n respectively)
reverse(sa.begin(), sa.end());
reverse(sb.begin(), sb.end());
return make_pair(sa, sb);
}
//returning the cost
int kyc()
{
return cost;
}
};
int main()
{
using namespace std;
//converting sx to sy
string sx, sy;
sx = "GCCCTAGCG";
sy = "GCGCAATG";
//standard input stream
//cin >> sx >> sy;
pair<string, string> st;
Alignment dyn(sx, sy);
dyn.form_array();
dyn.trace_back(sx.length(), sy.length());
st = dyn.alignst();
//Alignments can be different for same strings but cost will be same
cout << "Alignments of the strings\n";
cout << st.first << "\n";
cout << st.second << "\n";
cout << "Cost associated = ";
cout << dyn.kyc() << "\n";
/* Alignments
* M - modification, D - deletion, I - insertion for converting string1 to string2
*
* M M MD
* string1 - GCCCTAGCG
* string2 - GCGCAAT-G
*
*/
return 0;
}
|
code/dynamic_programming/src/edit_distance/edit_distance_hirschberg.cpp | /*
* dynamic programming | edit distance | C++
* Part of Cosmos by OpenGenus Foundation
*
* Dynamic-Programming + Divide & conquer for getting cost and aligned strings for problem of aligning two large strings
* Reference - Wikipedia-"Hirschberg's algorithm"
*/
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//cost associated
int cost = 0;
//insertion cost
inline int insC()
{
return 4;
}
//deletion cost
inline int delC()
{
return 4;
}
//modification cost
inline int modC(char fr, char to)
{
if (fr == to)
return 0;
return 3;
}
//reversing the string
string rever(string s)
{
int k = s.length();
for (int i = 0; i < k / 2; i++)
swap(s[i], s[k - i - 1]);
return s;
}
//minimizing the sum of shortest paths (see:GainAlignment function), calculating next starting point
int minimize(vector<int> ve1, vector<int> ve2, int le)
{
int sum, xmid = 0;
for (int i = 0; i <= le; i++)
{
if (i == 0)
sum = ve1[i] + ve2[le - i]; //reversing the array ve2 by taking its i element from last
if (sum > ve1[i] + ve2[le - i])
{
sum = ve1[i] + ve2[le - i];
xmid = i;
}
}
return xmid;
}
pair<string, string> stringOne(string s1, string s2)
{
//building of array for case string length one of any of the string
string sa, sb;
int m = s1.length();
int n = s2.length();
vector<vector<int>> fone(s1.length() + 5, vector<int>(2));
for (int i = 0; i <= m; i++)
fone[i][0] = i * delC();
for (int j = 0; j <= n; j++)
fone[0][j] = j * insC();
for (int i = 1; i <= m; i++)
{
int j;
//recurrence
for (j = 1; j <= n; j++)
fone[i][j] =
min(modC(s1[i - 1], s2[j - 1]) + fone[i - 1][j - 1],
min(delC() + fone[i - 1][j], insC() + fone[i][j - 1]));
}
int i = m, j = n;
cost += fone[i][j];
/*
* This code can be shortened as beforehand we know one of the string has length one but this gives general idea of a
* how a backtracking can be done is case of general strings length given we can use m*n space
*/
//backtracking in case the length is one of string
while (true)
{
if (i == 0 || j == 0)
break;
//fone[i][j] will have one of the three above values from which it is derived so comapring from each one
if (i >= 0 && j >= 0 && fone[i][j] == modC(s1[i - 1], s2[j - 1]) + fone[i - 1][j - 1])
{
sa.push_back(s1[i - 1]);
sb.push_back(s2[j - 1]);
i--; j--;
}
else if ((i - 1) >= 0 && j >= 0 && fone[i][j] == delC() + fone[i - 1][j])
{
sa.push_back(s1[i - 1]);
sb.push_back('-');
i -= 1;
}
else if (i >= 0 && (j - 1) >= 0 && fone[i][j - 1] == insC() + fone[i][j - 1])
{
sa.push_back('-');
sb.push_back(s2[j - 1]);
j -= 1;
}
}
//continue backtracking
if (i != 0)
while (i)
{
sa.push_back(s1[i - 1]);
sb.push_back('-');
i--;
}
else
while (j)
{
sa.push_back('-');
sb.push_back(s2[j - 1]);
j--;
}
//strings obtained are reversed alignment because we have started from i = m, j = n
reverse(sa.begin(), sa.end());
reverse(sb.begin(), sb.end());
return make_pair(sa, sb);
}
//getting the cost associated with alignment
vector<int> SpaceEfficientAlignment(string s1, string s2)
{
//space efficient version
int m = s1.length();
int n = s2.length();
vector<vector<int>> array2d(m + 5, vector<int>(2));
//base conditions
for (int i = 0; i <= m; i++)
array2d[i][0] = i * (delC());
for (int j = 1; j <= n; j++)
{
array2d[0][1] = j * (insC());
//recurrence
for (int i = 1; i <= m; i++)
array2d[i][1] =
min(modC(s1[i - 1], s2[j - 1]) + array2d[i - 1][0],
min(delC() + array2d[i - 1][1], insC() + array2d[i][0]));
for (int i = 0; i <= m; i++)
array2d[i][0] = array2d[i][1];
}
//returning the last column to get the row element x in n/2 column: see GainAlignment function
vector<int> vec(m + 1);
for (int i = 0; i <= m; i++)
vec[i] = array2d[i][1];
return vec;
}
pair<string, string> GainAlignment(string s1, string s2)
{
string te1, te2; //for storing alignments
int l1 = s1.length();
int l2 = s2.length();
//trivial cases of length = 0 or length = 1
if (l1 == 0)
for (int i = 0; i < l2; i++)
{
te1.push_back('-');
te2.push_back(s2[i]);
cost += insC();
}
else if (l2 == 0)
for (int i = 0; i < l1; i++)
{
te1.push_back(s1[i]);
te2.push_back('-');
cost += delC();
}
else if (l1 == 1 || l2 == 1)
{
pair<string, string> temp = stringOne(s1, s2);
te1 = temp.first;
te2 = temp.second;
}
//main divide and conquer
else
{
int ymid = l2 / 2;
/*
* We know edit distance problem can be seen as shortest path from initial(0,0) to (l1,l2)
* Now, here we are seeing it in two parts from (0,0) to (i,j) and from (i+1,j+1) to (m,n)
* and we will see for which i it is getting minimize.
*/
vector<int> ScoreL = SpaceEfficientAlignment(s1, s2.substr(0, ymid)); //for distance (0,0) to (i,j)
vector<int> ScoreR = SpaceEfficientAlignment(rever(s1), rever(s2.substr(ymid, l2 - ymid))); //for distance (i+1,j+1) to (m,n)
int xmid = minimize(ScoreL, ScoreR, l1); //minimizing the distance
pair<string, string> temp = GainAlignment(s1.substr(0, xmid), s2.substr(0, ymid));
te1 = temp.first; te2 = temp.second; //storing the alignment
temp = GainAlignment(s1.substr(xmid, l1 - xmid), s2.substr(ymid, l2 - ymid));
te1 += temp.first; te2 += temp.second; //storing the alignment
}
return make_pair(te1, te2);
}
int main()
{
string s1, s2;
s1 = "GCCCTAGCG";
s2 = "GCGCAATG";
//cin >> s1 >> s2; /*standard input stream*/
/*
* If reading from strings from two files
*/
// ifstream file1("file1.txt");
// ifstream file2("file2.txt");
// getline(file1, s1);
// file1.close();
// getline(file2, s2);
// file2.close();
pair<string, string> temp = GainAlignment(s1, s2);
//Alignments can be different for same strings but cost will be same
cout << "Alignments of strings\n";
cout << temp.first << "\n";
cout << temp.second << "\n";
cout << "Cost associated = " << cost << "\n";
/* Alignments
* M - modification, D - deletion, I - insertion for converting string1 to string2
*
* M M MD
* string1 - GCCCTAGCG
* string2 - GCGCAAT-G
*
*/
}
|
code/dynamic_programming/src/egg_dropping_puzzle/README.md | # Egg Dropping Puzzle
## Description
For a `H`-floor building, we want to know which floors are
safe to drop eggs from without broking them and which floors
aren't. There are a few assumptions:
- An egg that survives a fall can be used again.
- A broken egg must be discarded.
- The effect of a fall is the same for all eggs.
- If an egg breaks when dropped, then it would break if dropped from a higher window.
- If an egg survives a fall, then it would survive a shorter fall.
- It is not ruled out that the first-floor windows break eggs,
nor is it ruled out that eggs can survive the Hth-floor windows.
Having `N` eggs available, what is the **minimum** number of egg drops needed
to find the critical floor in the **worst case**?
## Solution
We can define the state of the dynamic programming model as being a pair `(n, k)`,
where `n` is the number of eggs available and `k` is the number of consecutive floors
that need to be tested.
Let `f(n,k)` be the minimum number of attempts needed to find the critical floor in the
worst case with `n` eggs available and with `k` consecutive floors to be tested.
Attempting to drop an egg for each floor `x` leads to two possibilities:
- The egg breaks from floor `x`: then we lose an egg but have to check only the floors
lower than `x`, reducing the problem to `n-1` eggs and `x-1` floors.
- The egg does not break: then we continue with `n` eggs at our disposal and have to
check only the floors higher than `x`, reducing the problem to `n` eggs and `k-x` floors.
As we want to know the number of trials in the *worst case*, we consider the maximum of the
two possibilities, that is `max( f(n-1, x-1), f(n, k-x) )`.
And as we want to know the *minimum* number of trials, we choose the floor that leads to
the minimum number of attempts. So:
```
f(n, k) = 1 + min( max( f(n-1, x-1), f(n, k-x) ) , 1 <= x <= h )
```
And the base cases are:
```
f(n, 0) = 0 // if there is no floor, no attempt is necessary
f(n, 1) = 1 // if there is only one floor, just one attempt is necessary
f(1, k) = k // with only one egg, k attempts are necessary
```
By using memoization or tabulation, the complexity of the algorithm becomes `O(n * k^2)`, as the number of states is `n*k` and the cost of computing a state is `O(k)`.
---
<p align=center>
A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.c | #include <stdio.h>
#include <string.h>
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define MAX_EGGS 100
#define MAX_FLOORS 100
#define INF 1000000000
int memo[MAX_EGGS][MAX_FLOORS];
int
eggDrop(int n, int k)
{
if (k == 0)
return (0);
if (k == 1)
return (1);
if (n == 1)
return (k);
if (memo[n][k] > -1)
return (memo[n][k]);
int ans = INF, h;
for (h = 1; h <= k; ++h)
ans = min(ans, max(eggDrop(n - 1, h - 1), eggDrop(n, k - h)));
return (memo[n][k] = ans + 1);
}
int
main()
{
memset(memo, -1, sizeof(memo));
int n, k;
printf("Enter number of eggs: ");
scanf("%d", &n);
printf("Enter number of floors: ");
scanf("%d", &k);
printf("Minimum Number of attempts required in Worst case = %d \n", eggDrop(n,k));
return (0);
}
|
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#define MAX_EGGS 100
#define MAX_FLOORS 100
#define INF 1000000000
using namespace std;
int memo[MAX_EGGS][MAX_FLOORS];
/*
* Returns the minimum number of attempts
* needed in the worst case for n eggs
* and k floors.
* Time complexity: O(n*k^2)
*/
int eggDrop(int n, int k)
{
// base cases
if (k == 0)
return 0; // if there is no floor, no attempt is necessary
if (k == 1)
return 1; // if there is only one floor, just one attempt is necessary
if (n == 1)
return k; // with only one egg, k attempts are necessary
// check if it is already computed
if (memo[n][k] > -1)
return memo[n][k];
int ans = INF;
// attempt to drop an egg at each height from 1 to k
for (int h = 1; h <= k; ++h)
ans = min(ans, max( // get worst case from:
eggDrop(n - 1, h - 1), // case in which egg breaks
eggDrop(n, k - h) // case in which egg does not break
));
return memo[n][k] = ans + 1; // store minimum value
}
int main()
{
for (int i = 0; i < MAX_EGGS; ++i)
for (int j = 0; j < MAX_FLOORS; ++j)
memo[i][j] = -1;
cout << eggDrop(2, 100) << '\n';
cout << eggDrop(10, 5) << '\n';
cout << eggDrop(10, 100) << '\n';
return 0;
}
|
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.cs | /* Part of Cosmos by OpenGenus Foundation */
using System;
class cosmos {
/* Function to get minimum number of */
/* trials needed in worst case with n */
/* eggs and k floors */
static int eggDrop(int n, int k)
{
// If there are no floors, then
// no trials needed. OR if there
// is one floor, one trial needed.
if (k == 1 || k == 0)
return k;
// We need k trials for one egg
// and k floors
if (n == 1)
return k;
int min = int.MaxValue;
int x, res;
// Consider all droppings from
// 1st floor to kth floor and
// return the minimum of these
// values plus 1.
for (x = 1; x <= k; x++) {
res = Math.Max(eggDrop(n - 1, x - 1),
eggDrop(n, k - x));
if (res < min)
min = res;
}
return min + 1;
}
// Driver code
static void Main()
{
int n = 2, k = 10;
Console.Write("Minimum number of "
+ "trials in worst case with "
+ n + " eggs and " + k
+ " floors is " + eggDrop(n, k));
}
}
|
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.hs | --- Part of Cosmos by OpenGenus Foundation
eggDropping :: Int -> Int -> Int
eggDropping floors eggs = d floors eggs
where m = floors
n = eggs
d floors' 1 = floors'
d 1 _ = 1
d 0 _ = 0
d _ 0 = error "No eggs left"
d floors' eggs' = minimum [1 + maximum [ table!(floors'-i, eggs')
, table!(i-1, eggs'-1)
]
| i <- [1..floors']
]
table = listArray bounds
[d i j | (i, j) <- range bounds] -- 2D array to store intermediate results
bounds = ((0, 0), (m, n))
|
code/dynamic_programming/src/egg_dropping_puzzle/egg_dropping_puzzle.py | # Part of Cosmos by the Open Genus Foundation
# A Dynamic Programming based Python Program for the Egg Dropping Puzzle
INT_MAX = 32767
def eggDrop(n, k):
eggFloor = [[0 for x in range(k + 1)] for x in range(n + 1)]
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
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
return eggFloor[n][k]
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))
)
|
code/dynamic_programming/src/egg_dropping_puzzle/eggdroppingpuzzle.java |
//Dynamic Programming solution for the Egg Dropping Puzzle
/* Returns the minimum number of attempts
needed in the worst case for a eggs and b floors.*/
import java.util.*;
public class EggDroppingPuzzle {
// min trials with a eggs and b floors
private static int minTrials(int a, int b) {
int eggFloor[][] = new int[a + 1][b + 1];
int result, x;
for (int i = 1; i <= a; ++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 <= b; ++j) {
eggFloor[1][j] = j;
}
for (int i = 2; i <= a; ++i) {
for (int j = 2; j <= b; ++j) {
eggFloor[i][j] = Integer.MAX_VALUE;
for (x = 1; x <= j; ++x) {
// get worst case from:case in which egg break (eggFloor[i-1][x-1]) and case in which egg does not break (eggFloor[i][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[a][b];
}
//testing the program
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of eggs");
int a = Integer.parseInt(sc.nextLine());
System.out.println("Enter no. of floors");
int b = Integer.parseInt(sc.nextLine());
//result outputs min no. of trials in worst case for a eggs and b floors
int result = minTrials(a, b);
System.out.println("Minimum number of attempts needed in Worst case with a eggs and b floor are: " + result);
}
}
|
code/dynamic_programming/src/factorial/factorial.c | #include <stdio.h>
int
factorial(int n)
{
if (n == 0 || n == 1)
return (1);
else
return (n * factorial(n - 1));
}
int
main()
{
int n;
printf("Enter a Whole Number: ");
scanf("%d", &n);
printf("%d! = %d\n", n, factorial(n));
return (0);
}
|
code/dynamic_programming/src/factorial/factorial.cpp | //Part of Cosmos by OpenGenus Foundation
#include <iostream>
using namespace std;
int factorial(int n)
{
//base case
if (n == 0 || n == 1)
{
return 1;
}
// recursive call
return (n * factorial(n - 1));
}
int main()
{
int n;
cout << "Enter a number";
//Taking input
cin >> n;
//printing output
cout << "Factorial of n :" << factorial(n) << endl;
}
|
code/dynamic_programming/src/factorial/factorial.exs | defmodule Factorial do
def factorial(0), do: 1
def factorial(1), do: 1
def factorial(num) when num > 1 do
num * factorial(num - 1)
end
end
|
code/dynamic_programming/src/factorial/factorial.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
func factorial(num int) int {
if num == 0 {
return 1
}
return (num * factorial(num-1))
}
func main() {
num := 5
fmt.Println(factorial(num))
}
|
code/dynamic_programming/src/factorial/factorial.java | /* Part of Cosmos by OpenGenus Foundation */
/**
* Implements factorial using recursion
*/
public class Factorial {
private static int factorial(int num) {
if (num == 0) {
return 1;
} else {
return (num * factorial(num - 1));
}
}
public static void main(String[] args) {
int number = 5;
int result;
result = factorial(number);
System.out.printf("The factorial of %d is %d", number, result);
}
}
|
code/dynamic_programming/src/factorial/factorial.js | function factorialize(number) {
if (number == 0) {
return 1;
} else {
return number * factorialize(number - 1);
}
}
factorialize(5);
/*replace the value of 5 with whatever value you
*want to find the factorial of
*/
|
code/dynamic_programming/src/factorial/factorial.md | ## Fibonacci Series implemented using dynamic programming
- If you do not know what **Fibonacci Series** is please [visit](https://iq.opengenus.org/calculate-n-fibonacci-number/) to get an idea about it.
- If you do not know what **dynamic programming** is please [visit](https://iq.opengenus.org/introduction-to-dynamic-programming/) to get an idea about it.
### Let's go step by step i.e code block by code block
The underlying concept for finding the factorial of a number *n* is :
- ```cpp n! = n*(n-1)*(n-2)*......*2*1 ``` for all i>1
- Which can also be written as ```cpp n! = n*((n-1)!)``` for all i>1
- And the initial case is :
- ```cpp 0! = 0 ``` (If you are curious about why this is the case, [checkout](https://iq.opengenus.org/factorial-of-large-numbers/))
- ```cpp 1! = 1 ```
The block of code below does exactly what we discussed above but using recursion.
```cpp
if (n == 0 || n == 1)
{
return 1;
}
return (n * factorial(n - 1));
```
The main function takes an input for the number *n* and calls the **factorial(n)** function, which has an if condition to check if it's the base condition i.e if *n* is 0 or 1, and return 1, otherwise it returns ```cpp (n * factorial(n - 1))```, which means that it call **factorial(n-1)** and waits for it to return and multiplies this with n and returns **n!**.
The recursion can be explained with the below diagram.
```cpp
main()
| ^
V | (return n*factorial(n-1))
factorial(n)
| ^
V | (return (n-1)*factorial(n-2))
factorial(n-1)
| ^
V | (return (n-2)*factorial(n-3))
factorial(n-2)
.
.
.
.
.
.
| ^
V | (return 2*factorial(1) = 2 * 1 = 2)
factorial(1)
( We know factorial(1) = 1 )
```
|
code/dynamic_programming/src/factorial/factorial.py | # Part of Cosmos by OpenGenus Foundation
from functools import wraps
def memo(f):
"""Memoizing decorator for dynamic programming."""
@wraps(f)
def func(*args):
if args not in func.cache:
func.cache[args] = f(*args)
return func.cache[args]
func.cache = {}
return func
@memo
def factorial(num):
"""Recursively calculate num!."""
if num < 0:
raise ValueError("Negative numbers have no factorial.")
elif num == 0:
return 1
return num * factorial(num - 1)
|
code/dynamic_programming/src/factorial/factorial.rs | // Part of Cosmos by OpenGenus Foundation
fn factorial(n: u64) -> u64 {
match n {
0 => 1,
_ => n * factorial(n - 1)
}
}
fn main() {
for i in 1..10 {
println!("factorial({}) = {}", i, factorial(i));
}
}
|
code/dynamic_programming/src/factorial/factorial.scala | /* Part of Cosmos by OpenGenus Foundation */
import scala.annotation.tailrec
/**
* Implement factorial using tail recursion
*/
object main {
@tailrec
private def _factorial(of: Int, current: Int): Int = {
if (of == 0) {
current
} else {
_factorial(of - 1, of * current)
}
}
def factorial(of: Int): Int = {
_factorial(of, 1)
}
def main(args: Array[String]) = {
val number: Int = 5
println(s"The factorial of ${number} is ${factorial(number)}")
}
}
|
code/dynamic_programming/src/fibonacci/fibonacci.c | #include<stdio.h>
int fib(int n)
{
int f[n+2]; // 1 extra to handle case, n = 0
int i;
f[0] = 0;
f[1] = 1;
for (i = 2; i <= n; i++)
{
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
int main ()
{
int n = 9;
printf("%d", fib(n));
getchar();
return 0;
}
|
code/dynamic_programming/src/fibonacci/fibonacci.cpp | // Part of Cosmos by OpenGenus
#include <iostream>
using namespace std;
int fib(int n)
{
int *ans = new int[n + 1]; //creating an array to store the outputs
ans[0] = 0;
ans[1] = 1;
for (int i = 2; i <= n; i++)
{
ans[i] = ans[i - 1] + ans[i - 2]; // storing outputs for further use
}
return ans[n];
}
int main()
{
int n;
cout << "Enter the Number:"; // taking input
cin >> n;
int output = fib(n);
cout << "Nth fibonacci no. is:" << output << endl; //printing nth fibonacci number
} |
code/dynamic_programming/src/fibonacci/fibonacci.exs | defmodule Fibonacci do
def fib(terms) do
if terms <= 0 do
{:error, :non_positive}
else
{fib_list, _} =
Enum.map_reduce(1..terms, {0, 1}, fn
1, _acc -> {1, {1, 1}}
_t, {n1, n2} -> {n1 + n2, {n1 + n2, n1}}
end)
Enum.each(fib_list, fn f -> IO.puts("#{f}") end)
end
end
end
|
code/dynamic_programming/src/fibonacci/fibonacci.go | package dynamic
// NthFibonacci returns the nth Fibonacci Number
func NthFibonacci(n uint) uint {
if n == 0 {
return 0
}
// n1 and n2 are the (i-1)th and ith Fibonacci numbers, respectively
var n1, n2 uint = 0, 1
for i := uint(1); i < n; i++ {
n3 := n1 + n2
n1 = n2
n2 = n3
}
return n2
} |
code/dynamic_programming/src/fibonacci/fibonacci.java | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Number:"); // taking input
int n = input.nextInt();
int output = fib(n);
System.out.println("Nth fibonacci no. is: " + output);
}
public static int fib(int n) {
int[] fibNumber = new int[n + 1]; // creating an array to store the outputs
fibNumber[0] = 0;
fibNumber[1] = 1;
for (int i = 2; i <= n; i++) {
fibNumber[i] = fibNumber[i - 1] + fibNumber[i - 2]; // storing outputs for further use
}
return fibNumber[n];
}
}
|
code/dynamic_programming/src/fibonacci/fibonacci.js | // Problem Statement(1): Find the nth Fibonacci number
// 1.a.Using Recusrion to find the nth fibonacci number
const FibonacciNumberRec = (num) => {
if (num <= 1)
return num;
return FibonacciNumberRec(num - 1) + FibonacciNumberRec(num - 2);
}
// 1.b.Using DP to find the nth fibonacci number
// fib[n] = fib[n - 1] + fib[n - 2]
const FibonacciNumberDP = (num) => {
let fib = [0, 1] // fib[0] = 0, fib[1] = 1
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib[num]; // return num'th fib number
}
// 2.Print the fibonacci series upto nth Fibonacci number
const FibonacciSeries = (num) => {
let fib = [0, 1] // fib[0] = 0, fib[1] = 1
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib;
}
// Call the functions
let n = 6
console.log(`The ${n}th Fibonacci Number is ${FibonacciNumberRec(n)}`);
n = 8
console.log(`The ${n}th Fibonacci Number is ${FibonacciNumberDP(n)}`);
n = 10
console.log(`The Fibonacci Series upto ${n}th term is ${FibonacciSeries(n)}`);
// I/O:
// 1.a) n = 6
// Output :
// The 6th Fibonacci Number is 8
// 1.b) n = 8
// The 8th Fibonacci Number is 21
// 2. n = 10
// The Fibonacci Series upto 10th term is 0,1,1,2,3,5,8,13,21,34,55
// Note:This is 0-based i.e, fib[0] = 0, fib[1] = 1, fib[2] = 0 + 1 = 1, fib[3] = 1 + 1 = 2
|
code/dynamic_programming/src/fibonacci/fibonacci.md | ## Fibonacci Series implemented using dynamic programming
- If you do not know what **Fibonacci Series** is please [visit](https://iq.opengenus.org/calculate-n-fibonacci-number/) to get an idea about it.
- If you do not know what **dynamic programming** is please [visit](https://iq.opengenus.org/n-th-fibonacci-number-using-dynamic-programming/) to get an idea about it.
### Let's go step by step i.e code block by code block
To get first *n* Fibonnaci numbers, we first create an array of size n
```cpp
int *ans = new int[n + 1];
```
Since the underlying concept for Fibonnaci Series is that :
- ```cpp F[i] = F[i-1] + F[i-2] ``` for all i>1
- And the initial case is :
- ```cpp F[0] = 0 ```
- ```cpp F[1] = 1 ```
The block of code below does exactly what we discussed above i.e initialise for 0,1 and then iterate from 2 to n and calculate the Fibonnaci Series using the concept of ```cpp F[i] = F[i-1] + F[i-2] ``` for all i>1.
```cpp
ans[0] = 0;
ans[1] = 1;
for (int i = 2; i <= n; i++)
{
ans[i] = ans[i - 1] + ans[i - 2];
}
```
The main function takes an input for the number *n* i.e the number of first *n* Fibonacci Numbers and calls the **fib()** function to get the array of first *n* Fibonnaci Numbers.
|
code/dynamic_programming/src/fibonacci/fibonacci.py | from sys import argv
def fibonacci(n):
"""
N'th fibonacci number using Dynamic Programming
"""
arr = [0, 1] # 1st two numbers as 0 and 1
while len(arr) < n + 1:
arr.append(0)
if n <= 1:
return n
else:
if arr[n - 1] == 0:
arr[n - 1] = fibonacci(n - 1)
if arr[n - 2] == 0:
arr[n - 2] = fibonacci(n - 2)
arr[n] = arr[n - 2] + arr[n - 1]
return arr[n]
if __name__ == "__main__":
if len(argv) < 2:
print("Usage: python3 fibonacci.py <N>")
print(fibonacci(int(argv[1])))
|
code/dynamic_programming/src/friends_pairing/friends_pairing.c | // Dynamic Programming solution to friends pairing problem in C
// Contributed by Santosh Vasisht
// Given n friends, each one can remain single or can be paired up with some other friend.
// Each friend can be paired only once.
// Find out the total number of ways in which friends can remain single or can be paired up.
#include <stdio.h>
#include <stdlib.h>
int countFriendsPairings(int n)
{
int table[n+1];
// Filling the table recursively in bottom-up manner
for(int i = 0; i <= n; ++i)
{
if(i <= 2)
table[i] = i;
else
table[i] = table[i-1] + (i-1) * table[i-2];
}
return table[n];
}
//Driver code
int main()
{
int n = 7;
printf("%d\n", countFriendsPairings(n));
return 0;
} |
code/dynamic_programming/src/friends_pairing/friends_pairing.cpp | // Dynamic Programming solution to friends pairing problem in C++
// Contributed by Santosh Vasisht
// Given n friends, each one can remain single or can be paired up with some other friend.
// Each friend can be paired only once.
// Find out the total number of ways in which friends can remain single or can be paired up.
#include <bits/stdc++.h>
using namespace std;
int countFriendsPairings(int n)
{
int table[n+1];
// Filling the table recursively in bottom-up manner
for(int i = 0; i <= n; ++i)
{
if(i <= 2)
table[i] = i;
else
table[i] = table[i-1] + (i-1) * table[i-2];
}
return table[n];
}
// Driver code
int main()
{
int n = 7;
cout << countFriendsPairings(n) << endl;
return 0;
} |
code/dynamic_programming/src/friends_pairing/friends_pairing.py | # Dynamic Programming solution to friends pairing problem in Python3
# Contributed by Santosh Vasisht
# Given n friends, each one can remain single or can be paired up with some other friend.
# Each friend can be paired only once.
# Find out the total number of ways in which friends can remain single or can be paired up.
def countFriendsPairings(n: int) -> int:
table = [0] * (n+1)
# Filling the table recursively in bottom-up manner
for i in range(n+1):
if i <= 2:
table[i] = i
else:
table[i] = table[i-1] + (i-1) * table[i-2]
return table[n]
#Driver Code
if __name__ == '__main__':
n = 7
print(countFriendsPairings(n)) |
code/dynamic_programming/src/house_robber/HouseRobber.cpp | // Below is the solution of the same problem using C++
int rob(vector<int>& nums) {
if(nums.size()==0)
return 0;
if(nums.size()==1)
return nums[0];
int res[nums.size()];
res[0]=nums[0];
res[1]=max(nums[0],nums[1]);
for(int i=2;i<nums.size();i++)
{
res[i]=max(res[i-1],nums[i]+res[i-2]);
}
return res[nums.size()-1];
}
|
code/dynamic_programming/src/house_robber/HouseRobber.java | import java.util.Arrays;
class HouseRobber {
public static int rob(int[] nums) {
int len = nums.length;
if(len == 0) return 0;
if(len == 1) return nums[0];
if(len == 2) return Math.max(nums[0], nums[1]);
int memo[] = new int [len];
memo[0] = nums[0];
memo[1] = Math.max(nums[0], nums[1]);
System.out.println("Memo before robbing: " + Arrays.toString(memo) + "\n");
for(int i=2; i<len; i++){
System.out.println("Visiting house no. " + (i+1));
int choice1 = nums[i] + memo[i-2];
int choice2 = memo[i-1];
System.out.println("choice 1 (rob this house and 2nd before) : " + choice1);
System.out.println("choice 2 (max of previous two houses) : " + choice2);
memo[i] = Math.max(choice1, choice2);
System.out.println("Memo after robbing: " + Arrays.toString(memo) + "\n");
}
return memo[len-1];
}
public static void main(String args[]){
int input[] = new int[]{1,2,3,4};
System.out.println("Houses with given stash on a street: " + Arrays.toString(input));
int stolenAmount = rob(input);
System.out.println("Max amount stolen by robber: " + stolenAmount);
}
}
|
code/dynamic_programming/src/house_robber/HouseRobber.js | /**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
// Tag: DP
const dp = [];
dp[0] = 0;
dp[1] = 0;
for (let i = 2; i < nums.length + 2; i++) {
dp[i] = Math.max(dp[i - 2] + nums[i - 2], dp[i - 1]);
}
return dp[nums.length + 1];
};
|
code/dynamic_programming/src/house_robber/README.md | # House Robber
## Description
Given a list of non-negative integers representing the amount of money in a house, determine the maximum amount of money a robber can rob tonight given that he cannot rob adjacent houses.
## Solution
e.g [1,2,3]<br>
Considering the constraint,<br>
robber has choice 1: houses with amount 1 and 3<br>
Or choice 2: house with amount 2<br>
Thus, 1st choice gives the maximum amount of money.<br>
Considering n is the current house to be robbed<br>
choice 1: memo[n]+memo[n-2]<br>
choice 2: memo[n-1]<br>
The solution can be represented as the following expression:<br>
Maximum((memo[n]+memo[n-2]), memo[n-1])<br>
## Time and Space complexity
Time complexity: O(n), n is number of elements in the input array<br>
Space complexity: O(n), space is required for the array
|
code/dynamic_programming/src/knapsack/Knapsack_DP_all3tech.cpp | ///////////////////////////////RECURSIVE APPROACH////////////////////////////////////////////////////////
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int knapSack(int W,int *wt,int *val,int n)
{
if(n==0||W==0)
{
return 0;
}
if(wt[n]<=W)
{
return max(val[n]+knapSack(W-wt[n],wt,val,n-1),knapSack(W,wt,val,n-1));
//(jab le liya uss wt ko, jab nhi liya uss wt ko)
//(liya to uska price + baki bacha hua ka price, nhi liya to baki bacha hua ka price)
//dono ka max nikalo(...,....)
}
else if(wt[n]>W)
{
return knapSack(W,wt,val,n-1);
//jab W bada hai to bag me aega hi nhi to baki bacha hua part pe call karenge function
}
}
int main() {
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
cout << knapSack(W, wt, val, n-1);
return 0;
}
//////////////////////////////////////MEMOIZATION APPROACH//////////////////////////////////////////////
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//memoisation = recursion + dp table ka use store karne ke liye
int knapSack(int W,int *wt,int *val,int n,int **t)
{
if(n==0||W==0)
{
t[n][W]=0;
return t[n][W];
}
if(t[n][W]!=-1)
{
return t[n][W];
//agar -1 ki jagha ko value hai to seedha usse return karwa do
}
if(wt[n]<=W)
{
t[n][W]=max(val[n]+knapSack(W-wt[n],wt,val,n-1,t),knapSack(W,wt,val,n-1,t));
return t[n][W];
//agar -1 hai to recurssive call to karni padegi
//aur uss jagha pe vo value store ho jaegi
}
else if(wt[n]>W)
{
t[n][W]=knapSack(W,wt,val,n-1,t);
return t[n][W];
//agar -1 hai to recurssive call to karni padegi
//aur uss jagha pe vo value store ho jaegi
}
return -1;
}
int main()
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
// int t[4][52]={-1};
int n = sizeof(val) / sizeof(val[0]);
////////////////////////////////////////
//to declare table dynamically
int **t;
t= new int*[n];
for (int i = 0; i < n; i++)
{
t[i] = new int[W + 1];
//we are creating cols for each row
}
for (int i = 0; i <n; i++)
{
for (int j = 0; j < W + 1; j++)
{
t[i][j] = -1;
//initializing to -1
}
}
//////////////////////////////////////
cout <<knapSack(W, wt, val, n-1,t);
return 0;
}
//////////////////////////////////////////TOP DOWN APPROACH/////////////////////////////////////////////
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//top-down approach me sabse pehli baat matrix banate
//matrix bananne se pehle recursion wala code likho
//usme jo variable change hore honge na uski table banegi
//table ka size n+1 w+1 karne ka rehta hai
//recurssion me jo base condition hoti hai usko hum top down me initialize ke roop me use karte
//that is jab T[0][0] to value 0 kar diya isme matlab (recurssion me jab n==0||w==0 then return 0 kiya tha.)
//table me ek point like 2,3 hume kya represent karta hai
//2 hume bataega ki bhai humne pehle 2 item liya hai
//aur 3 hume bataega uska weight matlab 3 wt ka bag hai
//aur item 1 item 2 diya rakha hai to ab muje max profit itna tak ka batao
//jab hum ye store kar diye to ye stored value humko aage wale i(items n),j(W) ke liye kaam aega
//so sabse pehle recursion fir ya to memoizaition ya top down
//top down me stack overflow hone ka chance nhi rehta to usse best mana jata haiii!
int knapSack(int W,int *wt,int *val,int n,int **t)
{
//yaha i denotes n (num of item) and j denotes W (weight)
for(int i=0;i<n+1;i++)
{
for(int j=0;j<W+1;j++)
{
if(i==0||j==0)
{
t[i][j]=0;
}
else if(wt[i]<=W)
{
t[i][j]=max(val[i]+t[i-1][j-wt[i]],t[i-1][j]);
//max(jab include kiya,include nhi kiya)
}
else if(wt[i]>W)
{
t[i][j]=t[i-1][j];
}
}
}
return t[n][W];
}
int main()
{
int val[] = { 60, 100, 120 };
int wt[] = { 10, 20, 30 };
int W = 50;
// int t[4][52]={-1};
int n = sizeof(val) / sizeof(val[0]);
////////////////////////////////////////
//to declare table dynamically
int **t;
t= new int*[n];
for (int i = 0; i < n; i++)
{
t[i] = new int[W + 1];
//we are creating cols for each row
}
//////////////////////////////////////
cout <<knapSack(W, wt, val, n-1,t);
return 0;
}
|
code/dynamic_programming/src/knapsack/README.md | # 0-1 Knapsack
## Description
Given `n` items, in which the `i`th item has weight `wi` and value `vi`,
find the maximum total value that can be put in a knapsack of capacity `W`.
You cannot break an item, either pick the complete item, or don't pick it.
## Solution
This is a dynamic programming algorithm.
We first start by building a table consisting of rows of weights and columns of values.
Starting from the first row and column, we keep on filling the table till the desired value is obtained.
Let the table be represented as `M[n, w]` where `n` is the number of objects included
and `w` is the left over space in the bag.
For every object, there can be two possibilities:
- If the object's weight is greater than the leftover space in the bag,
then `M[n, w]` = `M[n - 1, w]`
- Else,
the object might be taken or left out.
- If it is taken, the total value of the bag becomes
`M[n, w]` = `vn` + `M[n - 1, w - wn]`, where `vn` is value of the `n`th object and `wn` is its weight.
- Or if the object is not included,
`M[n, w]` = `M[n - 1, w]`
The value of `M[n,w]` is the maximum of both these cases.
In short, the optimal substructure to compute `M[n, w]` is:
```
M[n, w] = M[n-1, w], if wn > w
max( M[n-1, w], vn + M[n-1, w - wn] ), otherwise
```
The complexity of above algorithm is `O(n*W)`, as there are `n*W` states and each state is computed in `O(1)`.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/knapsack/knapsack.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
#define MAX 10
#define MAXIMUM(a, b) a > b ? a : b
void
Knapsack(int no, int wt, int pt[MAX], int weight[MAX])
{
int knap[MAX][MAX], x[MAX] = {0};
int i, j;
//For item
for (i = 0; i <=no; i++)
knap[i][0] = 0;
//For weight
for (i = 0; i <=wt; i++)
knap[0][i] = 0;
for (i = 1; i <= no; i++)
for (j = 1; j <= wt; j++) {
if ((j - weight[i]) < 0)
knap[i][j] = knap[i - 1][j];
else
knap[i][j] = MAXIMUM(knap[i - 1][j], pt[i] + knap[i - 1][j - weight[i]]);
}
printf("Max Profit : %d \n", knap[no][wt]);
printf("Edges are :\n");
for (i = no; i >= 1; i--)
if (knap[i][wt] != knap[i-1][wt]) {
x[i] = 1;
wt -= weight[i];
}
for (i = 1; i <= no; i++)
printf("%d\t", x[i]);
printf ("\n");
}
int
main(int argc, char *argv[])
{
int no, wt, pt[MAX] = {0}, weight[MAX] = {0};
int i;
printf("Enter the no of objects :\n");
scanf("%d", &no);
printf("Enter the total weight :\n");
scanf("%d", &wt);
printf("Enter the weights\n");
for (i = 1; i <= no; i ++)
scanf("%d", &weight[i]);
printf("Enter the profits\n");
for (i = 1; i <= no; i ++)
scanf("%d", &pt[i]);
Knapsack(no, wt, pt, weight);
return (0);
}
|
code/dynamic_programming/src/knapsack/knapsack.cpp | /*
*
* Part of Cosmos by OpenGenus Foundation
*
* Description:
* 1. We start with i = 0...N number of considered objects, where N is the
* total number of objects we have. Similarly, for the capacity of bag we
* go from b = 0...B where B is maximum capacity.
* 2. Now for each pair of (i, b) we compute the subset of objects which will
* give us the maximum value, starting from i = 1 to N and b from 0 to B.
* 3. We compute a "dp" where dp[i][b] will give us the maximum value when
* we consider the first i elements and the weight is b.
* 4. We take a bottom-up approach, first filling dp[0][...] = 0 (we consider 0 elements)
* and dp[...][0] = 0 (as capacity of bag is 0, value will be 0).
* 5. Now, for each (i, b) we either include the 'i'th object or we do not.
* dp[i][b] is the max of both these approaches.
* Case 1: If we do not include the 'i'th object, our max value will be the same
* as that for first (i - 1) objects to be filled in capacity b.
* i.e. dp[i - 1][b]
* Case 2: If we do include the 'i'th object, we need to clear space for it. For this,
* we compute the best score when the first (i - 1) objects were made to fit in
* a bag of capacity (b - Wi) where Wi is the weight of ith object. We add the
* value of ith object to this score. If Vi denotes the value of ith object, the
* best possible score after includig object i is:
* dp[i - 1][b - Wi] + Vi
* 6. We get the formula: dp[i][b] = max(dp[i-1][b], dp[i-1][b-Wi] + Vi)
* As we have computed the base cases dp[0][...] and dp[...][0] we can use this formula
* for the rest of the table and our required value will be dp[N][B].
*
*/
#include <utility>
#include <iostream>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define MOD 1000000007
#define INF 1000000000
#define pb push_back
#define sz size()
#define mp make_pair
//cosmos: knapsack 0-1
int knapsack(int value[], int weight[], int n_items, int maximumWeight)
{
// dp[N + 1][B + 1] to accommodate base cases i = 0 and b = 0
int dp[n_items + 1][maximumWeight + 1];
// Base case, as we consider 0 items, value will be 0
for (int w = 0; w <= maximumWeight; w++)
dp[0][w] = 0;
// We consider weight 0, therefore no items can be included
for (int i = 0; i <= n_items; i++)
dp[i][0] = 0;
// Using formula to calculate rest of the table by base cases
for (int i = 1; i <= n_items; i++)
for (int w = 1; w <= maximumWeight; w++)
{
// Only consider object if weight of object is less than allowed weight
if (weight[i - 1] <= w)
dp[i][w] = max(value[i - 1] + dp[i - 1][w - weight[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
return dp[n_items][maximumWeight];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int value[] = {12, 1000, 30, 10, 1000};
int weight[] = {19, 120, 20, 1, 120};
int n_items = 5;
int maximumWeight = 40;
cout << knapsack(value, weight, n_items, maximumWeight) << endl; //values of the items, weights, number of items and the maximum weight
return 0;
}
|
code/dynamic_programming/src/knapsack/knapsack.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
/*
Exptected output:
The value list is [12 34 1 23 5 8 19 10]
The weight list is [5 4 3 7 6 5 1 6]
For maxWeight 20, the max value is 89
*/
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
func knapsack(value, weight []int, maxWeight int) int {
dp := make([][]int, len(value)+1)
for i := range dp {
dp[i] = make([]int, maxWeight+1)
for j := range dp[i] {
dp[i][j] = 0
}
}
for i := 1; i <= len(value); i++ {
for j := 1; j <= maxWeight; j++ {
if weight[i-1] <= j {
dp[i][j] = max(dp[i-1][j], value[i-1]+dp[i-1][j-weight[i-1]])
} else {
dp[i][j] = dp[i-1][j]
}
}
}
return dp[len(value)][maxWeight]
}
func main() {
value := []int{12, 34, 1, 23, 5, 8, 19, 10}
weight := []int{5, 4, 3, 7, 6, 5, 1, 6}
maxWeight := 20
fmt.Printf("The value list is %v\n", value)
fmt.Printf("The weight list is %v\n", weight)
fmt.Printf("For maxWeight %d, the max value is %d\n", maxWeight, knapsack(value, weight, maxWeight))
}
|
code/dynamic_programming/src/knapsack/knapsack.java | // Part of Cosmos by OpenGenus Foundation
class Knapsack {
public static void main(String[] args) throws Exception {
int val[] = {10, 40, 30, 50};
int wt[] = {5, 4, 6, 3};
int W = 10;
System.out.println(knapsack(val, wt, W));
}
public static int knapsack(int val[], int wt[], int W) {
int N = wt.length; // Get the total number of items. Could be wt.length or val.length. Doesn't matter
int[][] V = new int[N + 1][W + 1]; //Create a matrix. Items are in rows and weight at in columns +1 on each side
//What if the knapsack's capacity is 0 - Set all columns at row 0 to be 0
for (int col = 0; col <= W; col++) {
V[0][col] = 0;
}
//What if there are no items at home. Fill the first row with 0
for (int row = 0; row <= N; row++) {
V[row][0] = 0;
}
for (int item=1;item<=N;item++){
//Let's fill the values row by row
for (int weight=1;weight<=W;weight++){
//Is the current items weight less than or equal to running weight
if (wt[item-1]<=weight){
//Given a weight, check if the value of the current item + value of the item that we could afford with the remaining weight
//is greater than the value without the current item itself
V[item][weight]=Math.max (val[item-1]+V[item-1][weight-wt[item-1]], V[item-1][weight]);
}
else {
//If the current item's weight is more than the running weight, just carry forward the value without the current item
V[item][weight]=V[item-1][weight];
}
}
}
//Printing the matrix
for (int[] rows : V) {
for (int col : rows) {
System.out.format("%5d", col);
}
System.out.println();
}
return V[N][W];
}
} |
code/dynamic_programming/src/knapsack/knapsack.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* method which returns the maximum total value in the knapsack
* @param {array} valueArray
* @param {array} weightArray
* @param {integer} maximumWeight
*/
function knapsack(valueArray, weightArray, maximumWeight) {
let n = weightArray.length;
let matrix = [];
// lazy initialize the element of 2d array
if (!matrix[0]) matrix[0] = [];
// if the knapsack's capacity is 0 - Set all columns at row 0 to be 0
for (let inc = 0; inc <= maximumWeight; inc++) {
matrix[0][inc] = 0;
}
for (let i = 1; i < n + 1; i++) {
// check all possible maxWeight values from 1 to W
for (let j = 1; j < maximumWeight + 1; j++) {
// lazy initialize the element of 2d array
if (!matrix[j]) matrix[j] = [];
// if current item weighs < j then we have two options,
if (weightArray[i - 1] <= j) {
// Given a weight, check if the value of the current item + value of the item that we could afford with the remaining weight
// is greater than the value without the current item itself
matrix[i][j] = Math.max(
matrix[i - 1][j],
valueArray[i - 1] + matrix[i - 1][j - weightArray[i - 1]]
);
} else {
// If the current item's weight is more than the running weight, just carry forward the value without the current item
matrix[i][j] = matrix[i - 1][j];
}
}
}
return matrix[n][maximumWeight];
}
console.log(
"Result - " + knapsack([12, 1000, 30, 10, 1000], [19, 120, 20, 1, 120], 40)
);
|
code/dynamic_programming/src/knapsack/knapsack.py | #######################################
# Part of Cosmos by OpenGenus Foundation
#######################################
def knapsack(weights, values, W):
n = len(weights)
# create 2d DP table with zeros to store intermediate values
tab = [[0 for i in range(W + 1)] for j in range(n + 1)]
# no further init required as enitre table is already inited
for i in range(1, n + 1):
# check all possible maxWeight values from 1 to W
for j in range(1, W + 1):
if weights[i - 1] <= j:
# if current item weighs < j then we have two options,
# take max of them
tab[i][j] = max(
tab[i - 1][j], values[i - 1] + tab[i - 1][j - weights[i - 1]]
)
else:
tab[i][j] = tab[i - 1][j]
return tab[n][W]
def main():
values = [12, 1000, 30, 10, 1000] # values of each item
weights = [19, 120, 20, 1, 120] # weights of each item in same order
W = 40
# Call knapsack routine to compute value
print("Result - {}".format(knapsack(weights, values, W)))
return
if __name__ == "__main__":
main()
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/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/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.c | #include <stdio.h>
int
kadanesAlgorithm(int a[], int n)
{
int max_so_far = 0, max_ending_here = 0;
int i;
for (i = 0; i < n; ++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);
}
int
main()
{
int n;
printf("Enter size of Array: ");
scanf("%d", &n);
int a[n];
printf("Enter %d Integers \n", n);
int i;
for (i = 0; i < n; ++i)
scanf("%d", &a[i]);
printf("Largest Contiguous Subarray Sum: %d \n", kadanesAlgorithm(a, n));
return (0);
}
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* BY:- https://github.com/alphaWizard
*
*/
#include <iostream>
#include <vector>
using namespace std;
int max_subarray_sum(const vector<int>& ar)
{
int msf = ar[0], mth = max(ar[0], 0);
size_t p = 0;
if (ar[0] < 0)
++p;
int maxi = ar[0];
for (size_t i = 1; i < ar.size(); i++)
{
maxi = max(maxi, ar[i]);
if (ar[i] < 0)
++p; // for handing case of all negative array elements
mth += ar[i];
if (mth > msf)
msf = mth;
if (mth < 0)
mth = 0;
}
return (p != ar.size()) ? msf : maxi;
}
int main()
{
cout << max_subarray_sum({-3, 2, -1, 4, -5}) << '\n'; // Expected output: 5
cout << max_subarray_sum({-1, -2, -3, -4, -5}) << '\n'; // Expected output: -1
return 0;
}
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.go | // Part of Cosmos by OpenGenus Foundation
package main
import "fmt"
func max(n1, n2 int) int {
if n1 > n2 {
return n1
}
return n2
}
func maxSubArraySum(data []int) int {
result := data[0]
current_max := max(data[0], 0)
for i := 1; i < len(data); i++ {
current_max += data[i]
result = max(result, current_max)
current_max = max(current_max, 0)
}
return result
}
func main() {
input := []int{-3, 2, -1, 4, -5}
input2 := []int{-1, -2, -3, -4, -5}
fmt.Printf("The max sum of %v is %d\n", input, maxSubArraySum(input))
fmt.Printf("The max sum of %v is %d\n", input2, maxSubArraySum(input2))
}
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.hs | module LargestSum where
-- Part of Cosmos by OpenGenus Foundation
sublists [] = []
sublists (a:as) = sublists as ++ [a]:(map (a:) (prefixes as))
suffixes [] = []
suffixes (x:xs) = (x:xs) : suffixes xs
prefixes x = map reverse $ (suffixes . reverse) x
largestSum = maximum . (map sum) . sublists
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Scanner;
public class Max_subarray_problem {
public static void main(String[] args) {
System.out.println(new int[] {-3, 2, -1, 4, -5}, 0, 4); // Expected output: 5
System.out.println(new int[] {-1, -2, -3, -4, -5}, 0, 4); // Expected output: -1
}
private static int findmaxsum(int[] a, int l, int h) {
int max;
if(l==h)
return a[l];
else
{
int mid = (l + h) / 2;
int leftmaxsum = findmaxsum(a, l, mid);
int rightmaxsum = findmaxsum(a , mid + 1, h);
int crossmaxsum = findcrosssum(a, l, mid, h);
max = Math.max(Math.max(leftmaxsum, rightmaxsum), crossmaxsum);
}
return max;
}
private static int findcrosssum(int[] a, int l, int mid, int h) {
int leftsum = Integer.MIN_VALUE;
int lsum = 0;
for(int i = mid; i >= l; i--)
{
lsum += a[i];
if(lsum > leftsum)
leftsum = lsum;
}
int rightsum = Integer.MIN_VALUE;
int rsum = 0;
for(int j = mid + 1; j <= h; j++)
{
rsum += a[j];
if(rsum > rightsum)
rightsum = rsum;
}
return rightsum + leftsum;
}
}
|
code/dynamic_programming/src/largest_sum_contiguous_subarray/largest_sum_contiguous_subarray.py | # Part of Cosmos by OpenGenus Foundation
# Function to find the maximum contiguous subarray using Kadane's algorithm
def maxSubArraySum(a):
max_so_far = a[0]
max_ending_here = max(a[0], 0)
for i in range(1, len(a)):
max_ending_here += a[i]
max_so_far = max(max_so_far, max_ending_here)
max_ending_here = max(max_ending_here, 0)
return max_so_far
def test():
tests = [
[-3, 2, -1, 4, -5], # Expected output: 5
[-1, -2, -3, -4, -5], # Expected output: -1
]
for arr in tests:
print("Maximum contiguous sum of", arr, "is", maxSubArraySum(arr))
test()
|
code/dynamic_programming/src/longest_bitonic_sequence/README.md | # Longest Bitonic Sequence
## Description
A bitonic sequence is a sequence of numbers which is first strictly increasing
then after a point strictly decreasing. Find the length of the longest bitonic
sequence in a given array `A`.
## Solution
This problem is a variation of the standard longest increasing subsequence problem.
We can denote `lis(n)` as the lenght of the longest increasing subsequence that ends
at `A[n]`, and `lds(n)` the lenght of the longest decreasing subsequence that starts
at `A[n]`.
That way, the value of `lis(n) + lds(n) - 1` gives us the longest bitonic
sequence in which `A[n]` is the highest value. So being `lbs(n)` the longest bitonic
sequence from `A[0]` to `A[n]`:
```
lbs(n) = max( lis(i) + lds(i) - 1, 0 <= i <= n )
```
The time complexity of above approach will be the same as of the algorithm
to find the longest increasing subsequence, that can be `O(n^2)` or `O(n log n)`.
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/opengenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
// helper function to get maximum of two integers
int
max(int a, int b)
{
return (a > b ? a : b);
}
/**
* Return the first element in v
* that is greater than or equal
* to x in O(log n).
*/
int
lower_bound(int v[], int n, int x)
{
int low = 0;
int high = n;
while (low < high) {
int mid = (low + high) / 2;
if (v[mid] >= x)
high = mid;
else
low = mid + 1;
}
return (low);
}
/**
* Return the length of the longest
* bitonic sequence in v.
* Time complexity: O(n lg n).
*/
int
longest_bitonic_sequence(int v[], int n) {
int lis[n]; // stores the longest increasing sequence that ends at ith position
int lds[n]; // stores the longest decreasing sequence that starts at ith position
int tail[n], tailSize; // used to compute LIS and LDS
int i;
// Computing LIS
tail[0] = v[0];
tailSize = 1;
lis[0] = 1;
for (i = 1; i < n; ++i) {
int idx = lower_bound(tail, tailSize, v[i]);
if(idx == tailSize)
tail[tailSize++] = v[i];
else
tail[idx] = v[i];
lis[i] = tailSize;
}
// Computing LDS
tailSize = 1;
lds[n - 1] = 1;
int i;
for(i = n - 2; i >= 0; --i) {
int idx = lower_bound(tail, tailSize, v[i]);
if(idx == tailSize)
tail[tailSize++] = v[i];
else
tail[idx] = v[i];
lds[i] = tailSize;
}
// lis[i] + lds[i] - 1 is the length of the
// longest bitonic sequence with max value
// at position i.
int ans = 0;
for(i = 0; i < n; ++i)
ans = max(ans, lis[i] + lds[i] - 1);
return (ans);
}
int
main()
{
int v1[] = {1, 2, 5, 3, 2};
int v2[] = {1, 11, 2, 10, 4, 5, 2, 1};
// Expected output: 5
printf("%d\n", longest_bitonic_sequence(v1, sizeof(v1)/sizeof(v1[0])));
// Expected output: 6
printf("%d\n", longest_bitonic_sequence(v2, sizeof(v2)/sizeof(v2[0])));
return (0);
}
|
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.js | /**
* Part of Cosmos by OpenGenus Foundation
*/
/**
* Method that returns the subsequenceLengthArray 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 subsequenceLengthArray = [];
for (i = 0; i < arrLength; i++) {
subsequenceLengthArray[i] = 1;
}
for (i = 1; i < arrLength; i++) {
for (j = 0; j < i; j++)
if (
inputArray[j] < inputArray[i] &&
subsequenceLengthArray[j] + 1 > subsequenceLengthArray[i]
) {
subsequenceLengthArray[i] = subsequenceLengthArray[j] + 1;
}
}
return subsequenceLengthArray;
}
/**
* Method that returns the maximum bitonic subsequnce length for the input array
* @param {array} inputArray
*/
function longestBitonicSubsequence(inputArray) {
const incSubsequenceLengthArray = longestIncreasingSubsequence(inputArray);
const decSubsequenceLengthArray = longestIncreasingSubsequence(
inputArray.reverse()
);
/* Return the maximum value of incSubsequenceLengthArray[i] + decSubsequenceLengthArray[i] - 1*/
let maxBitonicLength =
incSubsequenceLengthArray[0] + decSubsequenceLengthArray[0] - 1;
for (let i = 1; i < inputArray.length; i++) {
if (
incSubsequenceLengthArray[i] + decSubsequenceLengthArray[i] - 1 >
maxBitonicLength
) {
maxBitonicLength =
incSubsequenceLengthArray[i] + decSubsequenceLengthArray[i] - 1;
}
}
return maxBitonicLength;
}
console.log(
`Longest Bitonic Subsequence Length - ${longestBitonicSubsequence([
0,
8,
4,
12,
2,
10,
6,
14,
1,
9,
5,
13,
3,
11,
7,
15
])}`
);
|
code/dynamic_programming/src/longest_bitonic_sequence/longest_bitonic_sequence.py | # Part of Cosmos by OpenGenus Foundation
import copy
# returns the longest increasing sequence
def longest_increasing_seq(numbers):
# longest increasing subsequence
lis = []
# base case
lis.append([numbers[0]])
# start filling using dp - forwards
for i in range(1, len(numbers)):
lis.append([])
for j in range(i):
if numbers[j] < numbers[i] and len(lis[j]) > len(lis[i]):
lis[i] = copy.copy(lis[j])
lis[i].append(numbers[i])
return lis
# returns longest decreasing sequence
def longest_decreasing_seq(numbers):
# longest decreasing subsequence
lds = []
# to make an n sized list
lds = [[] for _ in range(len(numbers))]
# base case
lds[-1].append(numbers[-1])
# start filling using dp backwards
for i in range(len(numbers) - 2, -1, -1):
for j in range(len(numbers) - 1, i, -1):
if numbers[j] < numbers[i] and len(lds[j]) > len(lds[i]):
lds[i] = copy.copy(lds[j])
lds[i].append(numbers[i])
return lds
def longest_bitonic_seq(numbers):
lis = longest_increasing_seq(numbers)
lds = longest_decreasing_seq(numbers)
# now let's find the maxmimum
maxi = len(lis[0] + lds[0])
output = lis[0][:-1] + lds[0][::-1]
for i in range(1, len(numbers)):
if len(lis[i] + lds[i]) > maxi:
maxi = len(lis[i] + lds[i])
output = lis[i][:-1] + lds[i][::-1]
return output
# you can use any input format
# format the input such that the array of numbers looks like below
numbers = [1, 11, 2, 10, 4, 5, 2, 1]
output = longest_bitonic_seq(numbers)
print(output)
|
code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicseq.cpp | #include <iostream>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
int lBitconSeq(vector<int> v, int n)
{
vector<int> lis, lds; // lis stands for longest increasing subsequence and lds stands for longest decreasing subsequence
if (n == 0)
return 0; // in case tha array is empty longest length will also be empty
// finding lis
for (int i = 0; i < n; i++)
lis.push_back(1);
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (v[i] > v[j] && lis[j] + 1 > lis[i])
lis[i] = lis[j] + 1;
//findin lds
for (int i = 0; i < n; i++)
lds.push_back(1);
for (int i = 1; i < n; i++)
for (int j = 0; j < i; j++)
if (v[i] < v[j] && lds[j] + 1 > lds[i])
lds[i] = lds[j] + 1;
// result wil be max(lis[i] + lds[i] -1)
int res = lis[0] + lds[0] - 1;
for (int i = 1; i < n; i++)
if ((lis[i] + lds[i] - 1) > res)
res = lis[i] + lds[i] - 1;
return res;
}
int main()
{
vector<int> v;
int n;
cout << "enter no. of elements in array\n";
cin >> n;
cout << "enter elements of the array\n";
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
v.push_back(temp); // filling the array with numbers
}
cout << "max length of the lingest bitconic sequence is " << lBitconSeq(v, n);
}
|
code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicsequence.java | /* Part of Cosmos by OpenGenus Foundation */
/* Dynamic Programming implementation in Java for longest bitonic
subsequence problem */
import java.util.*;
import java.lang.*;
import java.io.*;
class LBS
{
/* lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly creates two temporary arrays
lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1.
lis[i] ==> Longest Increasing subsequence ending with arr[i]
lds[i] ==> Longest decreasing subsequence starting with arr[i]
*/
static int lbs( int arr[], int n )
{
int i, j;
/* Allocate memory for LIS[] and initialize LIS values as 1 for
all indexes */
int[] lis = new int[n];
for (i = 0; i < n; i++)
lis[i] = 1;
/* Compute LIS values from left to right */
for (i = 1; i < n; i++)
for (j = 0; j < i; j++)
if (arr[i] > arr[j] && lis[i] < lis[j] + 1)
lis[i] = lis[j] + 1;
/* Allocate memory for lds and initialize LDS values for
all indexes */
int[] lds = new int [n];
for (i = 0; i < n; i++)
lds[i] = 1;
/* Compute LDS values from right to left */
for (i = n-2; i >= 0; i--)
for (j = n-1; j > i; j--)
if (arr[i] > arr[j] && lds[i] < lds[j] + 1)
lds[i] = lds[j] + 1;
/* Return the maximum value of lis[i] + lds[i] - 1*/
int max = lis[0] + lds[0] - 1;
for (i = 1; i < n; i++)
if (lis[i] + lds[i] - 1 > max)
max = lis[i] + lds[i] - 1;
return max;
}
public static void main (String[] args)
{
int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15};
int n = arr.length;
System.out.println("Length of LBS is "+ lbs( arr, n ));
}
}
|
code/dynamic_programming/src/longest_common_increasing_subsequence/longest_common_increasing_subsequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
using namespace std;
int main()
{
int n, m, a[502] = {}, b[502] = {}, d[502][502] = {}, z = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
for (int i = 1; i <= m; i++)
cin >> b[i];
for (int i = 1; i <= n; i++)
{
int k = 0;
for (int j = 1; j <= m; j++)
{
d[i][j] = d[i - 1][j];
if (b[j] < a[i])
k = max(k, d[i - 1][j]);
if (b[j] == a[i])
d[i][j] = max(d[i - 1][j], k + 1);
z = max(z, d[i][j]);
}
}
cout << z << '\n';
}
|
code/dynamic_programming/src/longest_common_subsequence/Printing_longest_common_subsequence.cpp | //Printing longest common sub-sequence
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
//Helper function to print LCA
string LCA(string s1,string s2){
int m=s1.length();
int n=s2.length();
int dp[m+1][n+1];
//initialising first row
for(int i=0; i<=m; i++){
dp[0][i]=0;
}
//initialising first column
for(int j=0; j<=n; j++){
dp[j][0]=0;
}
//creating DP table
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
if(s1[i-1]==s2[j-1])
dp[i][j]=1+dp[i-1][j-1];
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
int i=m,j=n;
string result;
while(i>0&&j>0){
if(s1[i-1]==s2[j-1]){
result.push_back(s1[i-1]);
i--; j--;
}
else{
if(dp[i][j-1]>dp[i-1][j])
j--;
else
i--;
}
}
reverse(result.begin(),result.end());
return result;
}
int main()
{
string s1="abcdaf";
string s2="acbcf";
string answer=LCA(s1,s2);
cout<<"The LCA is: "<<answer;
return 0;
} |
code/dynamic_programming/src/longest_common_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/longest_common_subsequence/longest_common_subsequence.c | /*
Problem Statement :
Find the length of LCS present in given two sequences.
LCS -> Longest Common Subsequence
*/
#include <stdio.h>
#include <string.h>
#define MAX 1000
int max(int a, int b)
{
return (a > b) ? a : b;
}
int lcs(char *x, char *y, int x_len, int y_len)
{
int dp[x_len + 1][y_len + 1];
for (int i = 0; i <= x_len; ++i)
{
for (int j = 0; j <= y_len; ++j)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (x[i - 1] == y[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[x_len][y_len];
}
int main()
{
char a[MAX], b[MAX];
printf("Enter two strings : ", a, b);
scanf("%s %s", a, b);
int a_len = strlen(a);
int b_len = strlen(b);
printf("\nLength of LCS : %d", lcs(a, b, a_len, b_len));
return 0;
}
/*
Enter two strings : AGGTAB GXTXAYB
Length of LCS : 4
*/
|
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string>
#include <cstring>
#define MAX 1010
using namespace std;
int memo[MAX][MAX];
/* Compute the longest common subsequence
* of strings a[0...n] and b[0...m]
* Time complexity: O(n*m)
*/
int lcs(const string& a, const string& b, int n, int m)
{
if (n < 0 || m < 0)
return 0;
if (memo[n][m] > -1)
return memo[n][m];
if (a[n] == b[m])
return memo[n][m] = 1 + lcs(a, b, n - 1, m - 1);
return memo[n][m] = max( lcs(a, b, n - 1, m), lcs(a, b, n, m - 1) );
}
// Helper method
int get_lcs(const string& a, const string& b)
{
memset(memo, -1, sizeof memo);
return lcs(a, b, a.length() - 1, b.length() - 1);
}
int main()
{
cout << get_lcs("cosmos", "opengenus") << '\n';
cout << get_lcs("ABCDGH", "AEDFHR") << '\n';
return 0;
}
|
code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.cs | using System;
class LongestCommonSubsequence
{
static int longestCommonSubsequence(char[] x, char[] y)
{
int x_len = x.Length;
int y_len = y.Length;
int [,]dp = new int[x_len + 1, y_len + 1];
for (int i = 0; i <= x_len; i++)
{
for (int j = 0; j <= y_len; j++)
{
if (i == 0 || j == 0)
dp[i, j] = 0;
else if (x[i - 1] == y[j - 1])
dp[i, j] = dp[i - 1, j - 1] + 1;
else
dp[i, j] = max(dp[i - 1, j], dp[i, j - 1]);
}
}
return dp[x_len, y_len];
}
static int max(int a, int b)
{
return (a > b) ? a : b;
}
public static void Main()
{
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
char[] a = s1.ToCharArray();
char[] b = s2.ToCharArray();
Console.Write("Length of LCS : " + longestCommonSubsequence(a, b));
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.