Reputation:
I need to find a function that works like this:
int[] matches = getAllPossibleCombinations(
int lengthOfEachIntReturnedInArray,
List<char> typesOfElementsUsedInCombinations);
input elements would be these (this is just an example):
int lengthofeachintreturnedinarray = (int) 2
List<char> typesofelementsusedincombinations = {a,b}
then the output would have to be (in a string array):
aa
ab
ba
bb
Each individual output element in the array must have a length defined by the first argument in the method (in this case 2) and must contain all possible combinations between the given letters in the second argument
I have seen something about powersets, should I use them, or should foreach
loops suit the job?
! the proposed question with answer above is NOT the same, it doesn't use set lenghts !
Upvotes: 2
Views: 367
Reputation: 149020
I'll direct you to Eric Lippert's article on implementing a Cartesian Product in Linq, which he writes as an extension method.
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct = new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] {item}));
}
Using this, you can implement your method like this:
static IEnumerable<string> GetAllPossibleCombinations(
int lengthofeachintreturnedinarray,
IEnumerable<string> typesofelementsusedincombinations)
{
return Enumerable
.Repeat(typesofelementsusedincombinations, lengthofeachintreturnedinarray)
.CartesianProduct()
.Select(strings => String.Concat(strings));
}
Upvotes: 2