Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Practical 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

IT265– Design & Analysis of Algorithm 4IT (2023-24)

Practical-4
1) Aim: 0 1 knapsack
Program:
import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {


/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class
should be named Solution. */

Scanner sc = new Scanner(System.in);


int n = sc.nextInt();
int w[] = new int[n];
int v[] = new int[n];
for (int i = 0; i < n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
int W = sc.nextInt();
int[][] dp = new int[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= W; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
// System.out.print(dp[i][j] + " ");

} else if (w[i - 1] <= j) {


dp[i][j] = Math.max(v[i - 1] + dp[i - 1][j - w[i - 1]], dp[i - 1][j]);
// System.out.print(dp[i][j] + " ");
} else {
// if (i == 0) {
// dp[i][j] = v[i];
// } else {
// dp[i][j] = Math.max(v[i] + dp[i - 1][j - w[i]], dp[i - 1][j]);
// }
dp[i][j] = dp[i - 1][j];
// System.out.print(dp[i][j] + " ");
}
}
}
System.out.println(dp[n][W]);
}
}

ID No.:22IT109 Page 1
IT265– Design & Analysis of Algorithm 4IT (2023-24)

Output:

Conclusion: In this code we solve 0 1 knapsack problem using dynamic programming.

2)Aim: Matrix_chain_Multiplication Program:


import java.io.*;
import java.util.*;

public class Solution {

static int MatrixChainOrder(int n, int a[]) {


int dp[][] = new int[n][n];
for(int i=2;i<n;i++)
{
for(int row =0,col=i;row<n-i;row++,col++)
{
dp[row][col]=Integer.MAX_VALUE;
for(int k=row+1;k<col;k++)
{
dp[row][col]=Math.min(dp[row][col],dp[row][k]
+dp[k][col]+a[row]*a[k]*a[col]);
}
}
}

return dp[0][n-1];
}

ID No.:22IT109 Page 2
IT265– Design & Analysis of Algorithm 4IT (2023-24)

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n + 1];
for (int i = 0; i <= n; i++) {
arr[i] = sc.nextInt();
}
System.out.println( MatrixChainOrder(n + 1, arr));
sc.close();
}

}
Output:

Conclusion: In this code we solve Matrix_chain_Multiplication by dynamic programming.

Matrix chain multiplication is a problem where we can find minimum number of multiplication
for doing n number of matrices.

3)Aim: Longest common subsequence

Program:
#include <cmath>
#include <cstdio>
#include <vector>

ID No.:22IT109 Page 3
IT265– Design & Analysis of Algorithm 4IT (2023-24)

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int m, n;
cin >> m >> n;

vector<int> A(m), B(n);


for (int i = 0; i < m; ++i) {
cin >> A[i];
}
for (int i = 0; i < n; ++i) {
cin >> B[i];
}

vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

for (int i = 1; i <= m; ++i) {


for (int j = 1; j <= n; ++j) {
if (A[i - 1] == B[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}

vector<int> lcs;
int i = m, j = n;
while (i > 0 && j > 0) {
if (A[i - 1] == B[j - 1]) {
lcs.push_back(A[i - 1]);
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}

reverse(lcs.begin(), lcs.end());

ID No.:22IT109 Page 4
IT265– Design & Analysis of Algorithm 4IT (2023-24)

for (size_t i = 0; i < lcs.size(); ++i) {


cout << lcs[i] << " ";
}

return 0;
}
Output:

Conclusion: In this practical we finding longest common subsequent.

4)AIM: Coin change problem


Program:
#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);


string rtrim(const string &);
vector<string> split(const string &);

/*
* Complete the 'getWays' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. LONG_INTEGER_ARRAY c
*/

long long fun(int n, int i, vector<long> c, vector<vector<long long


>> &dp) {

ID No.:22IT109 Page 5
IT265– Design & Analysis of Algorithm 4IT (2023-24)

if (i == 0) {
return n % c[0] == 0;
}
if (dp[i][n] != 0) {
return dp[i][n];
}
long long take = 0;
long long nottake = fun(n, i - 1, c, dp);
if (c[i] <= n) {
take = fun(n - c[i], i, c, dp);
}
return dp[i][n] = take + nottake;
}
long getWays(int n, vector<long> c) {
int l = c.size();
vector<vector<long long>> dp(l, vector<long long>(n + 1, 0));
return fun(n, l - 1, c, dp);
}

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

string first_multiple_input_temp;
getline(cin, first_multiple_input_temp);

vector<string> first_multiple_input = split(rtrim(first_multipl


e_input_temp));

int n = stoi(first_multiple_input[0]);

int m = stoi(first_multiple_input[1]);

string c_temp_temp;
getline(cin, c_temp_temp);

vector<string> c_temp = split(rtrim(c_temp_temp));

vector<long> c(m);

for (int i = 0; i < m; i++) {


long c_item = stol(c_temp[i]);

ID No.:22IT109 Page 6
IT265– Design & Analysis of Algorithm 4IT (2023-24)

c[i] = c_item;
}

// Print the number of ways of making change for 'n' units usin
g coins having the values given by 'c'

long ways = getWays(n, c);

fout << ways << "\n";

fout.close();

return 0;
}

string ltrim(const string &str) {


string s(str);

s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)
))
);

return s;
}

string rtrim(const string &str) {


string s(str);

s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspac
e))).base(),
s.end()
);

return s;
}

vector<string> split(const string &str) {


vector<string> tokens;

string::size_type start = 0;

ID No.:22IT109 Page 7
IT265– Design & Analysis of Algorithm 4IT (2023-24)

string::size_type end = 0;

while ((end = str.find(" ", start)) != string::npos) {


tokens.push_back(str.substr(start, end - start));

start = end + 1;
}

tokens.push_back(str.substr(start));

return tokens;
}

Output:

Conclusion: The problem involves determining the number of ways to make change for a
given amount using available coin denominations. Dynamic Programming can efficiently solve it
by considering overlapping subproblems. By storing and referencing previously computed
solutions, it optimizes the process. The goal is to find the number of unique combinations for
making change.

5)AIM: Coin on the table


Program:

ID No.:22IT109 Page 8
IT265– Design & Analysis of Algorithm 4IT (2023-24)

import java.util.*;
public class CoinOnTheTable {

private static int k;

private static char[][] board;

private static int[][] costs;

private static int solve() {


dfs(0, 0, 0, 0);

for (int i = 0; i < board.length; i++) {


for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == '*') {
int minCost = costs[i][j];
return minCost == Integer.MAX_VALUE ? -1 : minC
ost;
}
}
}

return -1;
}

private static void dfs(int i, int j, int cost, int time) {

if (!inBoard(i, j) || cost >= costs[i][j]) {


return;
}

costs[i][j] = cost;

if (board[i][j] == '*') {
return;
}
if (time == k) {
return;
}

dfs(i - 1, j, board[i][j] == 'U' ? cost : cost + 1, time +


1);

ID No.:22IT109 Page 9
IT265– Design & Analysis of Algorithm 4IT (2023-24)

dfs(i, j - 1, board[i][j] == 'L' ? cost : cost + 1, time +


1);

dfs(i + 1, j, board[i][j] == 'D' ? cost : cost + 1, time +


1);

dfs(i, j + 1, board[i][j] == 'R' ? cost : cost + 1, time +


1);
}

private static boolean inBoard(int i, int j) {


return i >= 0 && i < board.length && j >= 0 && j < board[i]
.length;
}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int n = scanner.nextInt();
int m = scanner.nextInt();
k = scanner.nextInt();
scanner.nextLine();
board = new char[n][];

for (int i = 0; i < n; i++) {


board[i] = scanner.nextLine().toCharArray();
}
costs = new int[n][m];
for (int i = 0; i < costs.length; i++) {
Arrays.fill(costs[i], Integer.MAX_VALUE);
}

System.out.println(solve());

scanner.close();
}
}

Output:

ID No.:22IT109 Page 10
IT265– Design & Analysis of Algorithm 4IT (2023-24)

Conclusion: The problem requires optimizing the path of a coin on a rectangular board,
reaching a specific cell before a given time limit. By strategically altering cell directions, the
minimum number of operations can be found. It emphasizes efficient pathfinding and dynamic
decision-making, crucial for puzzle-solving and algorithmic challenges.

ID No.:22IT109 Page 11

You might also like