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:
Spring Boot - Service Components
Spring Boot Integration Testing with Embedded MongoDB
Java Program to Implement RenderingHints API
Java Program to implement Dynamic Array
Custom Exception trong Java
Spring Boot - Rest Controller Unit Test
Instance Profile Credentials using Spring Cloud
Java Program to Permute All Letters of an Input String
Quick Guide on Loading Initial Data with Spring Boot
Spring Boot - Interceptor
Java Program to Describe the Representation of Graph using Adjacency List
The DAO with JPA and Spring
Spring Security Custom AuthenticationFailureHandler
Java Program to Implement Maximum Length Chain of Pairs
Introduction to Spring Data REST
Java Program to Implement Skew Heap
Java Program to Implement AA Tree
Java Program to Implement HashSet API
A Comparison Between Spring and Spring Boot
Summing Numbers with Java Streams
Jackson – Bidirectional Relationships
Java Program to implement Sparse Vector
Add Multiple Items to an Java ArrayList
Java Program to Implement Bloom Filter
Java TreeMap vs HashMap
Java Multi-line String
Handling URL Encoded Form Data in Spring REST
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
A Custom Media Type for a Spring REST API
Mệnh đề if-else trong java
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Converting a Stack Trace to a String in Java