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 Cubic convergence 1/pi Algorithm
Introduction to Spring Data JPA
Sao chép các phần tử của một mảng sang mảng khác như thế nào?
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Sorting Query Results with Spring Data
The Order of Tests in JUnit
Hướng dẫn sử dụng Printing Service trong Java
Comparing Arrays in Java
Guide to Escaping Characters in Java RegExps
Java Program to Compute Cross Product of Two Vectors
Functional Interfaces in Java 8
Spring Boot With H2 Database
Java 8 Streams peek() API
Recommended Package Structure of a Spring Boot Project
Xây dựng ứng dụng Client-Server với Socket trong Java
Tạo số và chuỗi ngẫu nhiên trong Java
Display Auto-Configuration Report in Spring Boot
MyBatis with Spring
Spring Boot: Customize Whitelabel Error Page
Spring Boot - Eureka Server
Java Program to Perform Postorder Recursive Traversal of a Given Binary Tree
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Java Program to Check whether Directed Graph is Connected using BFS
Documenting a Spring REST API Using OpenAPI 3.0
Optional trong Java 8
Java Program to Implement Suffix Array
Deque và ArrayDeque trong Java
Java Program to Implement SynchronosQueue API
Spring Data – CrudRepository save() Method
Guide to Spring Cloud Kubernetes
Understanding Memory Leaks in Java