首页 > 解决方案 > C++ 中的洗牌向量

问题描述

我正在开发一个程序,该程序将初始向量作为 inpit。该向量的大小为 20。然后程序从该向量生成 10 个随机向量。为此,我在初始向量中选择 2 个赎金索引并将它们交换彼此生成一个新向量。这样做是为了生成所有 10 个新向量。生成的10个新向量应该存储在下面的二维向量中

vector<vector<int>> allparents

我已经能够使用 srand() 函数生成 2 个随机索引数,然后将这些索引处的元素交换为初始向量。但是我无法生成 10 个这样的随机父项,然后将它们存储在 allparents 2D 向量中。我的代码如下:

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

using namespace std;

int main () {
    srand(time(NULL));
    int i1=(rand()%19+1);
    int i2=(rand()%19+1);
    cout<<i1<<endl;
    cout<<i2<<endl;

    vector<int> initial={71,127,428,475,164,253,229,395,92,189,41,110,443,490,278,305,28,58,371,560};

    vector<vector<int>> allparents;
    for(int r=0;r<10;r++){
        for(int c=0;c<20;c++){
            swap(initial[i1],initial[i2]);
            allparents[r][c]=initial[c];
            cout<<allparents[r][c]<" "<<endl;
         }
    }
    return 0;
}

由于我是向量的新手,我会在这个程序中请求你的帮助。谢谢。

标签: c++arraysvectorrandom

解决方案


首先,我不会说你在“生成随机向量”,你只是在打乱一个预定义的向量。其次,我建议创建小的工作函数并用这些函数组装你的程序:

vector<int> shuffle(vector<int> v) {
    // Use the implementation you want here, I will use a std algorithm
    static auto rng = std::default_random_engine {};
    std::shuffle(std::begin(v), std::end(v), rng);
    return v; // this is a copy of the vector
}

int main() {
    vector<int> initial= {
       71,127,428,475,164,253,229,395,92,189,41,110,443,490,278,305,28,58,371,560
    };

    // Generate 10 shuffled vectors
    vector<vector<int>> shuffledVectors;
    for (int i = 0; i < 10; i++) {
        vector<int> shuffled = shuffle(initial);
        shuffledVectors.push_back(shuffled);
    }

    // Print them
    for (vector<int>& v : shuffledVectors) {
        for (int& i : v)
           cout << i << " ";
        cout << endl;
    }
    return 0;
}

输出:

164 41 110 305 278 28 58 127 229 189 475 395 560 428 71 443 253 371 490 92 
490 71 305 58 428 127 28 110 92 443 189 229 278 475 371 395 560 41 253 164 
395 278 560 490 28 164 71 229 58 41 428 305 127 253 475 371 92 189 110 443 
164 475 92 253 229 189 127 560 71 58 41 443 428 395 371 490 110 278 28 305 
443 253 428 110 278 71 475 127 58 41 371 229 305 189 395 164 28 490 92 560 
560 28 58 71 229 41 490 475 189 443 253 395 305 164 371 278 428 92 110 127 
395 443 371 58 253 305 92 127 475 110 428 229 189 41 164 278 71 560 28 490 
278 189 71 127 443 110 28 428 305 560 371 58 229 253 395 164 41 490 475 92 
28 395 92 443 560 278 371 71 58 305 475 253 428 490 229 189 164 110 41 127 
443 71 428 229 127 278 490 58 475 253 164 110 92 189 395 560 305 41 28 371

推荐阅读