lundi 10 avril 2017

Generating unique random characters and saving them in array

I want to generate random numbers and save them in an array. that' all ! but here is the point, I want to avoid duplicating and not having a number two or more times in array.

my code :

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
    int k, temp;

    cin >> k;

    int sym[k];

    srand(time(NULL));

    for (int i = 0; i < k; i++)
    {
        temp = rand() % 25 + 97;

        for(int j=0; j<i; j++)
        {
            while(temp == sym[j])
            {
                temp = rand() % 25 + 97; // 25 means a and 122 means z
            }
        }

        sym[i] = temp;

    }

    for(int i=0; i<k; i++)
    {
        cout << sym[i] << endl;
    }
    return 0;
}

I still get duplicated results.




Aucun commentaire:

Enregistrer un commentaire