需要递归生成文件数组的每个唯一组合
我研究并发现很多类似的请求,但没有一个完全符合我的需要。
这是我的问题。我正在使用 C# 工作,并且有一个 FileInfo[] 数组,其中包含未知数量的元素。
FileInfo[] files = new FileInfo[]
{
new FileInfo(@"C:\a.jpg"),
new FileInfo(@"C:\b.jpg"),
new FileInfo(@"C:\c.jpg"),
new FileInfo(@"C:\d.jpg"),
new FileInfo(@"C:\e.jpg"),
new FileInfo(@"C:\f.jpg"),
new FileInfo(@"C:\g.jpg"),
new FileInfo(@"C:\h.jpg"),
new FileInfo(@"C:\i.jpg"),
}; // Using 9 elements for this example
我需要生成这些文件的每种可能的重新排序组合的列表,而不重复这些文件。
因此,我的一些结果将是这样的(示例不是代码格式):
a, b, c, d, e, f, g, h, i
a, b, c, d, e, f, g, i, h // i & h switched
a, b, c, d, e, f, h, g, i // last 3 elements switched
a, a, b, b, c, c, d, d, e // THIS IS NOT ACCEPTED, because elements are duplicated
依此类推,直到我想出每种可能的组合
所以结果总数应该是中元素数量的阶乘大批。在这个例子中,有9个元素,所以应该有9*8*7*6*5*4*3*2*1=362,880种可能的组合。
我已经把这个问题搞乱了好几天了,但我就是无法集中注意力。感谢任何帮助,尤其是代码示例!
谢谢!
I've researched and found LOTS of similar requests, but nothing was quite what I needed.
Here is my problem. I'm working in C#, and I have a FileInfo[] array with an unknown number of elements in it.
FileInfo[] files = new FileInfo[]
{
new FileInfo(@"C:\a.jpg"),
new FileInfo(@"C:\b.jpg"),
new FileInfo(@"C:\c.jpg"),
new FileInfo(@"C:\d.jpg"),
new FileInfo(@"C:\e.jpg"),
new FileInfo(@"C:\f.jpg"),
new FileInfo(@"C:\g.jpg"),
new FileInfo(@"C:\h.jpg"),
new FileInfo(@"C:\i.jpg"),
}; // Using 9 elements for this example
And I need to generate a list of every possible reorder combination of these files, without repeating the files.
So, some of my results would be like this (example is not in code format):
a, b, c, d, e, f, g, h, i
a, b, c, d, e, f, g, i, h // i & h switched
a, b, c, d, e, f, h, g, i // last 3 elements switched
a, a, b, b, c, c, d, d, e // THIS IS NOT ACCEPTED, because elements are duplicated
And so on, until I've come up with every possible combination
So the total number of results should be the factorial of the number of elements in the array. In this example, there are 9 elements, so there should be 9*8*7*6*5*4*3*2*1=362,880 possible combinations.
I've been messing with this for a couple days now, and I just can't wrap my mind around it. Any help is appreciated, especially with code examples!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 Linq 很容易:
编辑:
这是一个通用解决方案,适用于任意数量的项目:
按如下方式使用它:(
此解决方案的灵感来自 Eric Lippert 关于笛卡尔积的文章。)
编辑 2:
这是使用
Aggregate:
Easy with Linq:
EDIT:
Here's a generic solution, for any number of items:
Use it as follows:
(This solution is inspired by Eric Lippert's article about cartesian products.)
EDIT 2:
Here's a variant using
Aggregate
:有多种算法可用于执行此操作。下面的页面列出了 3 个不同的:
There are various algorithms available for doing this. The page below lists 3 different ones:
您确实想要该集合的所有排列。
编辑:这里是您正在谈论的内容的示例: http://www.codeproject.com/KB/recipes/Premutations.aspx
You really want all the Permutations of the set.
Edit: here is an example of exactly what you are talking about: http://www.codeproject.com/KB/recipes/Premutations.aspx