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.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Check Computer Science Books
- Apply for C Internship
- Check C Books
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship