Vector & Permutations (Homework Help)

Hi, I searched and found similar topics but nothing seemed to help with exactly what I need. The question is:
- Write a program that produces ten random permutations of the numbers 1 to 10. To generate a random permutation, you need to fill a vector with the numbers 1 to 10 so that no two entries of the vector have the same contents. You could do it by brute force, by calling rand_int until it produces a value that is not yet in the vector. Instead, you should implement a smart method.
- Make a second array and fill it with the numbers 1 to 10. Then pick one of those at random, remove it, and append it to the permutation vector.
- Repeat ten times.
Any help would be greatly appreciated

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <cstdlib>

using namespace std;

int main()
{
    vector <int> perm[10];
    vector <int> nums[10];

    for (int count=1; count<11; count++);
    {
        nums[count-1]=count;
    }

    while (num.size>0)
    {
        int randNum=1+rand()%10;
        perm[num.size-1]=nums[randNum]
        nums.pop_back();
    }

    cout<<perm[]<<;
}
Last edited on
Standard library example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>


int main()
{
    std::vector<std::vector<int>> perm(10, {1, 2, 3, 4, 5 ,6 ,7 ,8 ,9, 10});
    for(auto& v: perm)
        std::random_shuffle(v.begin(), v.end());
    for(const auto& v: perm) {
        for(const auto& i: v)
            std::cout << std::setw(3) << i;
        std::cout << '\n';
    }
}

Your way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iomanip>
#include <iostream>
#include <vector>

std::vector<int> getPerm()
{
    std::vector<int> values {1, 2, 3, 4, 5 ,6 ,7 ,8 ,9, 10};
    std::vector<int> result;
    while(!values.empty()) {
        auto index = rand() % values.size();
        result.push_back(values[index]);
        values.erase(values.begin() + index);
    }
    return result;
}


int main()
{
    std::vector<std::vector<int>> perm(10);
    for(auto& v: perm)
        v = getPerm();
    for(const auto& v: perm) {
        for(const auto& i: v)
            std::cout << std::setw(3) << i;
        std::cout << '\n';
    }
}
Topic archived. No new replies allowed.