Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

arrays - C++ No-repeat random number generator

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 working when I put n=32769 in console program stop working. When i put number in range 0-32768 it's works. Any idea what is wrong in this code? While compilation i had no errors/warnings.

#include <stdio.h>
#include <iostream>
#include <ctime>


int main()
{
    clock_t start = clock();
    int n;
    std::cout << "n:";
    std::cin >> n;
    bool *used_numbers = new bool[n];
    memset(used_numbers, false, sizeof(used_numbers[0]) * n);
    int *permutation = new int[n];
    srand(unsigned(std::time(NULL)));
     int rnd_number;



    for (int i = 0; i < n; i++)
    {
        rnd_number = rand() % n;
        if (!used_numbers[rnd_number])
        {
            permutation[i] = rnd_number;
            used_numbers[rnd_number] = true;
        }
        else
            i--;
    }
    std::cout << "Permutation: 
 ";
    for (int k = 0; k < n; k++)
    {
        std::cout << permutation[k] << " ";
    }
    std::cout << std::endl;

    printf("[Debug]: %lu ms
", clock() - start);




    getchar();
    system("pause");
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
rand() % n

will never give you a number larger than RAND_MAX. RAND_MAX is the range of the numbers generated by rand().

If you use a value of n larger than RAND_MAX, you will loop forever after you draw the first RAND_MAX numbers. Simply, there's no numbers left to draw.

You need to improve your solution to be able to generate larger numbers, or use something better like shuffling a larger list of numbers.

Your algorithm has many issues, but an immediate simple fix would be:

rnd_number = (rand() * (RAND_MAX + 1) + rand()) % n;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...