Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCodeDay9
{
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> sequence)
{
if (sequence == null)
{
yield break;
}
var list = sequence.ToList();
if (!list.Any())
{
yield return Enumerable.Empty<T>();
}
else
{
var startingElementIndex = 0;
foreach (var startingElement in list)
{
var remainingItems = list.AllExcept(startingElementIndex);
foreach (var permutationOfRemainder in remainingItems.Permute())
{
yield return startingElement.Concat(permutationOfRemainder);
}
startingElementIndex++;
}
}
}
private static IEnumerable<T> Concat<T>(this T firstElement, IEnumerable<T> secondSequence)
{
yield return firstElement;
if (secondSequence == null)
{
yield break;
}
foreach (var item in secondSequence)
{
yield return item;
}
}
private static IEnumerable<T> AllExcept<T>(this IEnumerable<T> sequence, int indexToSkip)
{
if (sequence == null)
{
yield break;
}
var index = 0;
foreach (var item in sequence.Where(item => index++ != indexToSkip))
{
yield return item;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.