Pratical Part3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

PRACTICAL PART-3

Prepare the full Practical solution file for the below listed topic. (follow the
format given earlier)

1. 1.. Floyd’s Algorithm


2. Chain Matrix Multi
3. N – Queen Using Backtracking
4. Knapsack using Branch and Bound
5. Naïve String Matching
6. Rabin Karp String Matching

Shantilal Shah Engineering College, Bhavnagar. Page 1 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

1) Floyd’s Algorithm

Program :-
#include<stdio.h>

void floyd(int a[4][4], int n)

for(int k=0;k<n;k++)

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

for(int j=0;j<n;j++)

if(a[i][j]>a[i][k]+a[k][j])

a[i][j]=a[i][k]+a[k][j];

printf("All Pairs Shortest Path is :\n");

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

Shantilal Shah Engineering College, Bhavnagar. Page 2 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

for(int j=0;j<n;j++)

printf("%d ",a[i][j]);

printf("\n");

int main()

int cost[4][4] = {{0, 3, 999, 4}, {8, 0, 2, 999}, {5, 999, 0, 1}, {2, 999, 999, 0}};

int n = 4;

floyd(cost,n);

Output:-

Shantilal Shah Engineering College, Bhavnagar. Page 3 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

2) Chain Matrix Multi


Program :-
#include <stdio.h>
#include<limits.h>
#define INFY 999999999
long int m[20][20];
int s[20][20];
int p[20],i,j,n;

void print_optimal(int i,int j)


{

if (i == j)
printf(" A%d ",i);
else
{

printf("( ");
print_optimal(i, s[i][j]);
print_optimal(s[i][j] + 1, j);
printf(" )");

}
}

void matmultiply(void)

Shantilal Shah Engineering College, Bhavnagar. Page 4 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

{
long int q;
int k;

for(i=n;i>0;i--)
{

for(j=i;j<=n;j++)
{

if(i==j)
m[i][j]=0;
else
{
for(k=i;k<j;k++)
{

q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}

}
}

}
}

Shantilal Shah Engineering College, Bhavnagar. Page 5 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

int MatrixChainOrder(int p[], int i, int j)

{
if(i == j)

return 0;
int k;

int min = INT_MAX;


int count;

for (k = i; k <j; k++)


{
count = MatrixChainOrder(p, i, k) +

MatrixChainOrder(p, k+1, j) +
p[i-1]*p[k]*p[j];

if (count < min)


min = count;
}

// Return minimum count

return min;
}

Shantilal Shah Engineering College, Bhavnagar. Page 6 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

void main()
{

int k;
printf("Enter the no. of elements: ");

scanf("%d",&n);
for(i=1;i<=n;i++)

for(j=i+1;j<=n;j++)
{
m[i][i]=0;
m[i][j]=INFY;
s[i][j]=0;
}

printf("\nEnter the dimensions: \n");


for(k=0;k<=n;k++)
{
printf("P%d: ",k);
scanf("%d",&p[k]);
}

matmultiply();
printf("\nCost Matrix M:\n");

for(i=1;i<=n;i++)
for(j=i;j<=n;j++)

Shantilal Shah Engineering College, Bhavnagar. Page 7 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

printf("m[%d][%d]: %ld\n",i,j,m[i][j]);
i=1,j=n;
printf("\nMultiplication Sequence : ");

print_optimal(i,j);
printf("\nMinimum number of multiplications is : %d ",

MatrixChainOrder(p, 1, n));

}Output:-

Shantilal Shah Engineering College, Bhavnagar. Page 8 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

3) N – Queen Using Backtracking


Program :-
#include<stdio.h>

#include<stdlib.h>

#include<math.h>

int board[20],count;

int main()

int n,i,j;

void queen(int row,int n);

printf(" - N Queens Problem Using Backtracking -");

printf("\n\nEnter number of Queens:");

scanf("%d",&n);

queen(1,n);

return 0;

//function for printing the solution

Shantilal Shah Engineering College, Bhavnagar. Page 9 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

void print(int n)

int i,j;

printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)

printf("\t%d",i);

for(i=1;i<=n;++i)

printf("\n\n%d",i);

for(j=1;j<=n;++j) //for nxn board

if(board[i]==j)

printf("\tQ"); //queen at i,j position

else

printf("\t-"); //empty slot

Shantilal Shah Engineering College, Bhavnagar. Page 10 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

/*funtion to check conflicts

If no conflict for desired postion returns 1 otherwise returns 0*/

int place(int row,int column)

int i;

for(i=1;i<=row-1;++i)

//checking column and digonal conflicts

if(board[i]==column)

return 0;

else

if(abs(board[i]-column)==abs(i-row))

return 0;

return 1; //no conflicts

//function to check for proper positioning of queen

void queen(int row,int n)

int column;

for(column=1;column<=n;++column)

Shantilal Shah Engineering College, Bhavnagar. Page 11 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

if(place(row,column))

board[row]=column; //no conflicts so place queen

if(row==n) //dead end

print(n); //printing the board configuration

else //try queen with next position

queen(row+1,n);

Output:

Shantilal Shah Engineering College, Bhavnagar. Page 12 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

4) Knapsack using Branch and Bound

Program :-
// C++ program to solve knapsack problem using

// branch and bound #include

<bits/stdc++.h> using

namespace std;

// Structure for Item which store weight and corresponding

// value of Item struct

Item
{

float weight;

int value;

};

// Node structure to store information of decision

// tree

struct Node

// level --> Level of node in decision tree (or index

// in arr[]

// profit --> Profit of nodes on path from root to this

// node (including this node)

Shantilal Shah Engineering College, Bhavnagar. Page 13 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// bound ---> Upper bound of maximum profit in subtree

// of this node/

int level, profit, bound;

float weight;

};

// Comparison function to sort Item according to

// val/weight ratio bool

cmp(Item a, Item b)

double r1 = (double)a.value / a.weight;

double r2 = (double)b.value / b.weight; return

r1 > r2;

// Returns bound of profit in subtree rooted with u.

// This function mainly uses Greedy solution to find

// an upper bound on maximum profit. int

bound(Node u, int n, int W, Item arr[]) {

// if weight overcomes the knapsack capacity, return

// 0 as expected bound if

(u.weight >= W) return


0;

Shantilal Shah Engineering College, Bhavnagar. Page 14 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// initialize bound on profit by current profit

int profit_bound = u.profit;


// start including items from index 1 more to current

// item index int j

= u.level + 1; int

totweight = u.weight;

// checking index condition and knapsack capacity

// condition

while ((j < n) && (totweight + arr[j].weight <= W))

totweight += arr[j].weight;

profit_bound += arr[j].value;

j++;

// If k is not n, include last item partially for

// upper bound on profit

if (j < n)

profit_bound += (W - totweight) * arr[j].value

/ arr[j].weight; return profit_bound;

Shantilal Shah Engineering College, Bhavnagar. Page 15 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// Returns maximum profit we can get with capacity W int

knapsack(int W, Item arr[], int n)


{

// sorting Item on basis of value per unit

// weight.

sort(arr, arr + n, cmp);

// make a queue for traversing the node

queue<Node> Q;

Node u, v;

// dummy node at starting

u.level = -1;

u.profit = u.weight = 0;

Q.push(u);

// One by one extract an item from decision tree

// compute profit of all children of extracted item

// and keep saving maxProfit

int maxProfit = 0; while

(!Q.empty())

Shantilal Shah Engineering College, Bhavnagar. Page 16 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// Dequeue a node

u = Q.front();

Q.pop();

// If it is starting node, assign level 0 if (u.level

== -1)

v.level = 0;

// If there is nothing on next level

if (u.level == n-1)

continue;

// Else if not last node, then increment level,

// and compute profit of children nodes.

v.level = u.level + 1;

// Taking current level's item add current

// level's weight and value to node u's

// weight and value

v.weight = u.weight + arr[v.level].weight;

v.profit = u.profit + arr[v.level].value;

Shantilal Shah Engineering College, Bhavnagar. Page 17 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// If cumulated weight is less than W and

// profit is greater than previous profit,

// update maxprofit if (v.weight

<= W && v.profit > maxProfit)

maxProfit = v.profit;

// Get the upper bound on profit to decide

// whether to add v to Q or not.

v.bound = bound(v, n, W, arr);

// If bound value is greater than profit,

// then only push into queue for further

// consideration

if (v.bound > maxProfit)

Q.push(v);

// Do the same thing, but Without taking // the item

in knapsack

v.weight = u.weight;

v.profit = u.profit;

v.bound = bound(v, n, W, arr);

if (v.bound > maxProfit)

Q.push(v);

Shantilal Shah Engineering College, Bhavnagar. Page 18 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

return maxProfit;

// driver program to test above function int

main()

int W = 10; // Weight of knapsack

Item arr[] = {{2, 40}, {3.14, 50}, {1.98, 100},

{5, 95}, {3, 30}};

int n = sizeof(arr) / sizeof(arr[0]);

cout << "Maximum possible profit = "

<< knapsack(W, arr, n); return 0;

Output:-

Shantilal Shah Engineering College, Bhavnagar. Page 19 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

5. Naïve String Matching


Program:
#include <stdio.h>

#include <string.h>

int main (){

char txt[] = "tutorialsPointisthebestplatformforprogrammers";

char pat[] = "a";

int M = strlen (pat);

int N = strlen (txt);

for (int i = 0; i <= N - M; i++){

int j;

for (j = 0; j < M; j++)

if (txt[i + j] != pat[j])

break;

if (j == M)

printf ("Pattern matches at index %d \n", i);

return 0;

Shantilal Shah Engineering College, Bhavnagar. Page 20 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

Output:

Shantilal Shah Engineering College, Bhavnagar. Page 21 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

6. Rabin Karp String Matching

Program :-
/* Following program is a C implementation of Rabin Karp
Algorithm given in the CLRS book */
#include <stdio.h>
#include <string.h>

// d is the number of characters in the input alphabet


#define d 256

/* pat -> pattern


txt -> text
q -> A prime number
*/
void search(char pat[], char txt[], int q)
{
int M = strlen(pat);
int N = strlen(txt);
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;

Shantilal Shah Engineering College, Bhavnagar. Page 22 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// The value of h would be "pow(d, M-1)%q"


for (i = 0; i < M - 1; i++)
h = (h * d) % q;

// Calculate the hash value of pattern and first


// window of text
for (i = 0; i < M; i++) {
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}

// Slide the pattern over text one by one


for (i = 0; i <= N - M; i++) {

// Check the hash values of current window of text


// and pattern. If the hash values match then only
// check for characters on by one
if (p == t) {
/* Check for characters one by one */
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j])
break;
}

Shantilal Shah Engineering College, Bhavnagar. Page 23 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]


if (j == M)
printf("Pattern found at index %d \n", i);
}

// Calculate hash value for next window of text: Remove


// leading digit, add trailing digit
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) % q;

// We might get negative value of t, converting it


// to positive
if (t < 0)
t = (t + q);
}
}
}

/* Driver program to test above function */


int main()
{
char txt[] = "Hello bhargav";
char pat[] = "bhargav";

Shantilal Shah Engineering College, Bhavnagar. Page 24 of 25


Analysis And Design of Algorithms (3150703) Bhargav Borkhatariya (200430116515)

int q = 101; // A prime number


search(pat, txt, q);
return 0;
}

Output:

Shantilal Shah Engineering College, Bhavnagar. Page 25 of 25

You might also like