Skip to content

Instantly share code, notes, and snippets.

@martinfreedman
Last active January 17, 2018 17:17
Show Gist options
  • Save martinfreedman/139dd0ec7df4737651482241e48b062f to your computer and use it in GitHub Desktop.
Save martinfreedman/139dd0ec7df4737651482241e48b062f to your computer and use it in GitHub Desktop.
Combinatorics Extensions Methods
public static class EnumerableExtensions
{
// more generic from https://codereview.stackexchange.com/questions/91808/permutations-in-c
public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)
{
if (values.Count() == 1)
return values.ToSingleton();
return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())),(v, p) => p.Prepend(v));
}
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) =>
seqs.Aggregate(Enumerable.Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s))));
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) =>
Enumerable.Repeat(seq, repeat).CartesianProduct();
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) =>
seq.Aggregate(Enumerable.Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) =>
seq.Combinations().Where(s => s.Count() == numItems);
public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment