C++ No-repeat random number generator

前端 未结 3 1745
慢半拍i
慢半拍i 2020-12-12 05:38

I need to create algorithm implementation in C++ to generate random numbers to f.e table without repeat and list.

I created something code like that but it\'s stop w

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 06:35

    If you need to generate a sequence of non-crypto-safe numbers without a repeat then you can utilize Linear-feedback shift register. Example generation 65535 items (adopted from Wiki):

    #include 
    #include 
    #include 
    #include 
    
    int main(void)
    {
        // Any nonzero start state will work.
        const ::std::uint16_t start_state{0xACE1u};
        ::std::uint16_t lfsr{start_state};
        ::std::uint64_t period{0};
    #ifndef NDEBUG
        ::std::set<::std::uint16_t> used_items{};
    #endif // #ifndef NDEBUG
        do
        {
            // Get LSB (i.e., the output bit).
            bool lsb{0 != (lfsr & 1)};
            // Shift register
            lfsr >>= 1;
            // If the output bit is 1, apply toggle mask.
            if(lsb)
            {
                lfsr ^= 0xB400u;
            }
            // verify that current value has never appeared before
            assert(used_items.emplace(lfsr).second);
            std::cout << lfsr << "\n";
            ++period;
        }
        while(lfsr != start_state);
        ::std::cout << "period " << period << "\n";
        ::std::cout.flush();
        return 0;
    }
    

提交回复
热议问题