Daa Prac Solution

Preview:

Citation preview

1. DIVIDE AND CONQUER STRATERGY

1.) MERGE SORT

#include<conio.h>

#include<stdio.h>

int arr[20]; // array to be sorted

int main()

{

int n,i;

printf("Enter the size of array\n"); // input the elements

scanf("%d",&n);

printf("Enter the elements:");

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

scanf("%d",&arr[i]);

merge_sort(arr,0,n-1); // sort the array

printf("Sorted array:"); // print sorted array

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

printf("%d",arr[i]);

return 0;

}

int merge_sort(int arr[],int low,int high)

{

int mid;

if(low<high) {

mid=(low+high)/2;

// Divide and Conquer

merge_sort(arr,low,mid);

merge_sort(arr,mid+1,high);

// Combine

merge(arr,low,mid,high);

}

return 0;

}

int merge(int arr[],int l,int m,int h)

{

int arr1[10],arr2[10]; // Two temporary arrays to

hold the two arrays to be merged

int n1,n2,i,j,k;

n1=m-l+1;

n2=h-m;

for(i=0; i<n1; i++)

arr1[i]=arr[l+i];

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

arr2[j]=arr[m+j+1];

arr1[i]=9999; // To mark the end of each temporary array

arr2[j]=9999;

i=0;

j=0;

for(k=l; k<=h; k++) { //process of combining two sorted arrays

if(arr1[i]<=arr2[j])

arr[k]=arr1[i++];

else

arr[k]=arr2[j++];

}

return 0;

}

2.) QUICK SORT

// Quick Sort

#include<stdio.h>

#include<conio.h>

void quicksort(int [10],int,int);

void main()

{

int arr[20],n,i;

clrscr();

printf("Enter number of elements: ");

scanf("%d",&n);

printf("Enter the elements:\n");

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

scanf("%d",&arr[i]);

quicksort(arr,0,n-1);

printf("Elements are after sorting:\n");

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

printf(" %d ",arr[i]);

getch();

}

void quicksort(int arr[10],int first,int last)

{

int pivot,j,temp,i;

if(first<last)

{

pivot=first;

i=first;

j=last;

while(i<j)

{

while(arr[i]<=arr[pivot] && i<last)

i++;

while(arr[j]>arr[pivot])

j--;

if(i<j)

{

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

}

temp=arr[pivot];

arr[pivot]=arr[j];

arr[j]=temp;

quicksort(arr,first,j-1);

quicksort(arr,j+1,last);

}

}

3) BINARY SEARCH

/* Binary search for array */

#include<stdio.h>

#include<conio.h>

void main()

{

int a[20],n,i,j,b,temp;

int low, high,mid;

clrscr();

printf("Enter the number of elements: ");

scanf("%d",&n);

printf("Enter the elements:\n");

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

scanf("%d",&a[i]);

/* SORTING */

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

{

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

{

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

{

temp=a[i];

a[i]=a[j];

a[j]=temp;

}

}

}

printf("Sorted array:");

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

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

/* SEARCHING */

printf("\nEnter the element to search: ");

scanf("%d",&b);

low=0;

high=n-1;

do

{

mid=(low+high)/2;

if(b<a[mid])

high=mid-1;

if(b>a[mid])

low=mid+1;

}while(b!=a[mid] && low<=high);

if(b==a[mid])

printf("Number found!\nLocation: %d",mid+1);

else

printf("Number not found!");

getch();

}

4.) MATRIX MULTIPLICATION

#include<conio.h>

#include<stdio.h>

main()

{

int m1[10][10],i,j,k,m2[10][10],mult[10][10],r1,c1,r2,c2;

printf("Enter number of rows and columns of first matrix (less than 10)\n");

scanf("%d%d",&r1,&c1);

printf("Enter number of rows and columns of second matrix (less than 10)\n");

scanf("%d%d",&r2,&c2);

if(r2==c1)

{

printf("Enter rows and columns of First matrix \n");

printf("Row wise\n");

for(i=0;i<r1;i++)

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

scanf("%d",&m1[i][j]);

printf("First Matrix is :\n");

for(i=0;i<r1;i++)

{

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

printf("%d\t",m1[i][j]);

printf("\n");

}

printf("Enter rows and columns of Second matrix \n");

printf("Row wise\n");

for(i=0;i<r2;i++)

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

scanf("%d",&m2[i][j]);

printf("Second Matrix is:\n");

for(i=0;i<r2;i++)

{

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

printf("%d\t",m2[i][j]);

printf("\n");

}

printf("Multiplication of the Matrices:\n");

for(i=0;i<r1;i++)

{

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

{

mult[i][j]=0;

for(k=0;k<r1;k++)

mult[i][j]+=m1[i][k]*m2[k][j];

printf("%d\t",mult[i][j]);

}

printf("\n");

}

}

else

{

printf("Matrix multiplication cannot be done");

}

return 0;

}

2.) DYNAMIC PROGRAMMING

1.) BINOMIAL COEFFICIENT

#include<stdio.h>

#include<conio.h>

#define MAXN 100 /* largest n or m */

long binomial_coefficient(n,m)

int n,m; /* computer n choose m */

{

int i,j; /* counters */

long bc[MAXN][MAXN]; /* table of binomial coefficient values */

for (i=0; i<=n; i++) bc[i][0] = 1;

for (j=0; j<=n; j++) bc[j][j] = 1;

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

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

bc[i][j] = bc[i-1][j-1] + bc[i-1][j];

return( bc[n][m] );

}

main()

{

int a, b;

long binomial_coefficient();

while (1) {

scanf("%d %d",&a,&b);

printf("%d\n",binomial_coefficient(a,b));

}

}

2.) MAKING CHANGE

#include<conio.h>

#include <stdio.h>

const int QUARTER = 25;

const int DIME = 10;

const int NICKEL = 5;

int main( void ) {

int amount, quarters, dimes, nickels, pennies;

printf("Enter amount of change: ");

scanf("%d", &amount);

quarters = amount / QUARTER;

amount = amount % QUARTER;

dimes = amount / DIME;

amount = amount % DIME;

nickels = amount / NICKEL;

pennies = amount % NICKEL;

printf("%d quarters, %d dimes, %d nickels, %d pennies\n",

quarters, dimes, nickels, pennies);

return 0;

}

3.) ASSEMBLY LINE SCHEDULING

#include<conio.h>#include <stdio.h>

int n = 6, i;int a[2][6], t[2][6-1], e[2], x[2];int f1[6], f2[6], l[2][6], fe, le;

void print_stations(){ int i = le; int j;

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

for(j=n-1;j>0;--j) { i = l[i-1][j];

printf("line %d ", i);printf("station %d ", j);printf("\n");

}}

void fastest_way(){

f1[0] = e[0] + a[0][0]; f2[0] = e[1] + a[1][0];

int j;

for(j = 1; j<n; ++j) { if( (f1[j-1]+a[0][j]) <= (f2[j-1]+t[1][j-1]+a[0][j]) ) { f1[j] = f1[j-1] + a[0][j]; l[0][j] = 1; } else{ f1[j] = f2[j-1] + t[1][j-1] + a[0][j]; l[0][j] = 2; } if( (f2[j-1]+a[1][j]) <= (f1[j-1]+t[0][j-1]+a[1][j]) ) { f2[j] = f2[j-1] + a[1][j]; l[1][j] = 2; } else{ f2[j] = f1[j-1] + t[0][j-1] + a[1][j]; l[1][j] = 1; } } if( (f1[n-1] + x[0]) <= (f2[n-1] + x[1]) ) { fe = f1[n-1] + x[0]; le = 1; } else{ fe = f2[n-1] + x[1]; le = 2; } print_stations();}

int main(){ printf("This program gives the fastest way through a factory of n machines..\n");

printf("The entry times are set up\n"); e[0] = 2; e[1] = 4; printf("The exit times are set up\n");

x[0] = 3; x[1] = 2;

printf("\nEnter the station times of row S1:\n");

for(i=0; i<n; ++i) scanf("%d", &a[0][i]);

printf("\nEnter the station times of row S2:\n");

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

printf("\nEnter transaction times from row S1:\n");

for(i=0; i<n-1; ++i) scanf("%d", &t[0][i]);

printf("\nEnter transaction times from row S2:\n");

for(i=0; i<n-1; ++i) scanf("%d", &t[1][i]);

printf("\n");fastest_way();//call fastest way function

return 0;}

4.) KNAPSACK PROBLEM

// Knapsack using dynamic programming

#include <stdio.h>#define max(a,b) (a > b ? a : b)

int matrix[100][100] = {0};

int knapsack(int index, int size, int weights[],int values[]){ int take,dontTake;

take = dontTake = 0;

if (matrix[index][size]!=0) return matrix[index][size];

if (index==0) {

if (weights[0]<=size){

matrix[index][size] = values[0]; return values[0]; }

else{

matrix[index][size] = 0; return 0; } }

if (weights[index]<=size) take = values[index] + knapsack(index-1, size-weights[index], weights, values);

dontTake = knapsack(index-1, size, weights, values);

matrix[index][size] = max (take, dontTake);

return matrix[index][size];

}

void main(){ int nItems = 5; int knapsackSize = 12; int weights[5] = {1,2,5,6,7}; int values[5] = {1,6,18,22,28}; clrscr();

printf("Max value = %d\n",knapsack(nItems-1,knapsackSize,weights,values));

getch();}

5.) MATRIX CHAIN MULTIPLICATION

# include <stdio.h># include <conio.h># include <stdlib.h># define sz 20 # define INF 200000

void print(unsigned long s[][sz], int i, int j) { if (i == j) printf(" A%d ",i); else { printf(" ( "); print(s, i, s[i][j]);print(s, s[i][j] + 1, j); printf(" ) "); } } void printm(unsigned long m[][sz], int n) { int i,j;for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { printf("%5d",m[i][j]); } printf("\n\n");} printf("\nThe No. of multiplication required is : %d",m[1][n]); }

void Matrix_Chain_Order(int p[],int num){ unsigned long m[sz][sz] = {0}; unsigned long s[sz][sz] = {0}; unsigned int q = 0; int i, j, k, l;

int n = num;

for(i = 1; i <= n; i++)m[i][i] = 0;

for(l = 2; l <= n; l++)for(i = 1; i <= (n - l + 1); i++){ j = i + l - 1; m[i][j] = INF; for(k = i; k <= j - 1; 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; } } } print(s, i-1, j); printf("\n\n");printf("The Minimum No. of Multiplication Required is:\n\n");printm(m,n);}

void main() { int i,num=0,p[sz]={0}; clrscr();printf("Enter the number of matrix : "); scanf("%d",&num);printf("Enter %d no. of order sequence for %d matrix :\n",num+1,num); for(i=0;i<=num;i++) scanf("%d",&p[i]);printf("\n\n");printf("MULTIPLICATION SEQUENCE IS : "); printf("\n\n\t");Matrix_Chain_Order(p,num);getch();}

6.) LONGEST COMMON SUBSEQUENCE

#include<stdio.h>#include<string.h>

void print_lcs(char b[][20],char x[],int i,int j){ if(i==0 || j==0) return; if(b[i][j]=='c') { print_lcs(b,x,i-1,j-1); printf("%c",x[i-1]); } else if(b[i][j]=='u') print_lcs(b,x,i-1,j); else print_lcs(b,x,i,j-1);}

void lcs_length(char x[],char y[]){ int m,n,i,j,c[20][20]; char b[20][20]; m=strlen(x); n=strlen(y); for(i=0;i<=m;i++) c[i][0]=0; for(i=0;i<=n;i++) c[0][i]=0; for(i=1;i<=m;i++) for(j=1;j<=n;j++) {

if(x[i-1]==y[j-1]) { c[i][j]=c[i-1][j-1]+1; b[i][j]='c'; //c: left upright cross arrow } else if(c[i-1][j]>=c[i][j-1]) { c[i][j]=c[i-1][j]; b[i][j]='u'; //u: upright arrow }

else { c[i][j]=c[i][j-1]; b[i][j]='l'; //l: left arrow }

} print_lcs(b,x,m,n); }

void lcs(){ int i,j; char x[20],y[20]; printf("Type the first sequence: "); scanf("%s", &x); printf("Type the second sequence: "); scanf("%s", &y); printf("\nLongest Common Subsequence (LCS):"); lcs_length(x,y); }

int main(){ char ch;

do { lcs(); printf("\n\nAnother? y/n: "); scanf("%c%c", &ch, &ch); } while(ch == 'y' || ch == 'Y');

return 0;}

3.) GREEDY TECHNIQUE

1.) MINIMUM SPANNING TREE USING KRUSHKAL

#include<conio.h>

#include<stdio.h>

#define N 6 /* number of vertices */

#define M 15 /* number of edges in graph */

int U[N];

/* function prototypes */

void makeset (int i);

int find (int i);

void merge (int p, int q);

int equal (int p, int q);

void initial (int n);

void test_univ (void);

void pause (void); /* used mainly for test purposes */

/* function definitions */

int main()

{ int W[N][N] = {0,2,4,1,3,2, /* weighted graph */

2,0,6,4,5,1,

4,6,0,4,2,1,

1,4,4,0,5,4,

3,5,2,5,0,6,

2,1,1,4,6,0};

int E[M][3]; /* complete set of edges */

int F[N-1][3]; /* set of edges in min. span. tree */

int num_edges = 0; /* num of edges in min. span. tree */

int next_edge = 0; /* next edge not yet considered */

int weight = 0; /* minimal spanning tree weight */

int a, b, c, i, j, k; /* counter/placeholder variables */

/* initialize set of edges */

k = 0;

for (i = 0; i < N; i++)

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

if (j > i)

{ E[k][0] = i; /* first vertex of edge */

E[k][1] = j; /* second vertex of edge */

E[k][2] = W[i][j]; /* weight of edge */

k++;

}

/* display set of edges - before sort */

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

{ for (j = 0; j < 3; j++)

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

printf("\n");

}

pause();

/* sort set of edges in non-decreasing order by weight - bubblesort */

for (i = M - 1; i > 0; i--)

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

if (E[j][2] > E[j+1][2])

{ a = E[j][0];

b = E[j][1];

c = E[j][2];

E[j][0] = E[j+1][0];

E[j][1] = E[j+1][1];

E[j][2] = E[j+1][2];

E[j+1][0] = a;

E[j+1][1] = b;

E[j+1][2] = c;

}

/* display set of edges - after sort */

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

{ for (j = 0; j < 3; j++)

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

printf("\n");

}

/* create n disjoint subsets */

initial (N);

/* initialize set of edges in min. span. tree to empty */

for (i = 0; i < N - 1; i++)

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

F[i][j] = -1; /* '-1' denotes 'empty' */

test_univ();

/* find minimal spanning tree */

while (num_edges < N - 1)

{ a = E[next_edge][0];

b = E[next_edge][1];

i = find(a);

j = find(b);

if (!equal(i, j))

{ merge (i, j);

F[num_edges][0] = E[next_edge][0];

F[num_edges][1] = E[next_edge][1];

F[num_edges][2] = E[next_edge][2];

num_edges++;

test_univ();

}

next_edge++;

}

/* display edges comprising minimal spanning tree */

printf("\nMinimal Spanning Tree Edges:\n");

printf("F = (");

for (i = 0; i < N - 1; i++)

{ printf("(V%d,V%d)", F[i][0], F[i][1]);

if (i < N - 2)

printf(", ");

weight = weight + F[i][2];

}

printf(")\n");

printf("Minimal Spanning Tree Weight = %d\n", weight);

return (0);

}

/*************** makeset() ***************/

void makeset (int i)

{ U[i] = i;

}

/*************** find() ***************/

int find (int i)

{ int j;

j = i;

while (U[j] != j)

j = U[j];

return (j);

}

/*************** merge() ***************/

void merge (int p, int q)

{ if (p < q)

U[q] = p;

else

U[p] = q;

}

/*************** equal() ***************/

int equal (int p, int q)

{ if (p == q)

return (1);

else

return (0);

}

/*************** initial() ***************/

void initial (int n)

{ int i;

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

makeset(i);

}

/*************** test() ***************/

void test_univ (void)

/* test universe values */

{ int i;

printf("\nThe disjoint subsets are:\n");

for (i = 0; i < N; i++)

printf(" %3d", U[i]);

printf("\n");

}

/*************** pause() ***************/

void pause (void)

{ int i;

printf("Press ENTER to continue...\n");

i = getchar();

}

2.) MINIMUM SPANNING TREE USING PRIM

#include<stdio.h>

#include<conio.h>

int a,b,u,v,n,i,j,ne=1;

int visited[10]={0},min,mincost=0,cost[10][10];

void main()

{

clrscr();

printf("\n Enter the number of nodes:");

scanf("%d",&n);

printf("\n Enter the adjacency matrix:\n");

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

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

{

scanf("%d",&cost[i][j]);

if(cost[i][j]==0)

cost[i][j]=999;

}

visited[1]=1;

printf("\n");

while(ne<n)

{

for(i=1,min=999;i<=n;i++)

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

if(cost[i][j]<min)

if(visited[i]!=0)

{

min=cost[i][j];

a=u=i;

b=v=j;

}

if(visited[u]==0 || visited[v]==0)

{

printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);

mincost+=min;

visited[b]=1;

}

cost[a][b]=cost[b][a]=999;

}

printf("\n Minimun cost=%d",mincost);

getch();

}

3.) KNAPSACK

// 0/1 Knapsack using greedy method

# include<stdio.h>

# include<conio.h>

void knapsack(int n, float weight[], float profit[], float capacity)

{

float x[20], tp= 0;

int i, j, u;

u=capacity;

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

x[i]=0.0;

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

{

if(weight[i]>u)

break;

else

{

x[i]=1.0;

tp= tp+profit[i];

u=u-weight[i];

}

}

if(i<n)

x[i]=u/weight[i];

tp= tp + (x[i]*profit[i]);

printf("\n The result set is:\n");

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

printf("%f\t",x[i]);

printf("\n Maximum profit is: %f", tp);

}

void main()

{

float weight[20], profit[20], capacity;

int n, i ,j;

float ratio[20], temp;

clrscr();

printf ("\n Enter the no. of items: ");

scanf ("%d", &n);

printf ("\n Enter the weights and profits of each item: ");

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

scanf("%f %f", &weight[i], &profit[i]);

printf ("\n enter the capacity of knapsack: ");

scanf ("%f", &capacity);

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

ratio[i]=profit[i]/weight[i];

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

{

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

{

if(ratio[i]<ratio[j])

{

temp= ratio[j];

ratio[j]= ratio[i];

ratio[i]= temp;

temp= weight[j];

weight[j]= weight[i];

weight[i]= temp;

temp= profit[j];

profit[j]= profit[i];

profit[i]= temp;

}

}

}

knapsack(n, weight, profit, capacity);

getch();

}

4.) JOB SCHEDULING

5.) HUFFMAN TREE

#include<string.h>

#include<stdio.h>

#include<limits.h>

#include<stdlib.h>

typedef struct node

{

char ch;

int freq;

struct node *left;

struct node *right;

}node;

/*Declaring heap globally so that we do not need to pass it as an argument every time*/

/* Heap implemented here is Min Heap */

node * heap[1000000];

int heapSize;

/*Initialize Heap*/

void Init()

{

heapSize = 0;

heap[0] = (node *)malloc(sizeof(node));

heap[0]->freq = -INT_MAX;

}

/*Insert an element into the heap */

void Insert(node * element)

{

heapSize++;

heap[heapSize] = element; /*Insert in the last place*/

/*Adjust its position*/

int now = heapSize;

while(heap[now/2] -> freq > element -> freq)

{

heap[now] = heap[now/2];

now /= 2;

}

heap[now] = element;

}

node * DeleteMin()

{

/* heap[1] is the minimum element. So we remove heap[1]. Size of the heap is decreased.

Now heap[1] has to be filled. We put the last element in its place and see if it fits.

If it does not fit, take minimum element among both its children and replaces parent with it.

Again See if the last element fits in that place.*/

node * minElement,*lastElement;

int child,now;

minElement = heap[1];

lastElement = heap[heapSize--];

/* now refers to the index at which we are now */

for(now = 1; now*2 <= heapSize ;now = child)

{

/* child is the index of the element which is minimum among both the children */

/* Indexes of children are i*2 and i*2 + 1*/

child = now*2;

/*child!=heapSize beacuse heap[heapSize+1] does not exist, which means it has only one

child */

if(child != heapSize && heap[child+1]->freq < heap[child] -> freq )

{

child++;

}

/* To check if the last element fits ot not it suffices to check if the last element

is less than the minimum element among both the children*/

if(lastElement -> freq > heap[child] -> freq)

{

heap[now] = heap[child];

}

else /* It fits there */

{

break;

}

}

heap[now] = lastElement;

return minElement;

}

void print(node *temp,char *code)

{

if(temp->left==NULL && temp->right==NULL)

{

printf("char %c code %s\n",temp->ch,code);

return;

}

int length = strlen(code);

char leftcode[512],rightcode[512];

strcpy(leftcode,code);

strcpy(rightcode,code);

leftcode[length] = '0';

leftcode[length+1] = '\0';

rightcode[length] = '1';

rightcode[length+1] = '\0';

print(temp->left,leftcode);

print(temp->right,rightcode);

}

/* Given the list of characters along with their frequencies, our goal is to predict the encoding of the

characters such that total length of message when encoded becomes minimum */

int main()

{

Init();

int distinct_char ;

scanf("%d",&distinct_char);

char ch;

int freq;

int iter;

for(iter=0;iter<distinct_char;iter++)

{

char t[4];

scanf("%s",t); //Scanning the character as string to avoid formatting issues of input.

ch = t[0];

scanf("%d",&freq);

node * temp = (node *) malloc(sizeof(node));

temp -> ch = ch;

temp -> freq = freq;

temp -> left = temp -> right = NULL;

Insert(temp);

}

/* Special Case */

if(distinct_char==1)

{

printf("char %c code 0\n",ch);

return 0;

}

for(iter=0;iter<distinct_char-1 ;iter++)

{

node * left = DeleteMin();

node * right = DeleteMin();

node * temp = (node *) malloc(sizeof(node));

temp -> ch = 0;

temp -> left = left;

temp -> right = right;

temp -> freq = left->freq + right -> freq;

Insert(temp);

}

node *tree = DeleteMin();

char code[512];

code[0] = '\0';

print(tree,code);

}

Recommended