Skip to content

Instantly share code, notes, and snippets.

@kpol
Last active February 13, 2018 09:14
Show Gist options
  • Select an option

  • Save kpol/32f8d121de0923ad79bb5659ffa1f20a to your computer and use it in GitHub Desktop.

Select an option

Save kpol/32f8d121de0923ad79bb5659ffa1f20a to your computer and use it in GitHub Desktop.
Gets all permutations. Heap's algorithm.
/// <summary>
/// Heap's algorithm.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<T[]> GetAllPermutations<T>(IEnumerable<T> source)
{
var result = source.ToArray();
yield return result;
var copy = result.ToArray();
var c = new int[copy.Length];
int i = 0;
while (i < copy.Length)
{
if (c[i] < i)
{
if (i % 2 == 0)
{
var a = copy[0];
copy[0] = copy[i];
copy[i] = a;
}
else
{
var a = copy[c[i]];
copy[c[i]] = copy[i];
copy[i] = a;
}
yield return copy.ToArray();
c[i]++;
i = 0;
}
else
{
c[i] = 0;
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment