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.
//This is a java program to generate a random subset using coin flipping
import java.util.Random;
import java.util.Scanner;
public class Random_Subset_Coin_Flipping
{
static int coinFlip()
{
Random random = new Random();
return random.nextInt(2);
}
public static void main(String args[])
{
Random random = new Random();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in the set: ");
int N = sc.nextInt();
int[] sequence = new int[N];
for (int i = 0; i < N; i++)
sequence[i] = Math.abs(random.nextInt(100));
System.out.println("The elements in the set : ");
for (int i = 0; i < N; i++)
System.out.print(sequence[i] + " ");
System.out.print("\nThe random subset is: \n{ ");
for (int i = 0; i < N; i++)
if (coinFlip() == 1)
System.out.print(sequence[i] + " ");
System.out.println("}");
sc.close();
}
}
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 }
Related posts:
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Spring Boot - Enabling Swagger2
Java Program to Implement HashTable API
Java Program to Check Whether Topological Sorting can be Performed in a Graph
Java Program to Implement Coppersmith Freivald’s Algorithm
Jackson Annotation Examples
Java Program to Check whether Graph is a Bipartite using DFS
Java Program to Implement Sparse Array
Java Program to Implement Queue
Java Program to Implement Hash Tables Chaining with Binary Trees
Spring Boot Change Context Path
Java Program to Implement RoleList API
Using Custom Banners in Spring Boot
Java Program to Implement Weight Balanced Tree
Using JWT with Spring Security OAuth (legacy stack)
Spring Boot - Sending Email
Setting Up Swagger 2 with a Spring REST API
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Java Program to Implement IdentityHashMap API
Java Program to Implement CountMinSketch
The Registration API becomes RESTful
Lập trình mạng với java
Apache Commons Collections MapUtils
Guide to DelayQueue
Getting Started with Custom Deserialization in Jackson
Java Program to Perform Naive String Matching
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to implement Bit Matrix
Spring Boot - Google Cloud Platform
A Guide to TreeMap in Java
Java 8 Streams peek() API
Một số ký tự đặc biệt trong Java