How to generate an array of 256 distinct numbers

前端 未结 4 566
遇见更好的自我
遇见更好的自我 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 <stdlib.h>
    #include <time.h>
    
    #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;
    }
    
    0 讨论(0)
  • 2021-01-27 03:54
    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    int main(int argc, const char * argv[])
    {
        std::vector<int> items(256);
    
        std::iota(items.begin(),items.end(),0);
    
        std::random_shuffle(items.begin(), items.end());
    
        for(auto i:items)
            std::cout<<i<<"  ";
    }
    
    0 讨论(0)
  • 2021-01-27 04:01

    As others mentioned, use std::random_shuffle:

    std::vector<int> my_vec(256); //Reserve space for 256 numbers in advance.
    
    for(int n = 0; n < 256; ++n)
    {
      my_vec.push_back(n);
    }
    
    std::random_shuffle(my_vec.begin(), my_vec.end());
    
    0 讨论(0)
  • 2021-01-27 04:03

    You could try something like this:

    int main()
    {
        std::vector<int> available(256);
        int a[256];
    
        for (int i = 0; i < 256; ++i)
            available.push_back(i);
    
        for (int i = 0; i < 256; ++i)
        {
            int idx = rand() % available.size();
            a[i] = available[idx];
            available.erase(available.begin()+idx);
        }
    
        // use a[] as needed...
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题