Skip to main content
added 59 characters in body
Source Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101

You did also ask for a shortened version. I believe readability should not be a concern here (meaning the code should aim at being functional, not readable). Remove the local recursive function and allow the public API to have an optional parameter.

public static IEnumerable<T[]> Permutate<T>(
    this IEnumerable<T> source, IEnumerable<T> prefix = null) => 
        !source.Any() ? new[] { (prefix ?? Enumerable.Empty<T>()).ToArray() } :
            source.SelectMany((c, i) =>
                source.Take(i).Concat(source.Skip(i+1)).ToArray().Permutate(
                prefix.Append(c)));

use in production code at own risk :-)

You did also ask for a shortened version. I believe readability should not be a concern here. Remove the local recursive function and allow the public API to have an optional parameter.

public static IEnumerable<T[]> Permutate<T>(
    this IEnumerable<T> source, IEnumerable<T> prefix = null) => 
        !source.Any() ? new[] { (prefix ?? Enumerable.Empty<T>()).ToArray() } :
            source.SelectMany((c, i) =>
                source.Take(i).Concat(source.Skip(i+1)).ToArray().Permutate(
                prefix.Append(c)));

You did also ask for a shortened version. I believe readability should not be a concern here (meaning the code should aim at being functional, not readable). Remove the local recursive function and allow the public API to have an optional parameter.

public static IEnumerable<T[]> Permutate<T>(
    this IEnumerable<T> source, IEnumerable<T> prefix = null) => 
        !source.Any() ? new[] { (prefix ?? Enumerable.Empty<T>()).ToArray() } :
            source.SelectMany((c, i) =>
                source.Take(i).Concat(source.Skip(i+1)).ToArray().Permutate(
                prefix.Append(c)));

use in production code at own risk :-)

Source Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101

You did also ask for a shortened version. I believe readability should not be a concern here. Remove the local recursive function and allow the public API to have an optional parameter.

public static IEnumerable<T[]> Permutate<T>(
    this IEnumerable<T> source, IEnumerable<T> prefix = null) => 
        !source.Any() ? new[] { (prefix ?? Enumerable.Empty<T>()).ToArray() } :
            source.SelectMany((c, i) =>
                source.Take(i).Concat(source.Skip(i+1)).ToArray().Permutate(
                prefix.Append(c)));