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:
A Guide to the ViewResolver in Spring MVC
Giới thiệu Google Guice – Binding
Lớp Arrarys trong Java (Arrays Utility Class)
Setting a Request Timeout for a Spring REST API
Spring Data JPA @Query
Send email with SMTPS (eg. Google GMail)
Java Program to Implement Red Black Tree
Java Program to Describe the Representation of Graph using Incidence List
Spring Boot - Cloud Configuration Server
Sending Emails with Java
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Reversing a Linked List in Java
Guide to Java OutputStream
A Guide to the finalize Method in Java
Spring Boot Actuator
Transactions with Spring and JPA
Convert Hex to ASCII in Java
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
How to Store Duplicate Keys in a Map in Java?
Java Optional as Return Type
Java Program to Implement Insertion Sort
Java Program to Find a Good Feedback Vertex Set
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Lớp LinkedHashMap trong Java
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
How to Delay Code Execution in Java
Predicate trong Java 8
Spring Cloud Connectors and Heroku
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Java Program to Compute Discrete Fourier Transform Using Naive Approach
Java Program for Douglas-Peucker Algorithm Implementation
A Guide to Queries in Spring Data MongoDB