C#中的具体组合,无法掌握
我最近一直在研究组合,尝试了各种第三方解决方案,并尝试自己解决它。如果没有成功我可能会补充。
我需要生成一个 13 长度的字符串,其中包含所有可能的组合。.. int 0-2,IE
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 1 0
...
2 2 2 2 2 2 2 2 2 2 2 2 2
您可能会明白,我知道如果我想要一个肮脏的解决方案,我可以将其包装在循环中。任何指导或指示表示赞赏。
I've been looking into combinations lately, I've tried various 3rd party solutions, and tried to get my head around it myself. Without success I might add.
I need to generate a 13 length string with all possible combinations of say.. int 0-2, I.E
0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 2
0 0 0 0 0 0 0 0 0 0 0 1 0
...
2 2 2 2 2 2 2 2 2 2 2 2 2
You probably get the drill, I'm aware I could just wrap this up in loops if I wanted a dirty solution. Any guidance or pointers are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我很乐意为您编写代码,但您似乎正在寻找对问题的直觉。所以也许这感觉更像是一个“授人以鱼”的时刻。
那么让我问你几个问题:
让我们将问题推广到长度为 N 的字符串。N=1 的情况是什么样的? ?
N=2 的情况是什么样的 我
想知道您是否能看到,在给定 N=1 的情况下,我们如何以非常机械的方式轻松导出(也称为生成)N=2 的情况。现在,如果您看到此特定情况的模式,您能说出一般情况的模式是什么吗?即,如果你手里已经有长度为 N 的字符串的答案,并且我要求你向我提供长度为 N+1 的字符串的答案,你可以这样做吗?如果是这样,您就拥有了递归算法的定义。
PS 我想我会称这些组合而不是排列。
I'd be happy to write the code for you, but it seems like you are looking for intuition into the problem. So maybe this feels more like a "teach a man to fish" moment.
So let me ask you a few questions:
Let's generalize the problem to strings of length N. What does the N=1 case look like? It's
And what does the N=2 case look like? It's
I wonder if you can see how, given the N=1 case, we can easily derive (aka generate) the N=2 case in a very mechanical fashion. Now if you see the pattern for this specific case, can you say what the pattern is for the general case? i.e. If you happened to already have in your hand the answer for strings of length N, and I asked you to provide me with the answer for strings of length N+1 could you do so? If so you have the very definition of a recursive algorithm.
PS I think I'd call these combinations rather than permutations.
我忍不住认为这只是在基于 N 的数字系统(在您的示例中是 3 基系统)中添加数字。
我会编写一种允许您切换基础的方法(如果框架或库中尚未存在)。 IE:
然后只需编写一个 for 循环(抱歉,类伪 C 代码:)):
好的,希望对您有所帮助或给您一个如何解决它的想法:)
I can't help thinking of this as just adding number in a N-based numeric system (in your example a 3-base system).
I would write one method (if not already there in the framework or a library) that would allow you to switch bases. I.E:
then just write a for loop (sorry, pseudo-c-like-code :) ):
Ok, hope that helps or give you an idea on how to solve it :)
我已经编写了返回排列列表的快速函数,因此如果您没有时间编写自己的方法,可以使用它。 length 是排列长度,max 是最大数(在你的情况下,它将是 2)
I've written quickly function that returns list of permutations, so if you have not time to write your own method, you can use it. length is permutation length, max is maximum number (in your case, it would be 2)