Exp6 S
Exp6 S
UID: 24MCI10173
Branch: MCA(AI&ML)
Section/Group: 3B
Semester: 1st
Date of Performance: 21 Oct. 2024
Subject Name: Design and Analysis Algorithm lab
Subject Code: 24CAP-612
Task to be done:
1. Input the Set and Target Sum: Collect the input set S = {s1, s2, ..., sn} and the target sum d from the
user.
2. Generate All Possible Subsets: Use a recursive function or iteration to generate all subsets of the set S.
3. Check Each Subset's Sum: For each subset, calculate the sum and compare it with the target d.
4. Output Valid Subsets: If the sum of a subset equals d, print or store that subset.
5. Handle No Solution Case: If no subsets satisfy the condition (subset sum equals d), display a message
like "No solution found."
Algorithm Step:
1. Input the Set and Target Sum: Read the set S = {s1, s2, ..., sn} and the target sum d.
2. Recursive Subset Generation: Use recursion or backtracking to generate all possible subsets of S. For
each element, decide whether to include it in the current subset or not.
3. Subset Sum Calculation: For each subset, compute its sum. If the sum equals the target d, mark the
subset as a solution.
4. Check for Solutions: After evaluating all subsets, if any valid subsets are found, output them.
5. No Solution Handling: If no subsets have a sum equal to d, display "No solution found."
#include <stdio.h>
#define MAX 100
void findSubsets(int S[], int n, int subset[], int subsetSize, int sum, int target, int start)
{
if (sum == target) {
printf("Subset found: { ");
for (int i = 0; i < subsetSize; i++) {
printf("%d ", subset[i]);
}
printf("}\n");
return;
}
subset[subsetSize] = S[start];
findSubsets(S, n, subset, subsetSize + 1, sum + S[start], target, start + 1);
if (sum != target) {
printf("No subset of the given set adds up to %d.\n", target);
}
}
int main() {
int S[] = {1,2,3,4,5,6,7,8};
int n = sizeof(S) / sizeof(S[0]);
int d = 6;
findSubsetSolution(S, n, d);
return 0;
}
Output:
Learning Outcomes:
1. Recursive Problem Solving: Understanding how to use recursion or backtracking to generate all
subsets of a set and solve combinatorial problems.
2. Subset Sum Concept: Gaining the ability to solve the subset sum problem, an important problem in
computer science and algorithms.
3. Efficient Search Techniques: Learning how to efficiently search for solutions by checking conditions
(subset sum equals target) within recursive or iterative structures.
5. Handling Edge Cases: Learning how to manage cases where no solution is found and implementing
appropriate error or no-solution messages.