ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

Combinations

Returns all combinations of a chosen amount of selected elements in the sequence.

Source

/// <summary>
///   Returns all combinations of a chosen amount of selected elements in the sequence.
/// </summary>
/// <typeparam name = "T">The type of the elements of the input sequence.</typeparam>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "select">The amount of elements to select for every combination.</param>
/// <param name = "repetition">True when repetition of elements is allowed.</param>
/// <returns>All combinations of a chosen amount of selected elements in the sequence.</returns>
public static IEnumerable<IEnumerable<T>> Combinations<T>( this IEnumerable<T> source, int select, bool repetition = false )
{
	Contract.Requires( source != null );
	Contract.Requires( select >= 0 );

	return select == 0
		? new[] { new T[0] }
		: source.SelectMany( ( element, index ) =>
			source
				.Skip( repetition ? index : index + 1 )
				.Combinations( select - 1, repetition )
				.Select( c => new[] { element }.Concat( c ) ) );
}

Example

int[] numbers = new[] { 0, 1 };
var result = numbers.Combinations( 2, true );
// result == {{0, 0}, {0, 1}, {1, 0}, {1, 1}}

Author: Steven Jeuris

Submitted on: 15 nov 2011

Language: C#

Type: System.IEnumerable<T>

Views: 6017