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:
Hướng dẫn Java Design Pattern – Memento
XML Serialization and Deserialization with Jackson
Ignore Null Fields with Jackson
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Logout in an OAuth Secured Application
Quick Guide to the Java StringTokenizer
Spring Cloud AWS – Messaging Support
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Transactions with Spring and JPA
Java Program to Solve a Matching Problem for a Given Specific Case
Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java
Documenting a Spring REST API Using OpenAPI 3.0
Java Program to Implement LinkedHashSet API
Guava Collections Cookbook
Java – File to Reader
Create a Custom Exception in Java
Lớp LinkedHashMap trong Java
Hướng dẫn Java Design Pattern – DAO
Java Program to Find MST (Minimum Spanning Tree) using Prim’s Algorithm
Entity To DTO Conversion for a Spring REST API
An Intro to Spring Cloud Task
A Guide to JPA with Spring
Interface trong Java 8 – Default method và Static method
Using the Not Operator in If Conditions in Java
Java – Create a File
Spring Security Registration – Resend Verification Email
Hướng dẫn Java Design Pattern – Composite
HTTP Authentification and CGI/Servlet
Java Program to Implement Meldable Heap
Java Program to Use rand and srand Functions
Properties with Spring and Spring Boot