Skip to content

Instantly share code, notes, and snippets.

@fdeitelhoff
Created February 27, 2013 22:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdeitelhoff/5052611 to your computer and use it in GitHub Desktop.
Save fdeitelhoff/5052611 to your computer and use it in GitHub Desktop.
C# implementation for a combination with repetition. Implemented as an extension method for IEnumerable<char>.
public static IEnumerable<IList<char>> CombineWithRepetitions(this IEnumerable<char> input, int take)
{
ICollection<IList<char>> output = new Collection<IList<char>>();
IList<char> item = new char[take];
CombineWithRepetitions(output, input, item, 0);
return output;
}
private static void CombineWithRepetitions(ICollection<IList<char>> output, IEnumerable<char> input, IList<char> item, int count)
{
if (count < item.Count)
{
var enumerable = input as IList<char> ?? input.ToList();
foreach (var symbol in enumerable)
{
item[count] = symbol;
CombineWithRepetitions(output, enumerable, item, count + 1);
}
}
else
{
output.Add(new List<char>(item));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment