【发布时间】:2015-07-02 20:21:27
【问题描述】:
我想从数组中取出n 随机值。
我可以在 Python 中使用x=random.sample(listName, numberOfValuesNeeded)
[code]
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
const int MAX_Name=100;
srand((unsigned)time( NULL));
// Names
string PsDisp[MAX_Name]={"Alberto", "Bruno", "Carlo", "Dario", "Elio", "Francesco", "Giovanni", "Luca", "Marco", "Nicola", "Oreste", "Pietro", "Rino", "Sandro", "Tonino", "Valerio", "Vittorio"};
for(int x=1; x<=6; x++)
{
random_shuffle(begin(PsDisp), end(PsDisp));
cout << x << ": " << endl; // snomething missing before endl
}
return 0;
}
我想在屏幕上打印:
1:随机名称1
2:随机名称3 ...
6:随机名称6
【问题讨论】:
-
注意
std::random_shuffle不推荐,因为它的随机性可能很差。std::shuffle带有适当的 PRNG 更好。 -
1-6可以包含重复吗?如果没有,只需排序一次并打印前 6 个。访问元素的方法是
dispNames[x]。并使您的循环条件从 0 开始:for (int x=06; x<6; ++x) .... -
首先,这是一种非常低效(并且具有不必要的破坏性)的方法——就像在 Python 中使用
random.shuffle(n); return n[0]而不是return random.choice(n)。 -
另外,
random.sample为您提供无替换的样本,但您的算法为您提供有替换的样本。如果您希望您的代码无需替换即可工作,您只需随机播放一次并从结果中选择前 6 个值。 (但同样,不要使用 shuffle 进行采样……)