Created
February 27, 2013 22:35
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanx! A nice implementation.