如何在 C 中通过重复生成所有可能的变化

发布于 2024-10-06 08:53:19 字数 267 浏览 0 评论 0原文

我正在寻找一种 C 语言算法来生成所有可能的变化,并从 n 个元素中重复设置长度。 例如,如果长度为 3 并且元素为: 1, 2。输出应为:

1 1 1

1 1 0

1 0 0

1 0 1

0 0 0

0 0 1

0 1 1

0 1 0

我已经查找过这里有解决方案,但我能找到的都是Java或Python的实现,我不知道如何将它们重写为C。有人可以在这里发布这个问题的C代码吗?

I'm looking for an algorithm in C to generate all possible variations with repetitions for set length and from n elements.
For example, if the length is 3 and the elements are: 1, 2. The output should be :

1 1 1

1 1 0

1 0 0

1 0 1

0 0 0

0 0 1

0 1 1

0 1 0

I already looked for the solutions here, but all I could find were implementations in Java or Python and I don't know how to rewrite them to C. Can somebody please post a C code for this problem here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情感失落者 2024-10-13 08:53:19
void g(int l,int v,char *c)
{
    int i=v;
    if (l--==0) 
        puts(c);
    else 
        while(i)
            g(l,(c[l]='0'+--i,v),c);
}

void f(int l,int v)
{
    char c[l+2];
    g(((c[l]=13,c[l+1]=0),l),v,c);
}

int main()
{
    f(3,2);
    return 0;
}

测试,有效!,更新以修复可读性问题

void g(int l,int v,char *c)
{
    int i=v;
    if (l--==0) 
        puts(c);
    else 
        while(i)
            g(l,(c[l]='0'+--i,v),c);
}

void f(int l,int v)
{
    char c[l+2];
    g(((c[l]=13,c[l+1]=0),l),v,c);
}

int main()
{
    f(3,2);
    return 0;
}

Tested, works!, updated to fix readability issue

绝對不後悔。 2024-10-13 08:53:19

它只不过是在基数 B 中生成长度为 N 的所有数字(在您的情况下,N 是 3,B 是 2)。

It's nothing else than generating all the numbers of length N in base B (in your case N is 3 and B is 2).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文