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:
Java Program to Implement Binary Search Tree
Apache Commons Collections MapUtils
REST Web service: Basic Authentication trong Jersey 2.x
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Java Program to Implement Range Tree
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Generate All Possible Combinations Out of a, b, c, d, e
Hướng dẫn Java Design Pattern – Prototype
Java – Get Random Item/Element From a List
Spring Boot - Flyway Database
Java Program to Implement Hash Tables Chaining with Binary Trees
Read an Outlook MSG file
Biến trong java
Jackson Annotation Examples
Using Spring ResponseEntity to Manipulate the HTTP Response
Java Program to Implement Red Black Tree
Comparing Arrays in Java
Hướng dẫn Java Design Pattern – Chain of Responsibility
A Guide to the Java ExecutorService
Reactive Flow with MongoDB, Kotlin, and Spring WebFlux
Java Program to Perform Complex Number Multiplication
Java Program to implement Circular Buffer
Java Program to Find the Longest Path in a DAG
Java Program to Convert a Decimal Number to Binary Number using Stacks
Java Program to Solve any Linear Equations
Copy a List to Another List in Java
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
Marker Interface trong Java
Java String Conversions
Check if there is mail waiting
Collection trong java