任意数字计数器

Emr*_*ici 0 c algorithm counter state-machine

我需要一个计数器algortihm,它使用任意给定的数字进行计数.

我的代码与此类似:

static char digits[] = {'x','y','z'}; /* Arbitrary number of arbitrary digits. */
int i;
for(i=0; i<100; i++) {
    printf("%s\n", get_next());
}
Run Code Online (Sandbox Code Playgroud)

我的预期产量:

x
y
z
yx
yy
yz
zx
zy
zz
yxx
yxy
yxz
yyx
yyy
yyz
yzx
yzy
yzz
zxx
... and so on
Run Code Online (Sandbox Code Playgroud)

如你所见,我需要算法来实现get_next()函数,所以使用C语言不是重点.

编辑我以澄清目的:

我的get_next()函数可能与此类似:

char get_next() {
    static previous = digits[0];
    char *next_number;

    /* do something here using previous and digits[] */

    return next_number;
}
Run Code Online (Sandbox Code Playgroud)

请注意,使用get_next(void)next(previous_number)next(digits, previous_number)原型的功能,产生下一个数字是不是对我很重要.

编辑II以澄清目的:

从上面的简单示例来看,我的真实场景更复杂,我需要一个可以使用任意数量任意数字的通用解决方案.

数字输入示例:

static char digits[] = {'a', 'b', 'c', ... 'z', '0', '1', ...}; /* Lots of digits */
static char digits[] = {'s','t','a','c','k','o','v','e','r'};   /* Arbitrary sequence */
Run Code Online (Sandbox Code Playgroud)

R S*_*hko 5

这很简单.您希望转换为base digit_count,然后将数字转换为数字,而不是将数字转换为数组.

要转换为任意基数,您需要除法和余数.

这是一个比我以前使用的更好的版本,因为它实际上创建了一个缓冲区(而不是打印出来),为迭代删除了递归,而是在C而不是我以前的C/Python大杂烩.

因为它使用静态缓冲区,所以代码不是线程安全的.另请注意,如果数字太大,则没有错误检查代码不会使缓冲区下溢.最后,它使用了从结尾到前面构建字符串并返回指向缓冲区中间的指针的技巧,因此它不必反转结尾处的数字.

char *getnum(int x)
{
    static char buffer[1024];
    int idx = 1024;

    buffer[--idx] = '\0';

    if (x == 0)
        buffer[--idx] = digits[0];
    else
    {
        while (x != 0)
        {
            buffer[--idx] = digits[x % digit_count];
            x /= digit_count;
        }
    }    

    return buffer + idx;
}
Run Code Online (Sandbox Code Playgroud)