Skip to content

Instantly share code, notes, and snippets.

@johnboker
Created December 9, 2015 16:04
Show Gist options
  • Save johnboker/0695f972e31b36413969 to your computer and use it in GitHub Desktop.
Save johnboker/0695f972e31b36413969 to your computer and use it in GitHub Desktop.
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