C++实现从数组生成排除指定值的4个不重复随机索引问题
解决方案
你已经预先整理了仅包含合法索引的rand_pool,直接基于这个池子做随机采样即可满足所有要求:
- 采样全程仅使用预先筛选的合法值,不会命中要排除的2、3索引
- 采样结果天然无重复,不会出现重复取值问题
- 全程不修改原数组,不会影响后续索引计算逻辑
修正后可直接运行的代码
#include <iostream> #include <string> #include <cstdlib> #include <algorithm> #include <vector> #include <ctime> int main() { // 合法索引池,已排除指定过滤的2、3索引 static int rand_pool_arr[]{0, 1, 4, 5, 6, 7, 8, 9}; std::vector<int> rand_pool(std::begin(rand_pool_arr), std::end(rand_pool_arr)); std::string years[] = {"2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"}; srand((int)time(0)); // 打乱合法索引池顺序 std::random_shuffle(rand_pool.begin(), rand_pool.end()); std::vector<std::string> random_years; // 取前4个不重复的合法索引取值 for(int i = 0; i < 4; i++){ random_years.push_back(years[rand_pool[i]]); } // 输出结果 for (const auto& year : random_years) { std::cout << "\n" << year << "\n"; } return 0; }
逻辑说明
核心思路是对无重复的合法索引池做随机打乱后取前N个,对于你当前8个元素的索引池来说,全打乱的性能开销可完全忽略,逻辑简洁易维护。如果后续需要调整过滤的索引,仅需要修改rand_pool_arr的内容即可,其他逻辑无需改动。
内容的提问来源于stack exchange,提问作者Alex Pina
相关产品推荐
相关产品推荐

