gpt4 book ai didi

c# - 需要递归地生成文件数组的每个唯一组合

转载 作者:行者123 更新时间:2023-11-30 20:11:24 25 4
gpt4 key购买 nike

我已经研究并发现了很多类似的请求,但没有一个是我需要的。

这是我的问题。我在 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种可能的组合。

这几天我一直在纠结这个问题,我就是无法全神贯注。感谢您提供任何帮助,尤其是代码示例!

谢谢!

最佳答案

使用 Linq 很容易:

IEnumerable<FileInfo[]> permutations =
from a in files
from b in files.Except(new[] { a })
from c in files.Except(new[] { a, b })
from d in files.Except(new[] { a, b, c })
from e in files.Except(new[] { a, b, c, d })
from f in files.Except(new[] { a, b, c, d, e })
from g in files.Except(new[] { a, b, c, d, e, f })
from h in files.Except(new[] { a, b, c, d, e, f, g })
from i in files.Except(new[] { a, b, c, d, e, f, g, h })
select new[] { a, b, c, d, e, f, g, h, i };

编辑:

这是一个通用的解决方案,适用于任意数量的项目:

static class ExtensionMethods
{
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> source, int count)
{
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
for (int i = 0; i < count; i++)
{
result =
from seq in result
from item in source.Except(seq)
select seq.Concat(new[] { item });
}
return result;
}
}

按如下方式使用:

IEnumerable<IEnumerable<FileInfo>> permutations = files.GetPermutations(9);

(此解决方案的灵感来自 Eric Lippert's article about cartesian products。)


编辑 2:

这是一个使用 Aggregate 的变体:

static class ExtensionMethods
{
public static IEnumerable<IEnumerable<T>> GetPermutations2<T>(this IEnumerable<T> source, int count)
{
IEnumerable<IEnumerable<T>> seed = new[] { Enumerable.Empty<T>() };
return Enumerable.Repeat(source, count)
.Aggregate(
seed,
(accumulator, sequence) =>
from acc in accumulator
from item in sequence.Except(acc)
select acc.Concat(new[] { item }));
}
}

关于c# - 需要递归地生成文件数组的每个唯一组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com