Daa Lab Manual
Daa Lab Manual
NAME :……………………………………………….
REG.NO :………………………………………………..
YEAR/SEMESTER :………………………………………………..
ASAN MEMORIAL COLLEGE
OF ENGINEERING & TECHNOLOGY
(Asan Nagar, Thandarai, Oragadam Main Road,Chengalpet-603 001)
DEPARTMENT OF
SUBJECT NAME:
NAME :
REGISTER NO :
ASAN MEMORIAL COLLEGE OF ENGINEERING & TECHNOLOGY
(Asan Nagar, Thandarai, Oragadam Main Road,Chengalpet-603 001)
BONAFIDE CERTIFICATE
NAME :
REGISTER NO :
SUBJECT NAME :
SUBJECT CODE :
DEPARTMENT :
SEMESTER :
AIM:
To Implement recursive and non-recursive algorithms and study the order of growth from
log2n to n!.
ALGORITHM:
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return f
PROGRAM:
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
4
OUTPUT
int main()
{
int n, i;
unsigned long long factorial = 1;
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of Number %d = %llu", n, factorial);
}
getch();
}
5
OUTPUT:
RESULT:
Thus the recursive and non recursive algorithm for log2n implemented and output was
verified.
6
EXNO:2 Divide And Conquer
AIM:To implement stresssens matrix multiplication using divide and conquer
method.
INTRODUCTION
Divide And Conquer
This technique can be divided into the following three parts:
1. Divide: This involves dividing the problem into smaller sub-problems.
2. Conquer: Solve sub-problems by calling recursively until solved.
3. Combine: Combine the sub-problems to get the final solution of the whole problem.
PROGRAM:
#include <stdio.h>
int DAC_Max(int a[], int index, int l);
int DAC_Min(int a[], int index, int l);
7
{
return a[index];
}
if (index >= l - 2) {
if (a[index] < a[index + 1])
return a[index];
else
return a[index + 1];
}
// Driver Code
int main()
{
// Defining the variables
int min, max, N;
OUTPUT:
Maximum: 120
Minimum: 11
RESULT:Thus the Divide and conquer using matrix multiplication was calculated and
verified.
8
EX NO:3 TOPOLOGICAL SORTING
INTRODUCTION
many sorting algorithms used to sort the given data. It may be numeric data or strings. Take
a situation that our data items have relation. They are related with some condition that one
should happen only after other one happened.
For example shoe should wear after socks only. Another example, in academic course one
should study Applications of Algorithms subject only after studying Designing of
Algorithms. And Designing of Algorithms should study only after learning any programming
language. We can observe that a work requires pre-requisite. In these situations we represent
our data in a graph and we use directed edges from pre-requisite to next one. And we apply
Topological sorting to solve.
Most important condition to do Topological sorting on any graph is that Graph should be
Connected Directed Acyclic graph. It is not possible to apply Topological sorting either graph
is not directed or it have a Cycle.
Vertex in-degree
1 0
2 1
3 1
4 2
Step 2: Write the vertex which has in-degree 0 (zero) in solution. Here vertex 1 has in-degree
0. So,
9
Solution is: 1 -> (not yet completed )
Decrease in-degree count of vertices who are adjacent to the vertex which recently added to
the solution.
Here vertex 1 is recently added to the solution. Vertices 2 and 3 are adjacent to vertex 1. So
decrease the in-degree count of those and update.
ALGORITHM:
PROGRAM:
#include <stdio.h>
int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
for(i=0;i<n;i++){
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
10
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}
OUTPUT:
RESULT:
Thus the topological sort using decrease and conquer was calculated and output was verified
11
EXNO:4 HEAP SORT
AIM: To implement Heapsort using transform and conquer method
ALGORITHM:
1. create a leaf node for each unique character and build a min heap of all leaf nodes
(Min Heap is used as a priority queue. The value of frequency field is used to compare
two nodes in min heap. Initially, the least frequent character is at root)
2. Extract two nodes with the minimum frequency from the min heap.
3. Create a new internal node with a frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child and the other extracted node
as its right child. Add this node to the min heap.
4. Repeat steps#2 and #3 until the heap contains only one node. The remaining node is
the root node and the tree is complete.
PROGRAM:
#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {
// swap a[i] with a[largest]
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
12
heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
/* function to print the array elements */
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", arr[i]);
printf(" ");
}
}
int main()
{
int a[] = {48, 10, 23, 43, 28, 26, 1};
13
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
OUTPUT:
RESULT
Thus the transforms and conquer method using heap sort verified and executed.
14
Ex.No:5 Dynamic programming using Coin change Problem, Warshall’s and Floyd‘s
algorithms, Knapsack Problem
AIM:
To learn Dynamic programming –using Coin change Problem, Warshall’s and Floyd‘s
algorithms, Knapsack Problem
ALGORITHM
1. We have 2 choices for a coin of a particular denomination, either i) to include, or
ii) to exclude.
2. If we are at coins[n-1], we can take as many instances of that coin ( unbounded
inclusion ) i.e count(coins, n, sum – coins[n-1] ); then we move to coins[n-2].
3. After moving to coins[n-2], we can’t move back and can’t make choices for
coins[n-1] i.e count(coins, n-1, sum).
4. Finally, as we have to find the total number of ways, so we will add these 2
possible choices, i.e count(coins, n, sum – coins[n-1] ) + count(coins, n-1, sum );
Program:
#include <stdio.h>
15
int main()
{
int i, j;
int coins[] = { 1, 2, 3 };
int n = sizeof(coins) / sizeof(coins[0]);
printf("%d ", count(coins, n, 4));
getchar();
return 0;
}
Output
4
Warshall’s algorithm
#include<stdio.h>
#include<conio.h>
#include<math.h>
int max(int, int);
void warshal(int p[10][10], int n) {
int i, j, k;
for (k = 1; k <= n; k++)
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
}
int max(int a, int b) {
;
if (a > b)
return (a);
else
return (b);
}
void main() {
int p[10][10] = { 0 }, n, e, u, v, i, j;
printf("\n Enter the number of vertices:");
scanf("%d", &n);
printf("\n Enter the number of edges:");
scanf("%d", &e);
for (i = 1; i <= e; i++) {
//printf("\n Enter the end vertices of edge %d:", i);
scanf("%d%d", &u, &v);
p[u][v] = 1;
}
printf("\n Matrix of input data: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
16
warshal(p, n);
printf("\n Transitive closure: \n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf("%d\t", p[i][j]);
printf("\n");
}
getch();
}
Output:
$ gcc WarshallTransitiveClosure.c
$ ./a.out
Transitive closure:
1 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1
FLYODS ALGORITHM:
#include <stdio.h>
#include <conio.h>
void main()
17
{
int num, i, j, k = 1;
printf( " Enter a number to define the rows in Floyd's triangle: \n");
scanf( "%d", &num);
// use nested for loop
// outer for loop define the rows and check rows condition
for (i = 1; i <= num; i++)
{
// inner loop check j should be less than equal to 1 and print the data.
for (j = 1; j <= i; j++)
{
printf(" %2d", k++); // print the number
}
printf( "\n");
}
getch();
}
Output
Enter a number to define the rows in Floyd's triangle:
6
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
RESULT:
Thus the Dynamic programming using coin changing problem ,flyods &warshall’s
algorithm was implemented and out verified
18
Exno:6
Greedy Technique – Dijkstra’s algorithm, Huffman Trees and codes
AIM:
To learn dijikstra’s algorithm and Huffman tree codes using greedy technique
ALGORITHM
1. Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. C[i][j] is the cost of going from
vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is infinity.
4. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1 from the
source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Initially, distance of source vertex is taken as 0. i.e. distance[0]=0;
5. for(i=1;i<n;i++)
– Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark visited[w]
as 1.
– Recalculate the shortest distance of remaining vertices from the source.
– Only, the vertices not marked as 1 in array visited[ ] should be considered for recalculation
of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
19
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
20
}
count++;
}
21
};
return temp;
}
// current size is 0
minHeap->size = 0;
minHeap->capacity = capacity;
22
// A utility function to
// swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a,
struct MinHeapNode** b)
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
23
{
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
++minHeap->size;
int i = minHeap->size - 1;
while (i
&& minHeapNode->freq
< minHeap->array[(i - 1) / 2]->freq) {
output
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
RESULT:
Thus the greedy technique using Huffman code and dijikstras was Executed and output
verified.
24
Exno:7 SIMPLEX METHOD
AIM:
To implement iterative improvement using simplex method
ALGORITHM:
1. Make a change of variables and normalize the sign of the independent terms.
2. Normalize restrictions.
3. Match the objective function to zero.
4. Write the initial tableau of Simplex method.
5. Stopping condition.
6. Choice of the input and output base variables.
7. Update tableau.
PROGRAM
#include <stdio.h>
#include <math.h>
void Data() {
double R1,R2;
char R;
int I,J;
printf("\n LINEAR PROGRAMMING\n\n");
printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d",
&NV);
printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
if (R == 'Y' || R=='y')
R1 = 1.0;
else
R1 = -1.0;
printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
for (J = 1; J<=NV; J++) {
printf(" #%d ? ", J); scanf("%lf", &R2);
TS[1][J+1] = R2 * R1;
}
printf(" Right hand side ? "); scanf("%lf", &R2);
TS[1][1] = R2 * R1;
for (I = 1; I<=NC; I++) {
printf("\n CONSTRAINT #%d:\n", I);
25
for (J = 1; J<=NV; J++) {
printf(" #%d ? ", J); scanf("%lf", &R2);
TS[I + 1][J + 1] = -R2;
}
printf(" Right hand side ? "); scanf("%lf", &TS[I+1][1]);
}
printf("\n\n RESULTS:\n\n");
for(J=1; J<=NV; J++) TS[0][J+1] = J;
for(I=NV+1; I<=NV+NC; I++) TS[I-NV+1][0] = I;
}
void Pivot();
void Formula();
void Optimize();
void Simplex() {
e10: Pivot();
Formula();
Optimize();
if (NOPTIMAL == 1) goto e10;
}
void Pivot() {
double RAP,V,XMAX;
int I,J;
XMAX = 0.0;
for(J=2; J<=NV+1; J++) {
if (TS[1][J] > 0.0 && TS[1][J] > XMAX) {
XMAX = TS[1][J];
P2 = J;
}
}
RAP = 999999.0;
for (I=2; I<=NC+1; I++) {
if (TS[I][P2] >= 0.0) goto e10;
V = fabs(TS[I][1] / TS[I][P2]);
if (V < RAP) {
RAP = V;
P1 = I;
}
e10:;}
V = TS[0][P2]; TS[0][P2] = TS[P1][0]; TS[P1][0] = V;
}
void Formula() {;
//Labels: e60,e70,e100,e110;
int I,J;
26
for (I=1; I<=NC+1; I++) {
if (I == P1) goto e70;
for (J=1; J<=NV+1; J++) {
if (J == P2) goto e60;
TS[I][J] -= TS[P1][J] * TS[I][P2] / TS[P1][P2];
e60:;}
e70:;}
TS[P1][P2] = 1.0 / TS[P1][P2];
for (J=1; J<=NV+1; J++) {
if (J == P2) goto e100;
TS[P1][J] *= fabs(TS[P1][P2]);
e100:;}
for (I=1; I<=NC+1; I++) {
if (I == P1) goto e110;
TS[I][P2] *= TS[P1][P2];
e110:;}
}
OUTPUT:
RESULT:
Thus the iterative improvement using simplex method was verified and output
verified.
27
EX No:8 Backtracking – N-Queen problem, Subset Sum Problem
#define N 4
#include <stdbool.h>
#include <stdio.h>
28
for (i = 0; i < col; i++)
if (board[row][i])
return false;
return true;
}
29
/* This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise, return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
OUTPUT
..Q.
Q...
...Q
.Q..
SUBSET SUM PROBLEM
include <stdio.h>
#include <stdlib.h>
30
{
for(int i = 0; i < size; i++)
{
printf("%*d", 5, A[i]);
}
printf("\n");
}
// inputs
// s - set vector
// t - tuplet vector
// s_size - set size
// t_size - tuplet size so far
// sum - sum so far
// ite - nodes count
// target_sum - sum to be found
void subset_sum(int s[], int t[],
int s_size, int t_size,
int sum, int ite,
int const target_sum)
{
total_nodes++;
// constraint check
if( ite + 1 < s_size && sum - s[ite] + s[ite+1] <= target_sum )
{
// Exclude previous added item and consider next candidate
subset_sum(s, t, s_size, t_size-1, sum - s[ite], ite + 1, target_sum);
}
return;
}
else
{
// constraint check
if( ite < s_size && sum + s[ite] <= target_sum )
{
// generate nodes along the breadth
for( int i = ite; i < s_size; i++ )
{
t[t_size] = s[i];
31
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}
}
}
Output:
8 9 14 22n 8 14 15 16n 15 16 22nNodes generated 68
RESULT:
Thus the Program for backtracking and branch and branch bound was executed and
output was verified.
32
Exno:09 Branch and Bound - Assignment problem, Traveling Salesman Problem
AIM:
To implement branch and bound Assignment problem&Travaelling salesman problem
ALGORITHM:
1. Consider city 1 as the starting and ending point. Since the route is cyclic, we can
consider any point as a starting point.
2. Generate all (n-1)! permutations of cities.
3. Calculate the cost of every permutation and keep track of the minimum cost
permutation.
4. Return the permutation with minimum cost.
PROGRAM:
#include <bits/stdc++.h>
using namespace std;
#define N 4
// contains Job ID
int jobID;
33
for (int j = 0; j < N; j++)
node->assigned[j] = assigned[j];
node->assigned[y] = true;
node->parent = parent;
node->workerID = x;
node->jobID = y;
return node;
}
// store cost
min = costMatrix[i][j];
}
}
return cost;
}
34
}
};
// print Assignments
void printAssignments(Node *min)
{
if(min->parent==NULL)
return;
printAssignments(min->parent);
cout << "Assign Worker " << char(min->workerID + 'A')
<< " to Job " << min->jobID << endl;
int main()
{
// x-coordinate represents a Worker
// y-coordinate represents a Job
int costMatrix[N][N] =
{
{9, 2, 7, 8},
{6, 4, 3, 7},
{5, 8, 1, 8},
{7, 6, 9, 4}
};
/* int costMatrix[N][N] =
{
{82, 83, 69, 92},
{77, 37, 49, 92},
{11, 69, 5, 86},
{ 8, 9, 98, 23}
};
*/
/* int costMatrix[N][N] =
{
{2500, 4000, 3500},
{4000, 6000, 3500},
{2000, 4000, 2500}
};*/
/*int costMatrix[N][N] =
{
{90, 75, 75, 80},
{30, 85, 55, 65},
{125, 95, 90, 105},
{45, 110, 95, 115}
};*/
return 0;
35
OUTPUT:
Assign Worker A to Job 1
Assign Worker B to Job 0
Assign Worker C to Job 2
Assign Worker D to Job 3
Optimal Cost is 13
RESULT:
Thus the Branch and bound using travelling salesman problem was implemented and
executed.
36