0

I need to generate a code of specified length, and it has to be random and non repetitive, so far, I have the random string but it's repeating the letters

Here is my code;

#include <string>
#include <cstdlib>
#include <ctime>

class random_text_generator
{
public:
random_text_generator(const std::string& str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
: m_str(str)
{
    std::srand(std::time(0));
}   
std::string operator ()(std::size_t len = 1)
{
    std::string seq;
    std::size_t siz = m_str.size();
    if(siz)
        while(len--)
            seq.push_back(m_str[rand() % siz]);
    return seq;
}
private:        
std::string m_str;
};

#include <iostream>

int main(void)
{
using namespace std;
random_text_generator rtg;
for(size_t cnt = 0; cnt < 7; ++cnt)
  {
    cout << rtg(cnt) << endl;
  }
}

Again, this code generates the string but it repeats some letters, for example the output would look like this

**OUTPUT**
A K X K Y

See that the K is repeating.

Misbah Ali
  • 31
  • 1
  • 7

2 Answers2

2

You can use something like the following code. This generates a random permutation of the valid characters and then copies the first 6 characters of this permutation to a new string.

#include <random>
#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    const int max_len = 6;
    std::string valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    std::random_device rd;
    std::mt19937 g(rd());

    std::shuffle(valid_chars.begin(), valid_chars.end(), g);

    std::string rand_str(valid_chars.begin(), valid_chars.begin() + max_len);
    std::cout << rand_str;
    return 0;
}

live example

m.s.
  • 16,063
  • 7
  • 53
  • 88
-1

So this function that solved my problem

void foonkshun(){

char database[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K','L', 'M', 
'N', 'O','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

random_shuffle(database, database + 25);

for (int i = 1; i < 6; i++){
    cout << database[i];
   }
}

Thanks to Neil Kirk, Ed Heal, cad, Cornstalks. :D

Misbah Ali
  • 31
  • 1
  • 7