
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Random Subset by Coin Flipping in C++
This is a C++ program to generate a Random Subset by Coin Flipping.
Algorithms
Begin Take elements in an array as input. Using rand(), generate a random binary sequence. It generates randomly 0 or 1 as coin flipping and print the array element if it is 1. End
Example
#include<iostream> #include<stdlib.h> using namespace std; int main() { int i, n; cout<<"\nEnter the number of elements: "; cin>>n; int a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; } cout<<"\nThe random subset of the given set is: \n\t { "; for(i = 0; i < n; i++) { if(rand()%2 == 1) cout<<a[i]<<" "; } cout<<"}"; return 0; }
Output
Enter the number of elements: 7 Enter 1 element: 7 Enter 2 element: 6 Enter 3 element: 5 Enter 4 element: 4 Enter 5 element: 3 Enter 6 element: 2 Enter 7 element: 1 The random subset of the given set is: { 7 6 3 }
Advertisements