2011-01-28 48 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来修改该字符串。