2011-01-28 47 views
0
const int SIZE = 3; 
const char val[SIZE] = {'3', 'z', '7'}; 

const string& next(){ 
    static string ret = "0"; 
    static unsigned i = 0; 
    static unsigned j = 0; 
    s[j] = val[i]; 
    i++; 

    return ret; 

//... 
} 

每次下簡稱,我希望它返回下一個字符串鍵,如:c + +生成下一個關鍵

3 
z 
7 
33 
3z 
37 
z3 
zz 
z7 
73 
7z 
77 
333 
33z 
... 

VAL []可以是任何尺寸與任何值。我的實現是錯誤的和不完整的,我無法圍繞它進行思考。誰能幫忙?

回答

0

就圍繞它而言,你可以想象它會像增加一個數字一樣。增加最右邊的值,但如果超過最後值,則將其設置回第一個值並遞增下一列等,如有必要,在前面添加額外的值。

#include <iostream> 
#include <string> 

const int n = 3; 
const char val[n] = {'3', 'z', '7'}; 

const std::string& next() 
{ 
    static std::string ret; 
    if (ret.empty()) return ret = val[0]; 
    for (int i = ret.length() - 1; i >= 0; --i) 
     if (ret[i] == val[n - 1]) 
     { 
      // carry situation, reset this column & will increment next... 
      ret[i] = val[0]; 
     } 
     else 
     { 
      // found existing column with room to increment... 
      ret[i] = strchr(val, ret[i])[1]; 
      return ret; 
     } 

    return ret = val[0] + ret; // add an extra column at left... 
} 

int main() 
{ 
    for (int i = 0; i < 20; ++i) 
     std::cout << next() << ' '; 
    std::cout << '\n'; 
} 
1
const string& next(){ 
    static int pos = 1; 
    static string s; 
    s.clear(); 
    int n = pos++; 
    while (n){ 
     s += val[(n-1) % SIZE]; 
     // use s = val[(n-1] % SIZE] + s; for inverse order. 
     n = (n-1)/SIZE; 
    }; 
    return s; 
}; 
+0

這很煩人,因爲它很簡單並且工作正常(除了它是向後的),但我無法弄清楚爲什麼.. – kynnysmatto 2011-01-28 01:58:25

+0

@ kynnysmatto:檢查更新。 – ruslik 2011-01-28 02:03:39

0

你想在基地3格式的數字,爲您的數字不同尋常的符號。您可以使用itoa轉換爲基準3,然後通過將0更改爲3,1至z和2至7來修改該字符串。