7 Program ADA 1
7 Program ADA 1
Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack problems
using greedy approximation method.
#include <stdio.h>
#define MAX_ITEMS 50
// Swap weights
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
// Swap profits
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
}
// Sort items
sortItems(weight, profit, ratio, n);
int main() {
int n;
float capacity;
int choice;
if (choice == 1) {
solveContinuousKnapsack(weight, profit, n, capacity);
} else if (choice == 2) {
solveDiscreteKnapsack(weight, profit, n, capacity);
} else {
printf("Invalid choice.\n");
}
return 0;
}
8.Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n positive
integers whose sum is equal to a given positive integer d.
#include <stdio.h>
#define MAX_SIZE 10
int set[MAX_SIZE], subset[MAX_SIZE];
int n, targetSum, flag = 0;
void display(int count) {
printf("{");
for (int i = 0; i < count; i++) {
printf("%d", subset[i]);
if (i < count - 1) {
printf(", ");
}
}
printf("}\n");
}
void findSubset(int sum, int index, int count) {
if (sum == targetSum) {
flag = 1;
display(count);
return;
}
if (sum > targetSum || index >= n) {
return;
}
subset[count] = set[index];
findSubset(sum + set[index], index + 1, count + 1);
findSubset(sum, index + 1, count);
}
int main() {
printf("Enter the number of elements in the set: ");
scanf("%d", &n);
printf("Enter the elements of the set: ");
for (int i = 0; i < n; i++) {
scanf("%d", &set[i]);
}
if (!flag) {
printf("There is no solution\n");
}
return 0;
}
EXPERIMENT-12
Design and implement C/C++ Program for N Queen's problem using Backtracking.
Program:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int totalSolutions = 0; // Global variable to store the total number of solutions
- - Q -
Q - - -
- - - Q
- Q - -
Total solutions: 2
#include <stdio.h>
#define MAX_SIZE 10
int main() {
printf("Enter the number of elements in the set: ");
scanf("%d", &n);
if (!flag) {
printf("There is no solution\n");
}
Sample Output:
Enter the number of elements in the set: 8
Enter the elements of the set: 1 2 3 4 5 6 7 8
Enter the target sum: 8
Subsets with sum 8:
{1, 2, 5}
{1, 3, 4}
{1, 7}
{2, 6}
{3, 5}
{8}