Random array generation with no duplicates

前端 未结 9 990
無奈伤痛
無奈伤痛 2020-11-28 12:48

I am trying to create something that generates a random array with no duplicate values. I\'ve already looked at other answers but none seem to help me understand. I cannot t

9条回答
  •  余生分开走
    2020-11-28 12:49

    In c++, all you need is:

    std::random_shuffle()
    

    http://www.cplusplus.com/reference/algorithm/random_shuffle/

    int numbers [4];
    
    for (int x=0; x!=4;x++)
    {
        numbers[x] = x;
    }
    
    std::random_shuffle(numbers, numbers +4);
    

    Update: OK, I had been thinking that a suitable map function could go from each index to a random number, but thinking again I realize that may be hard. The following should work:

        int size = 10;
        int range = 100;
    
        std::set sample;
    
        while(sample.size() != size)
            sample.insert(rand() % range); // Or whatever random source.
    
        std::vector result(sample.begin(), sample.end());
    
        std::random_shuffle ( result.begin(), result.end() );
    

提交回复
热议问题