1 Star 0 Fork 0

JJustRight/ACM-ICPC-Algorithms

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Random_Number_Selection_from_Array.cpp 981 Bytes
一键复制 编辑 原始数据 按行查看 历史
pockemon 提交于 2018-10-19 19:24 +08:00 . Added python code for problems in math section
//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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/jjustright/ACM-ICPC-Algorithms.git
git@gitee.com:jjustright/ACM-ICPC-Algorithms.git
jjustright
ACM-ICPC-Algorithms
ACM-ICPC-Algorithms
master

搜索帮助