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:
Quick Guide to Spring Controllers
Lập trình mạng với java
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Hướng dẫn Java Design Pattern – Template Method
Different Ways to Capture Java Heap Dumps
Java Switch Statement
Spring JDBC
Java Program to Represent Graph Using 2D Arrays
String Joiner trong Java 8
Deque và ArrayDeque trong Java
Java Program to Implement Strassen Algorithm
ExecutorService – Waiting for Threads to Finish
Collect a Java Stream to an Immutable Collection
Java Program to Implement Quick Sort with Given Complexity Constraint
Toán tử trong java
Validations for Enum Types
Java Program to Implement vector
Java equals() and hashCode() Contracts
Java Program to Implement Rope
HttpClient 4 – Follow Redirects for POST
Java Program to Find Transitive Closure of a Graph
Java Program to Implement Sorted Array
Spring RestTemplate Request/Response Logging
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Spring Data MongoDB Transactions
Java Program to Implement Range Tree
Java Program to Implement Circular Doubly Linked List
Guide to the Java Queue Interface
Giới thiệu Google Guice – Dependency injection (DI) framework
Java Program to Implement Hash Tables with Quadratic Probing
Comparing Two HashMaps in Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào?