Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views37 pages

Daa Lab Manual

The document outlines practical exercises and algorithms related to artificial intelligence and data science, including recursive and non-recursive algorithms for factorial calculation, divide and conquer methods for matrix multiplication, topological sorting, heapsort, and dynamic programming techniques. Each section includes aims, algorithms, program code, and results of the experiments conducted. The document serves as a record notebook for students at Asan Memorial College of Engineering and Technology.

Uploaded by

hasiny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views37 pages

Daa Lab Manual

The document outlines practical exercises and algorithms related to artificial intelligence and data science, including recursive and non-recursive algorithms for factorial calculation, divide and conquer methods for matrix multiplication, topological sorting, heapsort, and dynamic programming techniques. Each section includes aims, algorithms, program code, and results of the experiments conducted. The document serves as a record notebook for students at Asan Memorial College of Engineering and Technology.

Uploaded by

hasiny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

ASAN MEMORIAL COLLEGE

OF ENGINEERING AND TECHNOLOGY


(Approved by AICTE & Affiliated to Anna University,Chennai)

Asan Nagar,Thandarai Village ,Chengalpattu-603105

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE


RECORD NOTE BOOK

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 :

Certified that this is the bonafide record of work done by


Mr./Ms. of semester in the
Department of of this college
laboratory during
the academic year .

Signature of Faculty-in-charge Signature of H.O.D

Submitted for Practical Examination held on

Internal Examiner External Examiner


EXNO: DATE EXPERIMENT MARK SIGN
EX NO:1 Implementation of recursive and non-recursive algorithms

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;
}

long int multiplyNumbers(int n) {


if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

4
OUTPUT

Enter a positive integer: 6


Factorial of 6 = 720

NON RECURSIVE ALGORITHM


ALGORITHM
1. Factorial of n= n*n-1*.....1
2. To find factorial of a number in c programming language we need to use for loop and
iterate from n to 1
3. in side loop we need to write a logic to multiply the result.
4. factorial *= i;
5. Finally in factorial we will have the result of 1 *2 *.....n
6. Let us see an example c program on finding factorial of a number without using recursion.
PROGRAM
#include <stdio.h>
#include <stdlib.h>

int main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter a number to find factorial: ");


scanf("%d",&n);

// show error if the user enters a negative integer


if (n < 0)
printf("Error! Please enter any positive integer number");

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);

// function to find the maximum no.


// in a given array.
int DAC_Max(int a[], int index, int l)
{
int max;
if(l - 1 == 0)
{
return a[index];
}
if (index >= l - 2) {
if (a[index] > a[index + 1])
return a[index];
else
return a[index + 1];
}

// logic to find the Maximum element


// in the given array.
max = DAC_Max(a, index + 1, l);

if (a[index] > max)


return a[index];
else
return max;
}

// Function to find the minimum no.


// in a given array.
int DAC_Min(int a[], int index, int l)
{
int min;
if(l - 1 == 0)

7
{
return a[index];
}
if (index >= l - 2) {
if (a[index] < a[index + 1])
return a[index];
else
return a[index + 1];
}

// Logic to find the Minimum element


// in the given array.
min = DAC_Min(a, index + 1, l);

if (a[index] < min)


return a[index];
else
return min;
}

// Driver Code
int main()
{
// Defining the variables
int min, max, N;

// Initializing the array


int a[7] = { 70, 250, 50, 80, 140, 12, 14 };

// recursion - DAC_Max function called


max = DAC_Max(a, 0, 7);

// recursion - DAC_Max function called


min = DAC_Min(a, 0, 7);
printf("The minimum number in a given array is : %d\n", min);
printf("The maximum number in a given array is : %d", max);
return 0;
}

OUTPUT:
Maximum: 120
Minimum: 11

RESULT:Thus the Divide and conquer using matrix multiplication was calculated and
verified.

8
EX NO:3 TOPOLOGICAL SORTING

AIM: To Implement decrease and conquer using topological sorting method.

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.

Topological Sort Example

Solving Using In-degree Method

Step 1: Write in-degree of all vertices:

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:

1. Identify a node with no incoming edges.


2. Add that node to the ordering.
3. Remove it from the graph.
4. Repeat the steps.

PROGRAM:

#include <stdio.h>

int main(){
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;

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


scanf("%d",&n);

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


for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}

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];

printf("\nThe topological order is:");

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:

Enter the no of vertices:


4
Enter the adjacency matrix:
Enter row 1
0110
Enter row 2
0001
Enter row 3
0001
Enter row 4
0000

The topological order is:1 2 3 4

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>

// Returns the count of ways we can


// sum coins[0...n-1] coins to get sum "sum"
int count(int coins[], int n, int sum)
{
// If sum is 0 then there is 1 solution
// (do not include any coin)
if (sum == 0)
return 1;

// If sum is less than 0 then no


// solution exists
if (sum < 0)
return 0;

// If there are no coins and sum


// is greater than 0, then no
// solution exist
if (n <= 0)
return 0;

// count is sum of solutions (i)


// including coins[n-1] (ii) excluding coins[n-1]
return count(coins, n - 1, sum)
+ count(coins, n, sum - coins[n - 1]);
}

// Driver program to test above function

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

Enter the number of vertices: 5


Enter the number of edges: 11
Enter the end vertices of edge 1: 1 1
Enter the end vertices of edge 2: 1 4
Enter the end vertices of edge 3: 3 2
Enter the end vertices of edge 4: 3 3
Enter the end vertices of edge 5: 3 4
Enter the end vertices of edge 6: 4 2
Enter the end vertices of edge 7: 4 4
Enter the end vertices of edge 8: 5 2
Enter the end vertices of edge 9: 5 3
Enter the end vertices of edge 10: 5 4
Enter the end vertices of edge 11: 5 5

Matrix of input data:


1 0 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1

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.

2. Array visited[ ] is initialized to zero.


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

3. If the vertex 0 is the source vertex then visited[0] is marked as 1.

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;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

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++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
OUTPUT:

HUFFMAN TREE AND CODES


Program:
#include <stdio.h>
#include <stdlib.h>

// This constant can be avoided by explicitly


// calculating height of Huffman Tree
#define MAX_TREE_HT 100

// A Huffman tree node


struct MinHeapNode {

// One of the input characters


char data;

// Frequency of the character


unsigned freq;

// Left and right child of this node


struct MinHeapNode *left, *right;

21
};

// A Min Heap: Collection of


// min-heap (or Huffman tree) nodes
struct MinHeap {

// Current size of min heap


unsigned size;

// capacity of min heap


unsigned capacity;

// Array of minheap node pointers


struct MinHeapNode** array;
};

// A utility function allocate a new


// min heap node with given character
// and frequency of the character
struct MinHeapNode* newNode(char data, unsigned freq)
{
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(
sizeof(struct MinHeapNode));

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


temp->data = data;
temp->freq = freq;

return temp;
}

// A utility function to create


// a min heap of given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap


= (struct MinHeap*)malloc(sizeof(struct MinHeap));

// current size is 0
minHeap->size = 0;

minHeap->capacity = capacity;

minHeap->array = (struct MinHeapNode**)malloc(


minHeap->capacity * sizeof(struct MinHeapNode*));
return minHeap;
}

22
// A utility function to
// swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a,
struct MinHeapNode** b)

struct MinHeapNode* t = *a;


*a = *b;
*b = t;
}

// The standard minHeapify function.


void minHeapify(struct MinHeap* minHeap, int idx)

int smallest = idx;


int left = 2 * idx + 1;
int right = 2 * idx + 2;

if (left < minHeap->size


&& minHeap->array[left]->freq
< minHeap->array[smallest]->freq)
smallest = left;

if (right < minHeap->size


&& minHeap->array[right]->freq
< minHeap->array[smallest]->freq)
smallest = right;

if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}

// A utility function to check


// if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap)
{

return (minHeap->size == 1);


}

// A standard function to extract


// minimum value node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

23
{

struct MinHeapNode* temp = minHeap->array[0];


minHeap->array[0] = minHeap->array[minHeap->size - 1];

--minHeap->size;
minHeapify(minHeap, 0);

return temp;
}

// A utility function to insert


// a new node to Min Heap
void insertMinHeap(struct MinHeap* minHeap,
struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;

while (i
&& minHeapNode->freq
< minHeap->array[(i - 1) / 2]->freq) {

minHeap->array[i] = minHeap->array[(i - 1) / 2];


i = (i - 1) / 2;
}

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>

#define CMAX 10 //max. number of variables in economic function


#define VMAX 10 //max. number of constraints

int NC, NV, NOPTIMAL,P1,P2,XERR;


double TS[CMAX][VMAX];

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

AIM: To implement Backtracking using branch and bound


ALGORITHM
We have to arrange four queens, Q1, Q2, Q3 and Q4 in 4 x 4 chess board. We will put
1.
ith queen in ith row. Let us start with position (1, 1). Q1 is the only queen, so there is no
issue. partial solution is <1>
2. We cannot place Q2 at positions (2, 1) or (2, 2). Position (2, 3) is acceptable. partial
solution is <1, 3>.
3. Next, Q3 cannot be placed in position (3, 1) as Q1 attacks her. And it cannot be placed at
(3, 2), (3, 3) or (3, 4) as Q2 attacks her. There is no way to put Q3 in third row. Hence,
the algorithm backtracks and goes back to the previous solution and readjusts the position
of queen Q2. Q2 is moved from positions (2, 3) to
(2, 4). Partial solution is <1, 4>
4. Now, Q3 can be placed at position (3, 2). Partial solution is <1, 4, 3>.
5. Queen Q4 cannot be placed anywhere in row four. So again, backtrack to the previous
solution and readjust the position of Q3. Q3 cannot be placed on (3, 3) or(3, 4). So the
algorithm backtracks even further.
6. All possible choices for Q2 are already explored, hence the algorithm goes back to partial
solution <1> and moves the queen Q1 from (1, 1) to (1, 2). And this process continues
until a solution is found.
PROGRAM:

#define N 4
#include <stdbool.h>
#include <stdio.h>

/* A utility function to print solution */


void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}

/* A utility function to check if a queen can


be placed on board[row][col]. Note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
So we need to check only left side for
attacking queens */
bool isSafe(int board[N][N], int row, int col)
{
int i, j;

/* Check this row on left side */

28
for (i = 0; i < col; i++)
if (board[row][i])
return false;

/* Check upper diagonal on left side */


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;

/* Check lower diagonal on left side */


for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;

return true;
}

/* A recursive utility function to solve N


Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;

/* Consider this column and try placing


this queen in all rows one by one */
for (int i = 0; i < N; i++) {
/* Check if the queen can be placed on
board[i][col] */
if (isSafe(board, i, col)) {
/* Place this queen in board[i][col] */
board[i][col] = 1;

/* recur to place rest of the queens */


if (solveNQUtil(board, col + 1))
return true;

/* If placing queen in board[i][col]


doesn't lead to a solution, then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
}
}

/* If the queen cannot be placed in any row in


this column col then return false */
return false;
}

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;
}

// driver program to test above function


int main()
{
solveNQ();
return 0;
}

OUTPUT
..Q.
Q...
...Q
.Q..
SUBSET SUM PROBLEM
include <stdio.h>
#include <stdlib.h>

#define ARRAYSIZE(a) (sizeof(a))/(sizeof(a[0]))

static int total_nodes;

// prints subset found


void printSubset(int A[], int size)

30
{
for(int i = 0; i < size; i++)
{
printf("%*d", 5, A[i]);
}

printf("\n");
}

// qsort compare function


int comparator(const void *pLhs, const void *pRhs)
{
int *lhs = (int *)pLhs;
int *rhs = (int *)pRhs;

return *lhs > *rhs;


}

// 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++;

if( target_sum == sum )


{
// We found sum
printSubset(t, t_size);

// 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];

if( sum + s[i] <= target_sum )


{
// consider next level node (along depth)

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

// state space tree node


struct Node
{
// stores parent node of current node
// helps in tracing path when answer is found
Node* parent;

// contains cost for ancestors nodes


// including current node
int pathCost;

// contains least promising cost


int cost;

// contain worker number


int workerID;

// contains Job ID
int jobID;

// Boolean array assigned will contains


// info about available jobs
bool assigned[N];
};

// Function to allocate a new search tree node


// Here Person x is assigned to job y
Node* newNode(int x, int y, bool assigned[],
Node* parent)
{
Node* node = new Node;

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;
}

// Function to calculate the least promising cost


// of node after worker x is assigned to job y.
int calculateCost(int costMatrix[N][N], int x,
int y, bool assigned[])
{
int cost = 0;

// to store unavailable jobs


bool available[N] = {true};

// start from next worker


for (int i = x + 1; i < N; i++)
{
int min = INT_MAX, minIndex = -1;

// do for each job


for (int j = 0; j < N; j++)
{
// if job is unassigned
if (!assigned[j] && available[j] &&
costMatrix[i][j] < min)
{
// store job number
minIndex = j;

// store cost
min = costMatrix[i][j];
}
}

// add cost of next worker


cost += min;

// job becomes unavailable


available[minIndex] = false;
}

return cost;
}

// Comparison object to be used to order the heap


struct comp
{
bool operator()(const Node* lhs,
const Node* rhs) const
{
return lhs->cost > rhs->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}
};*/

cout << "\nOptimal Cost is "


<< findMinCost(costMatrix);

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

You might also like