forked from Shaily20/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandom_Number_Selection_from_Array.cpp
More file actions
44 lines (34 loc) · 981 Bytes
/
Random_Number_Selection_from_Array.cpp
File metadata and controls
44 lines (34 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//Randomly select a number from a set of numbers.
#include<bits/stdc++.h>
using namespace std;
int selectRandom(int x)
{
static int res; // The resultant random number
static int count = 0; //Count of numbers visited so far in stream
count++; // increment count of numbers seen so far
// If this is the first element from stream, return it
if (count == 1)
res = x;
else
{
// Generate a random number from 0 to count - 1
int i = rand() % count;
// Replace the prev random number with new number with 1/count probability
if (i == count - 1)
res = x;
}
return res;
}
int main()
{
int n;
cout<<"Enter the Number of elements to be inserted in Array : ";
cin >> n;
int a[n];
for (int i = 0; i < n; i++){
cin>>a[i];
}
for (int i = 0; i < n; ++i)
printf("Random number from first %d numbers is %d \n",i+1, selectRandom(a[i]));
return 0;
}