Random Number Series Questions

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;
}


Randomly return any maximum index. Suppose in the array, we have many maximum values, randomly return one of the indexes. We can also apply the reservoir sampling technique here.

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值