Skip to content

Instantly share code, notes, and snippets.

@fdeitelhoff
Created February 27, 2013 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdeitelhoff/5052484 to your computer and use it in GitHub Desktop.
Save fdeitelhoff/5052484 to your computer and use it in GitHub Desktop.
An C# implementation for the B-heap. It generates all permutations for a given number.
public static IEnumerable<IEnumerable<T>> Permute<T>(this IList<T> v)
{
ICollection<IList<T>> result = new List<IList<T>>();
Permute(v, v.Count, result);
return result;
}
private static void Permute<T>(IList<T> v, int n, ICollection<IList<T>> result)
{
if (n == 1)
{
result.Add(new List<T>(v));
}
else
{
for (var i = 0; i < n; i++)
{
Permute(v, n - 1, result);
Swap(v, n % 2 == 1 ? 0 : i, n - 1);
}
}
}
private static void Swap<T>(IList<T> v, int i, int j)
{
var t = v[i];
v[i] = v[j];
v[j] = t;
}
@markolbert
Copy link

Thanx! A nice implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment