mardi 16 janvier 2018

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: \n ";
    for (int k = 0; k < n; k++)
    {
        std::cout << permutation[k] << " ";
    }
    std::cout << std::endl;

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




    getchar();
    system("pause");
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire