如何随机打乱向量中的元素 [英] How to shuffle elements in a vector randomly

查看:44
本文介绍了如何随机打乱向量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成一项需要满足以下条件的作业:

I'm trying to do an assignment which requires the following to happen:

  1. 请求所需的元素数 n.
  2. 用元素 0, 1, 2, ..., n – 1 填充一个向量并将其显示到控制台.
  3. 随机排列元素并将新排列显示到控制台.

我有输入向量,但我不知道如何打乱向量.

I have the inputting the vector, but I cannot figure out how to shuffle the vector.

注意:我不能使用 random_shuffle 函数或任何函数(除了 .swap() 或这里的索引)所以不要说要这样做.

Note: I can't use the random_shuffle function or any functions (besides .swap() or indexing in this) so don't say to do that.

到目前为止我所拥有的是

What I have so far is

#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>

using namespace std;

int main() {
    srand(time(NULL));
    vector<int> elements;
    int sizeOfVector;
    // size of the vector
    cout << "Please enter the size of the vector: " << endl;
    cin >> sizeOfVector;
    cout << "This is your vector:" << endl;
    // Output each element in the vector
    for (int i = 0; i < sizeOfVector; ++i) {
        elements.push_back(i);
        cout << i << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}

是的,再次,我似乎无法得到的是如何在不使用 random_shuffle 函数的情况下在不同位置打乱元素

So yeah, again, what I can't seem to get is how to shuffle the elements around in different positions WITHOUT using the random_shuffle function

我尝试过使用 Fisher-Yates shuffle,但是它只是重复向量:

I've tried using the Fisher-Yates shuffle, but it just repeats the vector:

for (int k = 0; k < sizeOfVector; k++)
{
    int r = rand() % sizeOfVector;
    swap(elements[k], elements[r]);
    cout << k << " ";
}

更新感谢修复它的用户 Danvil.

Update Thanks to user Danvil, who fixed it.

// first shuffle
for (int k = 0; k < sizeOfVector; k++) {
    int r = k + rand() % (sizeOfVector - k); // careful here!
    swap(elements[k], elements[r]);
}

// THEN print
for (int k = 0; k < sizeOfVector; k++) {
    cout << elements[k] << " ";
}

推荐答案

使用中定义的std::random_shuffle.请参阅此处.

Use std::random_shuffle defined in <algorithm>. See here.

你为什么不想使用这个功能?您的替代方法是复制它的源代码并将函数命名为 my_random_shuffle - 但这显然很愚蠢.

Why would you not want to use this function? Your alternative is copy it's source code and name the function my_random_shuffle - but this is obviously silly.

顺便说一下,该算法称为 Fisher-Yates shuffle.

By the way, the algorithm is called Fisher-Yates shuffle.

更新:你的算法实现基本正确,但你需要这样做:

Update: Your implementation of the algorithm is basically correct, but you need to do it like this:

// first shuffle
for (int k = 0; k < sizeOfVector; k++) {
    int r = k + rand() % (sizeOfVector - k); // careful here!
    swap(elements[k], elements[r]);
}

// THEN print
for (int k = 0; k < sizeOfVector; k++) {
    cout << elements[k] << " ";
}

这篇关于如何随机打乱向量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆