Random array generation with no duplicates

前端 未结 9 905
無奈伤痛
無奈伤痛 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 13:12

    If you want to pseudo-randomly traverse a large space without maintaining visited indices, you should look at this project I contributed to years ago for the basic technique. http://packetfactory.openwall.net/projects/ipspace/index.html

    You should be able to adapt it to your purposes, source is at the bottom of the page.

    0 讨论(0)
  • 2020-11-28 13:13

    You start off filling a container with consecutive elements beginning at 0

    std::iota(begin(vec), end(vec), 0);

    then you get yourself a decent random number generator and seed it properly

    std::mt19937 rng(std::random_device{}());

    finally you shuffle the elements using the rng

    std::shuffle(begin(vec), end(vec), rng);

    live on coliru


    On some implementations random_device doesn’t work properly (most notably gcc on windows) and you have to use an alternative seed, i.e. the current time → chrono.

    0 讨论(0)
  • srand(time(NULL));
    const int N = 4;
    int numbers [N];
    
    bool isAlreadyAdded(int value, int index)
    {
         for( int i = 0; i < index; i ++)
              if( numbers[i] == value)
                  return true;
         return false;
    }
    for (int x=0; x!=N;x++)
    {
        int tmp = 1 + (rand() % N) ;
        while( x !=0 && isAlreadyAdded(tmp, x))
               tmp = 1 + (rand() % N) ;
    
        numbers[x] = tmp;
        printf("%d ", numbers[x]);
    }
    

    It's just a way. it should work, of course there are better ways

    0 讨论(0)
提交回复
热议问题