{"a", "b","c"}
사이의 모든 가능한 조합을 생성해야합니다.가능한 조합 찾기 linq
예를 들어 입력 집합은 {"a", "b","c"}
이고 예상 출력은 {"a", "b", "c" "ab", "ac", "bc", "abc"}
입니다.
{"a", "b","c"}
사이의 모든 가능한 조합을 생성해야합니다.가능한 조합 찾기 linq
예를 들어 입력 집합은 {"a", "b","c"}
이고 예상 출력은 {"a", "b", "c" "ab", "ac", "bc", "abc"}
입니다.
당신이 찾고있는 것처럼 들리는 것은 기본적으로 power set의 형식입니다. <<
운영자 덕분에, 당신은 30 개 이상의 요소가 목록에이 방법을 사용할 수 없게됩니다
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];
}
참고 : 여기에 (this site에서 가져온) 간단한 구현입니다. 30 개 요소에서 결과 집합에 2 또는 1073741824 요소가 포함될 것이므로 어쨌든 많은 요소에 가까운 목록으로 시도하지 않는 것이 좋습니다. 전원 세트가 널 (null) 세트가 포함되어 있기 때문에
당신은, 당신은 그러나이
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);
}
당신은 지금까지 시도 무엇? - 이것은 Linq가 굉장히 적합한 문제는 아닌 것처럼 보입니다. 일반 오래된 반복은 갈 길입니다. – ColinE
글쎄, 나는 Eric Lippert의 [Cartesian product] (http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx)를 사용해 보았습니다. , 도움이되지 않습니다. – serene
제목을 편집했습니다. "[제목에"태그 "가 포함되어 있어야합니까?] (http://meta.stackexchange.com/questions/19190/)"합의가 "아니오, 그렇지 않아야합니다"로 표시되어야합니다. –