lundi 6 septembre 2021

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:

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)). Is there a better way to shuffle the array in my situation?




Aucun commentaire:

Enregistrer un commentaire