Maximum value's random index

来源:互联网 发布:c语言while语句举例 编辑:程序博客网 时间:2024/06/06 02:01
#include <vector>#include <iostream>#include <cstdlib>#include <climits>#include <time.h>using namespace std;// naive method// Go through the array once, find the max and the number of occurrences (n)// Generate a random number (r) between 1 and n// Go through the array again, return rth occurrance.int randomIndex(vector<int>& nums) {  int max_val = INT_MIN;  int count = 0;  for(int i = 0; i < nums.size(); ++i) {    if(nums[i] > max_val) {      max_val = nums[i];      count = 1;    } else if(nums[i] == max_val) {      count++;    }  }  srand(time(NULL));  int random_value = rand() % count + 1;  cout << random_value << endl;  cout << "random value is" << endl;  int max_index = 1;  for(int i = 0; i < nums.size(); ++i) {    if(nums[i] == max_val && max_index == random_value) {      return i;    } else if(nums[i] == max_val) max_index++;  }}int main(void) {  vector<int> nums{2, 1, 2, 1, 5, 4, 5, 5};  cout << randomIndex(nums) << endl;}

0 0