Skip to content

Commit 24c1a40

Browse files
Merge pull request matthewsamuel95#136 from sanchaymittal/patch-10
Randomized algorithms
2 parents 546e883 + 05ae018 commit 24c1a40

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//Randomly select a number from a set of numbers.
2+
#include<bits/stdc++.h>
3+
4+
using namespace std;
5+
6+
int selectRandom(int x)
7+
{
8+
static int res; // The resultant random number
9+
static int count = 0; //Count of numbers visited so far in stream
10+
11+
count++; // increment count of numbers seen so far
12+
13+
// If this is the first element from stream, return it
14+
if (count == 1)
15+
res = x;
16+
else
17+
{
18+
// Generate a random number from 0 to count - 1
19+
int i = rand() % count;
20+
21+
// Replace the prev random number with new number with 1/count probability
22+
if (i == count - 1)
23+
res = x;
24+
}
25+
return res;
26+
}
27+
28+
int main()
29+
{
30+
31+
int n;
32+
cout<<"Enter the Number of elements to be inserted in Array : ";
33+
cin >> n;
34+
35+
int a[n];
36+
37+
for (int i = 0; i < n; i++){
38+
cin>>a[i];
39+
}
40+
41+
for (int i = 0; i < n; ++i)
42+
printf("Random number from first %d numbers is %d \n",i+1, selectRandom(a[i]));
43+
return 0;
44+
}

0 commit comments

Comments
 (0)