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:
Immutable Objects in Java
Java Copy Constructor
Java Multi-line String
Spring Boot - Interceptor
Debug a HttpURLConnection problem
Guide to Spring @Autowired
Using a List of Values in a JdbcTemplate IN Clause
Spring Boot - Scheduling
Simple Single Sign-On with Spring Security OAuth2
Java Program to Implement Direct Addressing Tables
RegEx for matching Date Pattern in Java
Java Program to Implement Threaded Binary Tree
How to Iterate Over a Stream With Indices
Hướng dẫn sử dụng Java String, StringBuffer và StringBuilder
A Custom Media Type for a Spring REST API
Flattening Nested Collections in Java
Java Program to Implement Sparse Matrix
The Order of Tests in JUnit
Compare Two JSON Objects with Jackson
Collection trong java
Exploring the New Spring Cloud Gateway
Java Program to Implement Network Flow Problem
Read an Outlook MSG file
Cơ chế Upcasting và Downcasting trong java
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Spring Boot - Introduction
Java Program to Implement Hash Trie
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Java Program to Perform Finite State Automaton based Search
Spring 5 Functional Bean Registration
Spring Boot - Tracing Micro Service Logs
Transactions with Spring and JPA