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 @Primary Annotation
Spring Boot: Customize Whitelabel Error Page
ClassNotFoundException vs NoClassDefFoundError
Spring MVC Setup with Kotlin
Flattening Nested Collections in Java
Sending Emails with Java
Servlet 3 Async Support with Spring MVC and Spring Security
Java Program to Implement Hash Tables with Quadratic Probing
Spring Boot: Customize the Jackson ObjectMapper
Apache Tiles Integration with Spring MVC
Batch Processing with Spring Cloud Data Flow
Java Program to Implement K Way Merge Algorithm
Retrieve User Information in Spring Security
Jackson Date
Java Program to Check if a Matrix is Invertible
Java Program to Implement Sorted Doubly Linked List
Hướng dẫn Java Design Pattern – Strategy
Java Program to Solve the Fractional Knapsack Problem
Introduction to Thread Pools in Java
Guide to the Synchronized Keyword in Java
Java Program to Check Cycle in a Graph using Topological Sort
Build a REST API with Spring and Java Config
Java Program to Check Whether Topological Sorting can be Performed in a Graph
Spring WebClient vs. RestTemplate
Spring Security Basic Authentication
Calling Stored Procedures from Spring Data JPA Repositories
Java Program to Emulate N Dice Roller
Custom Cascading in Spring Data MongoDB
Spring Boot - Quick Start
Java Program to Compute the Area of a Triangle Using Determinants
A Quick Guide to Spring Cloud Consul
Getting Started with Custom Deserialization in Jackson