This is a C Program to generate all possible subsets with exactly K elements in each subset. Generate a permutation and include only k elements in subset.
Here is source code of the C Program to Generate All Possible Subsets with Exactly k Elements in Each Subset. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
int main(int argc, char **argv) {
int i, j;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
printf("Enter the number of elements in the set: ");
int N;
scanf("%d", &N);
int sequence[N];
for (i = 0; i < N; i++)
sequence[i] = rand() % (50 - 1 + 1) + 1;
printf("The elements in the set : ");
for (i = 0; i < N; i++)
printf("%d ", sequence[i]);
printf("Enter the number of elements in the subset: ");
int n;
scanf("%d", &n);
int binary[(int) pow(2, N)];
for (i = 0; i < pow(2, N); i++) {
int b = 1;
binary[i] = 0;
int num = i, count = 0;
while (num > 0) {
if (num % 2 == 1)
count++;
binary[i] += (num % 2) * b;
num /= 2;
b = b * 10;
}
if (count == n) {
printf("{ ");
for (j = 0; j < N; j++) {
if (binary[i] % 10 == 1)
printf("%d ", sequence[j]);
binary[i] /= 10;
}
printf("}\n");
}
}
return 0;
}
Output:
$ gcc KElementsSubset.c $ ./a.out Enter the number of elements in the set: 5 The elements in the set : 47 44 12 13 23 Enter the number of elements in the subset: 3 { 47 44 12 } { 47 44 13 } { 47 12 13 } { 44 12 13 } { 47 44 23 } { 47 12 23 } { 44 12 23 } { 47 13 23 } { 44 13 23 } { 12 13 23 }
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Check Computer Science Books
- Check C Books
- Practice Computer Science MCQs