JohnTargaryen / Learning-C-

1 stars 0 forks source link

Data Structure and Logic Design #2

Open JohnTargaryen opened 8 years ago

JohnTargaryen commented 8 years ago

Magic Square

  1. way to construct a 2D array whose size is unkown and needs user's input;
无法声明一个不定大小的二维数组,不过可以用二级指针来模拟(我想你清楚数组和指针的区别吧)
int **A;        //声明二级指针A,指向一个指针数组(切记不是指向一个二维数组)

cin >> M >> N;        //输入两个维度
A = new int *[M];        //开辟指针数组
for(i=0; i<M; i++)
        A[i] = new int[N];
这样以后使用A[i][j]就像二维数组一样

source : http://zhidao.baidu.com/link?url=tMIXMu1qlHPbu2hcQXox7SEnZzVorTJgJg4gaaQcFC_4MhiU3M_11rwGVvIHp_gluDRVGqFBCTEfk1ivKpQDGK

JohnTargaryen commented 8 years ago

Rand()

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;

Repeatability


srand()

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();