Skip to content

Instantly share code, notes, and snippets.

@steveash
Created November 21, 2016 22:31
Show Gist options
  • Save steveash/793289679648cd516e6e91840d0d5ffc to your computer and use it in GitHub Desktop.
Save steveash/793289679648cd516e6e91840d0d5ffc to your computer and use it in GitHub Desktop.
Generate all total orderings of (a) an unordered set of events with (b) an ordered list of events.
public static IEnumerable<List<T>> AllOrderings<T>(List<T> unordered, List<T> ordered)
{
if (unordered.Count == 0)
{
yield return ordered;
}
else
{
foreach (var permutation in GetPermutations(unordered, unordered.Count))
{
var unorderedPermutation = permutation.ToList();
foreach (var interleaving in AllInterleavings(unorderedPermutation, ordered))
{
yield return interleaving;
}
}
}
}
private static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
{
if (length == 1) return list.Select(t => new T[] { t });
return GetPermutations(list, length - 1).SelectMany(t => list.Where(e => !t.Contains(e)),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
private static IEnumerable<List<T>> AllInterleavings<T>(List<T> candidate, List<T> target)
{
if (candidate.Count == 0)
{
yield return target;
}
else if (target.Count == 0)
{
yield return candidate;
}
else
{
// take the first one and place it all the places that you can and still have a valid list
for (int i = 0; i < target.Count + 1; i++)
{
List<T> result = new List<T>();
if (i > 0)
{
result.AddRange(target.GetRange(0, i));
}
result.Add(candidate[0]);
int candidatesLeft = candidate.Count - 1;
int targetsLeft = target.Count - i;
foreach (var restInterleave in AllInterleavings<T>(candidate.GetRange(1, candidatesLeft), target.GetRange(i, targetsLeft)))
{
var innerResult = new List<T>(result);
innerResult.AddRange(restInterleave);
yield return innerResult;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment