Random Number Series Questions
来源:互联网 发布:淘宝兼职红包单 编辑:程序博客网 时间:2024/04/20 06:49
This webpage gives a perfect solution to generate K random numbers from given N size array: http://www.geeksforgeeks.org/reservoir-sampling/
However, there are a varieties of related questions.
1: implement an algorithm that takes as input an array of distinct element and a size, return a subset of the given size of the array elements. All subset should be equally likely. Return the result in input array itself.
int randomGenerator(int left, int right) { srand(time(NULL)); return left + rand() % (right - left + 1);}// given a size of array and input k, return k subset random numbers.void randomK(vector<int>& nums, int k) { default_random_engine seed((random_device())()); for(int i = 0; i < k; ++i) { swap(nums[i], nums[uniform_int_distribution<int>{i, static_cast<int>(nums.size()) - 1}(seed)]); } return;}int main(void) { vector<int> nums{0, 1, 2, 3, 4, 5, 6}; randomK(nums, 3); for(int i = 0; i < 3; ++i) { cout << nums[i] << " "; } cout << endl;}
1: The first though is to count the maximum values numbers, generate a random number for this count, traverse the array again and return the random index.
2: we can make use of the reservoir sampling.
#include "header.h"using namespace std;// in an unsorted array, there are many maximum values, randomly return one index.int randomMaximumValueIndex(vector<int>& nums) { srand(time(NULL)); int maxValue = 0; int count = 0; int res = 0; for(int i = 0; i < nums.size(); ++i) { if(nums[i] > maxValue) { maxValue = nums[i]; count++; res = i; } else if(nums[i] == maxValue){ if(rand() % ++count == 0) res = i; // if found the other maxValue, randomly update the index. } } return res;}int main(void) { vector<int> nums{0, 1, 6, 3, 6, 5, 6}; cout << randomMaximumValueIndex(nums) << endl;}
0 0
- Random Number Series Questions
- random number
- [Random Coding]Interval Related Questions
- random number in C
- Pseduo Random Number Generator
- Random Number Generation
- Generating the random number
- Random number for GPU
- [c++] random number
- Hackerrank Random Number Generator
- random, urandom - kernel random number source devices
- Random Number系列:Discrete Uniform random variable
- Algorithm of poisson random number
- Random Number系列:二项分布(Binomial)
- change the random number everytime
- 关于Pseudorandom number 和 Genuine random number
- VMware Server 2 序列号series number
- pandas基础:Series、和NumPy里的random.x()
- 3497. 水仙花数
- SparkML之推荐算法(一)ALS
- 3 Sum
- IntelliJ IDEA快捷键大全(图片)
- NoSql入门和概述
- Random Number Series Questions
- SparkStreaming之基本数据源输入
- C++学习指南
- SparkStreaming之DStream operations
- SparkStreaming之foreachRDD
- SparkStreaming之窗口函数
- SparkStreaming之Output Operations
- CODEFORCES 270B Multithreading <<新闻持续更新>>
- SparkStreaming之Accumulators和Broadcast