1

I am trying to write a c++ program to print a random 10 letter string from a-z (ascii code 97 to 122) with non-repetitive letters. I have written this code which sometimes runs perfectly but most of the times the while loop runs infinitely. Where's the problem?

(EDIT: setting flag=0 at the beginning of while fixes the problem)

void randomstring() {int i,j,flag=1; char x, s[20]=" "; srand(time(0)); for(i=0;i<10;i++) {flag=1; //ensure entry into while while(flag) {x=rand()%26+97; //get random letter from a-z for(j=0;j<10;j++) {if(x==s[j]) //match with existing letters flag=2; //if matched, try again } if(flag!=2) {s[i]=x; //if doesn't match, add to string flag=0; //exit while } } } cout<<s; } 
2

2 Answers 2

3

(Currently the loop will not terminate if a duplicate character is spotted.) But aside from this, the code is nasty for a couple of other reasons:

  1. You're assuming ASCII encoding which is not guaranteed by the standard.

  2. Sampling with replacement can cause problems with looping, and also can create statistical anomalies (although with a crude generator like rand() these will be no worse than the generator itself).

One solution is to write

char s[] = {'a', 'b', 'c', .../*ToDo - type out all the other letters*/, 'z'}

and shuffle this using

std::random_shuffle(std::begin(s), std::end(s)); 

and read out the first 10 elements of s.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please explain why loop doesn't terminate when duplicate is found?
1

Once the flag is set to 2, it is stuck. You should reset the flag to 1 inside the while loop.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.