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 - Thymeleaf
Different Ways to Capture Java Heap Dumps
Java Program to Implement Sieve Of Atkin
Convert char to String in Java
Hướng dẫn Java Design Pattern – Template Method
Generating Random Numbers in a Range in Java
Introduction to Netflix Archaius with Spring Cloud
Spring Boot - Admin Client
Java Program to Implement Min Hash
Mockito and JUnit 5 – Using ExtendWith
HashSet trong java
Case-Insensitive String Matching in Java
Hướng dẫn Java Design Pattern – Builder
Java Program to Implement the Bin Packing Algorithm
How to Define a Spring Boot Filter?
Spring Boot - Tracing Micro Service Logs
Introduction to the Java NIO2 File API
Add Multiple Items to an Java ArrayList
Request Method Not Supported (405) in Spring
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Introduction to Spliterator in Java
How to Manually Authenticate User with Spring Security
Spring Boot Security Auto-Configuration
New Features in Java 10
Quick Intro to Spring Cloud Configuration
Java Program to Implement Binomial Heap
Spring Boot - CORS Support
Java Program to Perform Uniform Binary Search
Send email with authentication
Java Program to Perform Naive String Matching
HttpClient Timeout
Introduction to Apache Commons Text