0% found this document useful (0 votes)
6 views28 pages

Daa Manual 2 PDF

The document is a laboratory record for students at Arunachala College of Engineering for Women, specifically for the Department of Artificial Intelligence and Data Science, focusing on the course AD3351 - Design and Analysis of Algorithms. It includes various programming exercises such as calculating factorials using recursion and non-recursion, generating Fibonacci series, solving the coin change problem using dynamic programming, implementing Strassen's matrix multiplication, and performing heap sort. Each exercise contains the aim, algorithm, program code, output, and results confirming successful execution.

Uploaded by

princy_usha
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)
6 views28 pages

Daa Manual 2 PDF

The document is a laboratory record for students at Arunachala College of Engineering for Women, specifically for the Department of Artificial Intelligence and Data Science, focusing on the course AD3351 - Design and Analysis of Algorithms. It includes various programming exercises such as calculating factorials using recursion and non-recursion, generating Fibonacci series, solving the coin change problem using dynamic programming, implementing Strassen's matrix multiplication, and performing heap sort. Each exercise contains the aim, algorithm, program code, output, and results confirming successful execution.

Uploaded by

princy_usha
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/ 28

ARUNACHALA COLLEGE OF ENGINEERING FOR WOMEN

Manavilai, Vellichanthai-629203
KanyaKumari District

LABORATORY RECORD

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

AD3351-DESIGN AND ANALYSIS OF ALGORITHMS

NAME OF THE STUDENT :

REGISTER NUMBER :

YEAR/SEM :
ARUNACHALA COLLEGE OF ENGINEERING FOR WOMEN
Manavilai, Vellichanthai-629203
Kanyakumari District

This is to certify that this is a bonafide record of the work done by


Ms.……………………………………………RegisterNumber ...................................................... of.
…………Semester,Department of Artificial Intelligence and Data Science of this college in the
AD3351-DESIGN AND ANALYSIS OF ALGORITHMS during April/May 2024 in partial
fulfillment of the requirement of the B.E degree course of the Anna University,Chennai.

Staff in Charge Head of the Department

This record is submitted for the Practical University Examination held on …………………………..

Internal Examiner External Examiner


INDEX

Sl.
No. Date Program Name Signature

2
Ex No: 1a Factorial of a Number Using Recursion
Date:

Aim: To write a program for implementing Factorial of a Number Using Recursion

Algorithm

• Start
• Get the input from the user, by using the entered value the fact() is called
• The n-1 value is passed to fact() from the function
• Every time the function is called the n value is decremented by 1
• Once the value of n is 1, the recursive function will be stopped and send the value to the main()
function.
• End

Program
#include<stdio.h>
long int fact(int x);
int main()
{
int x;
printf("Enter A Number To Find Factorial: ");
scanf("%d",&x);
printf("The Factorial of %d = %ld", x, fact(x));
return 0;
}

long int fact(int x)


{
if (x>=1)
return x*fact(x-1);
else
return 1;
}

Output:
Enter A Number To Find Factorial: 7
The Factorial of 7 = 5040

Result: Thus the Program to implementing Factorial Of A Number Using Recursion


was executed and verified successfully.

3
Ex No: 1b Factorial Of A Number Using Non-Recursion
Date:

Aim: To write a program for implementing Factorial Of A Using Non-Recursion


Algorithm
• Start.
• Read the integer n.
• If n is negative
• Print "Factorial of a negative number doesn't exist."
• Exit the algorithm.
• Initialize a variable fact to 1.
• For each integer i from 1 to n (inclusive)
• Multiply fact by i and store the result back in fact.
• Print the value of fact as the factorial of n.
• End.
Program
#include <stdio.h>
unsigned long long factorial(int n);
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of a negative number doesn't exist.\n");
} else
{
printf("Factorial of %d is %llu\n", num, factorial(num));
}
return 0;
}
unsigned long long factorial(int n)
{
unsigned long long fact = 1;
for (int i = 1; i <= n; ++i)
{
fact *= i;
}
return fact;
}

Output
Enter a number: 7
Factorial of 7 is 5040
Result: Thus the Program to implementing factorial of a number using non-recursion was executed and
verified successfully
4
Ex No: 2a Fibonacci series using non-recursion algorithms
Date:

Aim: To write a program for implementing Fibonacci series using non-recursion algorithms.
Algorithm
• Start.
• Read the integer x1, x2, and x3 are used to hold the Fibonacci sequence elements, and the
variable num is used to store the number of elements in the Fibonacci series.
• Enter the number of elements they want in the Fibonacci series using the printf and scanf
functions.
• The loop starts from a = 2 because the first two Fibonacci numbers 0 and 1 are already known
and printed outside the loop.
• Fibonacci Calculation: F(n) = F(n-1) + F(n-2).
• The printf statement inside the loop prints the value of x3, which is the next Fibonacci number in
the series.
• After printing the x3 value, the variables x1 and x2 are shifted to hold the values of the two
previous Fibonacci numbers for the next iteration.
• The program returns 0, indicating successful completion of the main function.
• End.

Program
#include<stdio.h>
int main()
{
int x1=0,x2=1,x3,a,num;
printf("Enter the number of elements:");
scanf("%d",&num);
printf("\n%d %d",x1,x2);//printing 0 and 1
for(a=2;a<num;++a)//loop starts from 2 because 0 and 1 are already printed
{
x3=x1+x2;
printf(" %d",x3);
x1=x2;
x2=x3;
}
return 0;
}
Output:
Enter the number of elements:15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Result: Thus the Program to implementing Fibonacci series using non-recursion algorithms was
executed and verified successfully

5
Ex No: 2b Fibonacci series using recursion algorithms
Date:

Aim: To write a program for implementing Fibonacci series using recursion algorithms.
Algorithm
• Start.
• variable a is initialized with the value 9 which represents the desired position of the Fibonacci
number in the sequence that we want to find.
• The printf statement in the main function prints the result.
• Fibonacci function to calculate the 9th Fibonacci number (a),
• displays the result with the format string: "%dth Fibonacci Number: %d".
• End.

Program
#include <stdio.h>
int fibonacci(int x)
{
if (x <= 1)
return x;
return fibonacci(x - 1) + fibonacci(x - 2);
}

int main()
{
int a = 9;
printf("%dth Fibonacci Number: %d", a, fibonacci(a));
return 0;
}
Output:

9th Fibonacci Number: 34

Result: Thus the Program to implementing Fibonacci series using recursion algorithms was executed and
verified successfully

6
Ex No: 3 Coin Change Problem with Dynamic Approach
Date:

Aim: To write a program for coin change problem with dynamic approach

Algorithm

1. The size of the dynamicprogTable is equal to (number of coins +1)*(Sum +1).


2. The first column value is one because there is only one way to change if the total amount is 0. (we do
not include any coin).
3. Row: The total number of coins. The fact that the first-row index is 0 indicates that no coin is
available. If the value index in the second row is 1, only the first coin is available. Similarly, if the
value index in the third row is 2, it means that the first two coins are available to add to the total
amount, and so on. The row index represents the index of the coin in the coins array, not the coin
value.

4. Column: Total amount (sum). Because the first-column index is 0, the sum value is 0. The second
column index is 1, so the sum of the coins should be 1. Similarly, the third column value is 2, so a
change of 2 is required, and so on.

5. As a result, each table field stores the solution to a sub problem.


For example, dynami progTable[2][3]=2 indicates two ways to compute the sum of three using the
first two coins 1,2.
6. The final outcome will be calculated by the values in the last column and row.
In this case, you must loop through all of the indexes in the memo table (except the first row and
column) and use previously-stored solutions to the subproblems.

• If the coin value is greater than the dynamicprogSum, the coin is ignored, i.e.
dynamicprogTable[i][j]=dynamicprogTable[i-1][j].

• If the coin value is less than the dynamicprogSum, you can consider it, i.e.
dynamicprogTable[i][j]=dynamicprogTable[i-1].[dynamicprogSum]+dynamicprogTable[i][j-coins[i-
1]].

Program

#include <stdio.h>
int coins[] = {1,2,3}, sum=4;
int numberofCoins = 3;
//Function to initialize 1st column of dynamicprogTable with 1
void initdynamicprogTable(int dynamicprogTable[][5])
{
int i;
//First row to 0
for(i=1; i<=sum+1; i++)
{
dynamicprogTable[0][i] = 0;
7
}
//First column to 1
for(i=1; i<=numberofCoins; i++)
{
dynamicprogTable[i][0] = 1;
}
}
int solution(int dynamicprogTable[][5])
{
int coinindex, dynamicprogSum;
for(coinindex=1; coinindex<numberofCoins+1; coinindex++)
{
for(dynamicprogSum=1; dynamicprogSum< 5; dynamicprogSum++)
{
//value of coin should be less than or equal to sum value to consider it
if(coins[coinindex-1] > dynamicprogSum)
dynamicprogTable[coinindex][dynamicprogSum] =
dynamicprogTable[coinindex1][dynamicprogSum];
else
dynamicprogTable[coinindex][dynamicprogSum] = dynamicprogTable[coinindex-
1][dynamicprogSum]+dynamicprogTable[coinindex][dynamicprogSum-coins[coinindex-1]];
}
}
//return final row and column value
return dynamicprogTable[numberofCoins][sum];
}
int main()
{
int dynamicprogTable[numberofCoins+1][5];
initdynamicprogTable(dynamicprogTable);
printf("Total Solutions: %d",solution(dynamicprogTable));
return 0;
}

Output

Result: Thus the Program for coin change problem with dynamic approach was executed and verified
successfully.

8
Ex No:4 Strassen’s Matrix Multiplication
Date:
Aim: To write a program for strassen’s Matrix Multiplication

Algorithm
1. Divide the input matrices A and B into four equal-sized sub-matrices each.
2. Compute seven matrix multiplications recursively as follows:
- Multiply the top left sub-matrix of A with the top left sub-matrix of B.
- Multiply the top right sub-matrix of A with the bottom left sub-matrix of B.
- Multiply the bottom left sub-matrix of A with the top right sub-matrix of B.
- Multiply the bottom right sub-matrix of A with the bottom right sub-matrix of B.
- Add the results of these multiplications together to obtain four intermediate resultmatrices.
3. Combine the four intermediate result matrices to form the final result matrix:
- Construct the top left quadrant of the final result matrix by adding the top left andtopright
intermediate matrices.
- Construct the bottom left quadrant of the final result matrix by adding the bottomleftand
bottom right intermediate matrices.
- Construct the top right quadrant of the final result matrix by subtracting the topleft
intermediate matrix from the top right intermediate matrix.
- Construct the bottom right quadrant of the final result matrix by subtracting thebottom left
intermediate matrix from the bottom right intermediate matrix.
4. The final result matrix is the product of the input matrices A and B.
Program
#include<stdio.h>
int main()

{
int z[2][2];
int i, j;
int m1, m2, m3, m4 , m5, m6, m7;
intx[2][2] = {{12, 34},{22, 10}};
int y[2][2] = {{3, 4}{2, 1}};
printf("\nThe first matrix is\n");
for(i= 0; i < 2; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", x[i][j]);
}
printf("\nThe second matrix is\n");

9
for(i = 0; i < 2; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", y[i][j]);
}
m1= (x[0][0] + x[1][1]) * (y[0][0] + y[1][1]);
m2= (x[1][0] + x[1][1]) * y[0][0];
m3= x[0][0] * (y[0][1] - y[1][1]);
m4= x[1][1] * (y[1][0] - y[0][0]);
m5= (x[0][0] + x[0][1]) * y[1][1];
m6= (x[1][0] - x[0][0]) * (y[0][0]+y[0][1]);
m7= (x[0][1] - x[1][1]) * (y[1][0]+y[1][1]);
z[0][0]= m1 + m4- m5 + m7;
z[0][1] = m3 + m5;
z[1][0] = m2 + m4;
z[1][1] = m1 - m2 + m3 + m6;
printf("\nProduct achieved using Strassen's algorithm \n");
for(i = 0; i < 2 ; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", z[i][j]);
}
return 0;
}
Output

Result: Thus the Program to multiply two matrices using strassens algorithm was executed and
verified successfully.

10
Ex No:5 Transform and conquer – Heap sort
Date:

Aim: To write a program for Transform and conquer – Heap sort

Algorithm
1. Start
2. Print the unsorted array.
3. Creating the binary heap of the array.
4. Start iteration from the last leaf node of the heap to the root node.
5. Each iteration swaps the root node with the last leaf node and then calls the
heapify operation to rearrange the heap.
6. On heapify operation, swap the larger children element with the root node if
the root is smaller than the child.
7. Print the sorted array.
8. Stop.
Program
#include <stdio.h>
// Function to swap two elements
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}

// Heapify function to maintain the max-heap property


void heapify(int array[], int size, int index)
{
int largest = index; // Initialize the largest element as the root
int left = 2 * index + 1; // Left child index
int right = 2 * index + 2; // Right child index
// If left child is larger than root
if (left < size && array[left] > array[largest])
{
largest = left;
}
// If right child is larger than largest so far
if (right < size && array[right] > array[largest])
{

11
largest = right;
}
// If largest is not the root, swap the root with the largest element
if (largest != index) {
swap(&array[index], &array[largest]);
// Recursively heapify the affected sub-tree
heapify(array, size, largest);
}
}

// Heap Sort function


void heapSort(int array[], int size)
{
// Build the max-heap from the array
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
// Extract elements from the heap one by one
for (int i = size - 1; i > 0; i--) {
// Move the current root (maximum element) to the end
swap(&array[0], &array[i]);
// Heapify the reduced heap
heapify(array, i, 0);
}
}
// Function to print an array
void printArray(int array[], int size)
{
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
// Driver code
int main()
{
int arr[] = {54, 32, 67, 12, 90, 5};
int size = sizeof(arr) / sizeof(arr[0]);

12
printf("Original array: ");
printArray(arr, size);
heapSort(arr, size);
printf("Sorted array: ");
printArray(arr, size);
return 0;
}

Output:
Original array: 54 32 67 12 90 5
Sorted array: 5 12 32 54 67 90

Result: Thus the implementation of heap sort was done and verified successfully

13
Ex No:6 Dynamic Programming – FLOYD ALGORITHM
Date:
Aim: To write a c program for Dynamic Programming – FLOYD ALGORITHM

Algorithm
1. Start
2. Declare the variables.
3. Read the number of vertices and edges of the graph.
4. It takes the adjacency matrix as input and it find the transitive closure of the given graph.
5. Print the matrix
6.Stop.

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++)
{
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);
}
14
Output:
All Pairs Shortest Path is :
0354
5023
3601
2570

Result: Thus the implementation of FLOYD algorithm was done and verified successfully

15
Ex No: 7 Greedy technique – Dijkstra’s algorithm
Date:

Aim: To write the c program for Greedy technique – Dijkstra’s algorithm

Algorithm

1. Start with a weighted graph

2. Choose a starting vertex and assign infinity path values to all other devices

3. Go to each vertex and update its path length

4. If the path length of the adjacent vertex is lesser than new path length, don't update it

5. Avoid updating path lengths of already visited vertices

6. After each iteration, we pick the unvisited vertex with the least path length. So we

choose 5 before 7

7. Notice how the rightmost vertex has its path length updated twice

8.Repeat until all the vertices have been visited


Program
#include <stdio.h>
#define INFINITY 9999
#define MAX 10
void Dijkstra(int Graph[MAX][MAX], int n, int start);
void Dijkstra(int Graph[MAX][MAX], int n, int start)
{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i, j;
// Creating cost matrix
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (Graph[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = Graph[i][j];
for (i = 0; i < n; i++)
{
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
}
16
distance[start] = 0;
visited[start] = 1;
count = 1;
while (count < n - 1)
{
mindistance = INFINITY;
for (i = 0; i < n; i++)
if (distance[i] < mindistance && !visited[i])
{
mindistance = distance[i];
nextnode = i;
}
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;
}
count++;
}
// Printing the distance
for (i = 0; i < n; i++)
if (i != start) {
printf("\nDistance from source to %d: %d", i, distance[i]);
}
}
int main() {
int Graph[MAX][MAX], i, j, n, u;
n = 7;
Graph[0][0] = 0;
Graph[0][1] = 0;
Graph[0][2] = 1;
Graph[0][3] = 2;
Graph[0][4] = 0;
Graph[0][5] = 0;
Graph[0][6] = 0;

Graph[1][0] = 0;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 3;
Graph[1][6] = 0;

Graph[2][0] = 1;
17
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 1;
Graph[2][4] = 3;
Graph[2][5] = 0;
Graph[2][6] = 0;

Graph[3][0] = 2;
Graph[3][1] = 0;
Graph[3][2] = 1;
Graph[3][3] = 0;
Graph[3][4] = 0;
Graph[3][5] = 0;
Graph[3][6] = 1;

Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 3;
Graph[4][3] = 0;
Graph[4][4] = 0;
Graph[4][5] = 2;
Graph[4][6] = 0;

Graph[5][0] = 0;
Graph[5][1] = 3;
Graph[5][2] = 0;
Graph[5][3] = 0;
Graph[5][4] = 2;
Graph[5][5] = 0;
Graph[5][6] = 1;

Graph[6][0] = 0;
Graph[6][1] = 0;
Graph[6][2] = 0;
Graph[6][3] = 1;
Graph[6][4] = 0;
Graph[6][5] = 1;
Graph[6][6] = 0;
u = 0;
Dijkstra(Graph, n, u);
return 0;
}

18
Output
Distance from source to 1: 3

Distance from source to 2: 1

Distance from source to 3: 2

Distance from source to 4: 4

Distance from source to 5: 4

Distance from source to 6: 3

Result: Thus the implementation of Dijkstra’s algorithm was done and verified successfully

19
Ex No: 8 Backtracking – n-queens problem
Date:

Aim: To write the c program for Backtracking – n-queens problem

Algorithm
1. Start
2. N Queen’s problem is the puzzle.
3. Placing chess queens on a chessboard, so that no two queensattack each other.
4. Here we use the Brute-Force method to solve the problem.
5. Stop
Program
#include<stdio.h>
#define BOARD_SIZE 5
void displayChess(int chBoard[BOARD_SIZE][BOARD_SIZE]) {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++)
printf("%d ", chBoard[row][col]);
printf("\n");
}
}
int isQueenPlaceValid(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntRow, int crntCol) {
// checking if queen is in the left or not
for (int i = 0; i < crntCol; i++)
if (chBoard[crntRow][i])
return 0;
for (int i = crntRow, j = crntCol; i >= 0 && j >= 0; i--, j--)
//checking if queen is in the left upper diagonal or not
if (chBoard[i][j])
return 0;
for (int i = crntRow, j = crntCol; j >= 0 && i < BOARD_SIZE; i++, j--)
//checking if queen is in the left lower diagonal or not
if (chBoard[i][j])
return 0;
return 1;
}
int solveProblem(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntCol) {

20
//when N queens are placed successfully
if (crntCol >= BOARD_SIZE)
return 1;
// checking placement of queen is possible or not
for (int i = 0; i < BOARD_SIZE; i++) {
if (isQueenPlaceValid(chBoard, i, crntCol)) {
//if validate, place the queen at place (i, col)
chBoard[i][crntCol] = 1;
//Go for the other columns recursively
if (solveProblem(chBoard, crntCol + 1))
return 1;
//When no place is vacant remove that queen
chBoard[i][crntCol] = 0;
}
}
return 0;
}
int displaySolution() {
int chBoard[BOARD_SIZE][BOARD_SIZE];
for(int i = 0; i < BOARD_SIZE; i++)
for(int j = 0; j < BOARD_SIZE; j++)
//set all elements to 0
chBoard[i][j] = 0;
//starting from 0th column
if (solveProblem(chBoard, 0) == 0) {
printf("Solution does not exist");
return 0;
}
displayChess(chBoard);
return 1;
}
int main()
{
displaySolution();
return 0;
}
21
Output:

10000
00010
01000
00001
00100

Result: Thus the implementation of N-Queens Problem was done and verified successfully.

22
Ex No: 9 Branch and bound – traveling salesman problem
Date:

Aim: To write the c program for Branch and bound – traveling salesmanproblem

Algorithm:
1. Start
2. Read the number of cities and the cost matrix.
3. Find the path with minimum cost using mincost()
function.
4.4.Print the path with least cost.
5.Sto #include<stdio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()
{
int i,j;

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


scanf("%d",&n);

printf("\nEnter the Cost Matrix\n");

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


{
printf("\nEnter Elements of Row: %d\n",i+1);

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


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

completed[i]=0;
}

printf("\n\nThe cost list is:");

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


{
printf("\n");

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


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

void mincost(int city)


23
{
int i,ncity;

completed[city]=1;

printf("%d--->",city+1);
ncity=least(city);

if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];

return;
}

mincost(ncity);
}

int least(int c)
{
int i,nc=999;
int min=999,kmin;

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


{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}

if(min!=999)
cost+=kmin;

return nc;
}

int main()
{
takeInput();

printf("\n\nThe Path is:\n");


mincost(0); //passing 0 because starting vertex
24
printf("\n\nMinimum cost is %d\n ",cost);

return 0;
}
p
Program

OUTPUT:
Enter the number of villages: 4
Enter the Cost Matrix

Enter Elements of Row: 1


0413
Enter Elements of Row: 2
4021
Enter Elements of Row: 3
1205
Enter Elements of Row: 4
3150
The cost list is:
0 4 1 3
4 0 2 1
1 2 0 5
3 1 5 0

The Path is:


1--->3--->2--->4--->1

Minimum cost is 7

Result: Thus the implementation of Traveling Salesman Problem was done and verifiedsuccessfully

25
Ex No: 10 Subset Sum Problem using Backtracking.
Date:

Aim: To write the C to solve the Subset Sum Problem using Backtracking.

Algorithm
• Input: A set of integers
• Target sum
• A temporary array, subset[], to store the current subset.
• Variables: to keep track of the size of the current subset, total to store the sum of the current
subset, and index to track the current position in the set.
• If total equals target, print the current subset and return.
• If total exceeds target or index is equal to the size of the set, return (backtrack).
• Include the current element (set[index]) in the subset and call the function recursively with
updated parameters (subsetSize + 1, total + set[index], index + 1).
• Exclude the current element from the subset and call the function recursively with updated
parameters (subsetSize, total, index + 1).

Program
#include <stdio.h>
#include <stdlib.h>
static int total_nodes;
void printValues(int A[], int size){
for (int i = 0; i < size; i++) {
printf("%*d", 5, A[i]);
}
printf("\n");
}
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) {
printValues(t, t_size);
subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);
return;
}
else {
for (int i = ite; i < s_size; i++) {
t[t_size] = s[i];
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}
void generateSubsets(int s[], int size, int target_sum){
int* tuplet_vector = (int*)malloc(size * sizeof(int));
subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);
free(tuplet_vector);
26
}
int main(){
int set[] = { 5, 6, 12 , 54, 2 , 20 , 15 };
int size = sizeof(set) / sizeof(set[0]);
printf("The set is ");
printValues(set , size);
generateSubsets(set, size, 25);
printf("Total Nodes generated %d\n", total_nodes);
return 0;
}

Output:
The set is 5 6 12 54 2 20 15
5 6 12 2
5 20
Total Nodes generated 127

Result: Thus the implementation of Subset Sum Problem using Backtracking was done and verified
successfully

27

You might also like