NotALolicon
NotALolicon

Reputation: 31

How to generate a list of shuffled arrays from a given array?

I look to the internet for this issue and found that I can use the random_shuffle function from <algorithm> header. My following code:

void Localization::generate_population(){
    int* ptr = new int[size];
    for(int i{}; i < size; ++i) ptr[i] = i;

    for(int i{}; i < size; ++i) {
        std::random_shuffle(ptr, ptr + size);
        population[i] = ptr;
    }
}

This is my class function which is automatically called in the constructor. I'd ran the program and end up with the same shuffled arrays. The internet told me that I forgot to add std::srand(std::time(0)) at the beginning of my program, so I did just that:

I'd removed some code to make it easier to read. Hopefully it is still understandable.

int main(int argc, char **argv){
    std::srand(std::time(0));

    Localization* gps = new Localization(array_here);
    delete gps;
}

However, when I build and ran my program I get a similar result:

[ INFO] [1630975155.983523195]: 0: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.983979451]: 1: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.983990418]: 2: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.983996142]: 3: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.984001312]: 4: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.984006477]: 5: [2, 4, 6, 0, 5, 1, 3]
[ INFO] [1630975155.984013677]: 6: [2, 4, 6, 0, 5, 1, 3]

Not exactly sure how std::srand(std::time(0)) works, but maybe it is because the for loop ran too fast for the std::srand(std::time(0)) to take any effect. Is there a better way to shuffle the array in my situation?

Edited code (worked but not sure if it is efficient):

#include <iostream>
#include <algorithm>
#include <iterator>
#include <random>

int main(){
    int size {5};
    int** a2d = new int*[size]; 
    int* ptr = new int[size];
    for(int i{}; i < size; ++i) ptr[i] = i;

    std::random_device rd;
    std::default_random_engine dre{ rd() }; 
    for(int i{}; i < size; ++i){
        int* another = new int[size];
        std::copy(ptr, ptr + size, another);
        std::shuffle(another, another + size, dre);
        a2d[i] = another;
        std::copy(another, another + size, ptr);
    }
    delete ptr;

    for(int i{}; i < size; ++i){
        printf("%d: %d, %d, %d, %d, %d\n", i, a2d[i][0], a2d[i][1], a2d[i][2], a2d[i][3], a2d[i][4]);
    }
}

Output:

0: 3, 2, 4, 0, 1
1: 0, 1, 3, 4, 2
2: 4, 3, 1, 2, 0
3: 3, 2, 0, 1, 4
4: 0, 4, 2, 1, 3

Upvotes: 1

Views: 118

Answers (1)

fortytoo
fortytoo

Reputation: 462

As @cigien commented, random_shuffle has been deprecated. You can use the standard "shuffle" function which shuffles all the elements of a given container.

std::random_device rd;
std::default_random_engine dre{ rd() }; // seed RNG

std::shuffle(std::begin(myContainer), std::end(myContainer), dre);

Upvotes: 2

Related Questions