C Program to Generate a Random Subset by Coin Flipping

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.

  1. #include<stdio.h>
  2. #include<math.h>
  3. #include<time.h>
  4. #include<stdlib.h>
  5.  
  6. int coinFlip() {
  7.     time_t seconds;
  8.     time(&seconds);
  9.     srand((unsigned int) seconds);
  10.     return rand() % 2;
  11. }
  12.  
  13. int main(int argc, char **argv) {
  14.     int i;
  15.     time_t seconds;
  16.     time(&seconds);
  17.     srand((unsigned int) seconds);
  18.  
  19.     printf("Enter the number of elements in the set: ");
  20.     int N;
  21.     scanf("%d", &N);
  22.     int sequence[N];
  23.  
  24.     for (i = 0; i < N; i++)
  25.         sequence[i] = rand() % (50 - 1 + 1) + 1;
  26.  
  27.     printf("The elements in the set : ");
  28.     for (i = 0; i < N; i++)
  29.         printf("%d ", sequence[i]);
  30.  
  31.     printf("\nThe random subset is: \n{ ");
  32.     for (i = 0; i < N; i++)
  33.         if (coinFlip() == 1)
  34.             printf("%d ", sequence[i]);
  35.     printf("}");
  36.     return 0;
  37. }

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]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.