0

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.

2 Answers2

0

Random generator doesn't mean unique generation, collisions can always happen especially when the number of generated values is high and the bounds or limits for the generation is small...

to avoid duplicated elements replace this array

int sym[k];

by a set which is a container that doesn't allow duplicate entries...

std::set<int>

after that, you need to replace the logic because looping k times does not mean having k elements in the set, so you need to do a while loop until the size of the set reaches the limit k

Edit:

if you need some unsorted generated values, the instead of using a set, consider implementing an unordered_set

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

I will use std::unordered_set to avoid duplicated

Patricio Rossi
  • 167
  • 2
  • 5