Skip to content

Instantly share code, notes, and snippets.

@DUznanski
Created December 11, 2019 16:28
Show Gist options
  • Save DUznanski/038aaadf0560a0d1a11f42af82834c15 to your computer and use it in GitHub Desktop.
Save DUznanski/038aaadf0560a0d1a11f42af82834c15 to your computer and use it in GitHub Desktop.
namespace Alvornithms
{
class Itertools
{
static IEnumerable<T[]> Permutations<T>(T[] ts) where T : System.IComparable<T>
{
Array.Sort(ts);
while (true)
{
yield return (T[])ts.Clone();
int pivot = ts.Length - 2;
while (ts[pivot].CompareTo(ts[pivot + 1]) >= 0)
{
pivot--;
if (pivot < 0) { yield break; }
}
int swap = ts.Length - 1;
while (ts[pivot].CompareTo(ts[swap]) >= 0)
{
swap--;
}
SwapArrayIndexes(ts, pivot, swap);
int swap_counts = (ts.Length - pivot - 1) / 2;
for (int k = 1; k <= swap_counts; k++)
{
SwapArrayIndexes(ts, pivot + k, ts.Length - k);
}
}
}
static void SwapArrayIndexes<T>(T[] ts, int a, int b)
{
T temp = ts[a];
ts[a] = ts[b];
ts[b] = temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment