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 Hamiltonian Cycle Algorithm
Introduction to Using Thymeleaf in Spring
Java Program to Implement Euler Circuit Problem
Jackson Ignore Properties on Marshalling
Jackson Exceptions – Problems and Solutions
Using a List of Values in a JdbcTemplate IN Clause
Java Program to Generate Random Numbers Using Multiply with Carry Method
Spring Boot: Customize the Jackson ObjectMapper
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Deploy a Spring Boot App to Azure
Spring Boot - Service Components
Java Program to Implement Knight’s Tour Problem
Java Program to Perform Searching Using Self-Organizing Lists
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Java 8 Collectors toMap
A Guide to Spring Boot Admin
Difference Between Wait and Sleep in Java
Marker Interface trong Java
Java Program to Find Inverse of a Matrix
The “final” Keyword in Java
Lập trình hướng đối tượng (OOPs) trong java
Hướng dẫn Java Design Pattern – Iterator
Entity To DTO Conversion for a Spring REST API
Spring Boot - CORS Support
Display Auto-Configuration Report in Spring Boot
Java – Get Random Item/Element From a List
Java Program to Implement Cartesian Tree
A Quick Guide to Spring Cloud Consul
Java Program to Find a Good Feedback Edge Set in a Graph
Comparing Strings in Java
Jackson JSON Views
A Guide to the ViewResolver in Spring MVC