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 find the maximum subarray sum O(n^2) time(naive method)
A Comparison Between Spring and Spring Boot
Java Program to Implement Adjacency Matrix
Introduction to Using Thymeleaf in Spring
Hướng dẫn Java Design Pattern – Transfer Object
Creating a Custom Starter with Spring Boot
Java Program to Implement Circular Doubly Linked List
Dynamic Proxies in Java
Guava CharMatcher
Java Program to Check Whether a Directed Graph Contains a Eulerian Cycle
The “final” Keyword in Java
Hướng dẫn Java Design Pattern – Flyweight
Java 8 and Infinite Streams
So sánh ArrayList và Vector trong Java
How to Return 404 with Spring WebFlux
Introduction to Spring Data JPA
Java Streams vs Vavr Streams
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Control Structures in Java
Reactive WebSockets with Spring 5
Guide to Java Instrumentation
Array to String Conversions
Java Program to Implement Sorted Doubly Linked List
Mảng (Array) trong Java
Java Multi-line String
Java Program to Implement Heap’s Algorithm for Permutation of N Numbers
Java Program to Print only Odd Numbered Levels of a Tree
JWT – Token-based Authentication trong Jersey 2.x
Lập trình đa luồng với CompletableFuture trong Java 8
A Guide to Concurrent Queues in Java
Java Program to Implement LinkedBlockingDeque API
Semaphore trong Java