Java Program to Generate a Random Subset by Coin Flipping

This is a java program to generate a random subset using coin flipping method. Coin is flipped, if is head(1), that element is in the subset else not in the subset.

Here is the source code of the Java Program to Generate a Random Subset by Coin Flipping. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a java program to generate a random subset using coin flipping 
  2. import java.util.Random;
  3. import java.util.Scanner;
  4.  
  5. public class Random_Subset_Coin_Flipping 
  6. {
  7.     static int coinFlip() 
  8.     {
  9.         Random random = new Random();
  10.         return random.nextInt(2);
  11.     }
  12.  
  13.     public static void main(String args[]) 
  14.     {
  15.         Random random = new Random();
  16.         Scanner sc = new Scanner(System.in);
  17.         System.out.println("Enter the number of elements in the set: ");
  18.         int N = sc.nextInt();
  19.         int[] sequence = new int[N];
  20.  
  21.         for (int i = 0; i < N; i++)
  22.             sequence[i] = Math.abs(random.nextInt(100));
  23.  
  24.         System.out.println("The elements in the set : ");
  25.         for (int i = 0; i < N; i++)
  26.             System.out.print(sequence[i] + " ");
  27.  
  28.         System.out.print("\nThe random subset is: \n{ ");
  29.         for (int i = 0; i < N; i++)
  30.             if (coinFlip() == 1)
  31.                 System.out.print(sequence[i] + " ");
  32.         System.out.println("}");
  33.         sc.close();
  34.     }
  35. }

Output:

$ javac Random_Subset_Coin_Flipping.java
$ java Random_Subset_Coin_Flipping
 
Enter the number of elements in the set: 
10
The elements in the set : 
1 44 88 58 8 62 94 59 38 33 
The random subset is: 
{ 1 44 8 33 }
 
Enter the number of elements in the set: 
3
The elements in the set : 
0 42 91 
The random subset is: 
{ 42 91 }

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java 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.