This is a C Program to generate a random subset by flipping coin. Basic idea is to generate randomly number either 0/1, if the number is zero print the subset.
Here is source code of the C Program to Generate a Random Subset by Coin Flipping. 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 coinFlip() {
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
return rand() % 2;
}
int main(int argc, char **argv) {
int i;
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("\nThe random subset is: \n{ ");
for (i = 0; i < N; i++)
if (coinFlip() == 1)
printf("%d ", sequence[i]);
printf("}");
return 0;
}
Output:
$ gcc CoinFlipping.c $ ./a.out Enter the number of elements in the set: 5 The elements in the set : 31 5 13 28 33 The random subset is: { 31 5 13 28 33 }
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Computer Science Internship
- Apply for C Internship
- Practice BCA MCQs
- Buy C Books
- Buy Computer Science Books