Open JohnTargaryen opened 8 years ago
int i = rand() % n; // i is a random number range from 0 to n;
string random() {
string RandomStr;
char ch;
int i;
while (RandomStr.length() < 9) {
bool flag1 = true;
i = rand() % 9;
ch = (i + 1) +'0';
for (int i = 0; i < RandomStr.length(); i++) {
if (RandomStr[i] == ch) {
flag1 = false;
continue;
}
}if (flag1 == true)
RandomStr += ch;
}
return RandomStr;
}
The function that i wrote above is supposed to generate random string that contains unrepeated numbers from 1 to 9. However, everytime i run the program it returns the same string 698524137;
Function srand() takes an unsigned int argument and seeds function rand to produce a different sequence of random numbers for each execution of the prpgram;
Therefore, my function string random() can be altered into
string random(int seed) {
srand(seed); // added
string RandomStr;
char ch;
int i;
while (RandomStr.length() < 9) {
bool flag1 = true;
i = rand() % 9;
ch = (i + 1) +'0';
for (int i = 0; i < RandomStr.length(); i++) {
if (RandomStr[i] == ch) {
flag1 = false;
continue;
}
}
if (flag1 == true)
RandomStr += ch;
}
return RandomStr;
}
With diffent seed provided for srand() ,the function rand() will generate different random numbers, and with the same seed, of course, you can get the same sequence generated by rand();
Magic Square
source : http://zhidao.baidu.com/link?url=tMIXMu1qlHPbu2hcQXox7SEnZzVorTJgJg4gaaQcFC_4MhiU3M_11rwGVvIHp_gluDRVGqFBCTEfk1ivKpQDGK