打乱 vector 中一定比例的元素的最佳方法是什么。
假设我想要打乱 10% 或 90% 的 vector 。 不一定是前 10%,而是全面的 10%。
TIA
最佳答案
修改 Fisher-Yates 洗牌以对数组中 10% 的索引不执行任何操作。
这是我发布(来自维基百科)和修改的 Java 代码,但我认为您可以将其翻译成 C++,因为这更像是一个算法问题,而不是语言问题。
public static void shuffleNinetyPercent(int[] array)
{
Random rng = new Random(); // java.util.Random.
int n = array.length; // The number of items left to shuffle (loop invariant).
while (n > 1)
{
n--; // n is now the last pertinent index
if (rng.nextDouble() < 0.1) continue; //<-- ADD THIS LINE
int k = rng.nextInt(n + 1); // 0 <= k <= n.
// Simple swap of variables
int tmp = array[k];
array[k] = array[n];
array[n] = tmp;
}
}
关于C++ vector 随机洗牌它的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1667625/