How to generate an array of 256 distinct numbers

前端 未结 4 624
遇见更好的自我
遇见更好的自我 2021-01-27 03:34

I have this:

#include     
using namespace std;   
int main()
{
    int a[256];
    int b;
    int k;
    for (int i = 0; i < 256; i ++){
             


        
4条回答
  •  不知归路
    2021-01-27 03:54

    std::random_shuffle is the way to go, as previously mentioned, but just in case you don't want to use it (maybe using ANSI C instead of C++), here's a quick-and-dirty implementation:

    #include 
    #include 
    
    #define SIZE 256
    
    static inline void
    swap(int *a, int *b) {
        // Don't swap them if they happen to be the same element 
        // in the array, otherwise it'd be zeroed out
        if (a != b) {
            *a ^= *b;
            *b ^= *a;
            *a ^= *b;
        }
    }
    
    int main(void)
    {
        int A[SIZE], i;
        // Initialize array with sequential incrementing numbers
        for (i = 0; i < SIZE; ++i)
            A[i] = i;
    
        // Initialize random seed
        srand(time(NULL));
    
        // Swap every element of the array with another random element
        for (i = 0; i < SIZE; ++i)
            swap(&A[i], &A[rand() % SIZE]);
    
        return 0;
    }
    

提交回复
热议问题