gpt4 book ai didi

c# - 寻找可能的组合 linq

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

我需要在 {"a", "b","c"} 之间生成所有可能的组合。

例如,输入集如 {"a", "b","c"},预期输出为 {"a", "b", "c"“ab”、“ac”、“bc”、“abc”

最佳答案

听起来您要找的基本上是 power set 的一种形式.这是一个简单的实现(取自 this site ):

public IEnumerable<IEnumerable<T>> GetPowerSet<T>(this IList<T> list)
{
return from m in Enumerable.Range(0, 1 << list.Count)
select
from i in Enumerable.Range(0, list.Count)
where (m & (1 << i)) != 0
select list[i];
}

请注意,感谢 <<运算符,您将无法将此方法用于包含超过 30 个元素的列表。无论如何,我不建议尝试使用包含接近那么多元素的列表,因为在 30 个元素时,结果集将包含 230 或 1073741824 个元素。

你可以使用这个方法得到你想要的结果

public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet()
select string.Concat(s);
}

但是,因为幂集包含空集,所以这实际上会返回结果 {"", "a", "b", "c", "ab", "ac", "bc", "abc"} .要过滤掉空字符串,请使用:

public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet()
let str = string.Concat(s)
where str.Length > 0 // exclude null set result
select str;
}

或者更简单地说:

public IEnumerable<string> GetPermutations(IList<string> strings)
{
return from s in strings.GetPowerSet().Skip(1)
select string.Concat(s);
}

关于c# - 寻找可能的组合 linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470672/

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