#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;
}
Maximum value's random index
最新推荐文章于 2023-02-08 15:58:40 发布
本文介绍了一种从数组中随机选取最大值索引的方法。首先遍历数组找到最大值及其出现次数,然后生成一个随机数作为最大值的第几次出现,并再次遍历数组返回该次出现的最大值的索引。

168万+

被折叠的 条评论
为什么被折叠?



