CShap 协程全排列 源代码
时间: 2023-11-23 10:08:05 浏览: 77
以下是C#协程全排列的源代码:
using System;
using System.Collections;
public class CoroutinePermutations
{
private int[] array;
private int currentIndex;
private IEnumerator coroutine;
public CoroutinePermutations(int[] array)
{
this.array = array;
this.currentIndex = array.Length - 1;
this.coroutine = Permute().GetEnumerator();
}
public bool Next()
{
return coroutine.MoveNext();
}
public int[] Current
{
get { return (int[])coroutine.Current; }
}
private IEnumerable Permute()
{
if (array.Length == 1)
{
yield return array;
}
else
{
while (true)
{
yield return array;
int i = currentIndex - 1;
while (i >= 0 && array[i] >= array[i + 1])
{
i--;
}
if (i < 0)
{
yield break;
}
int j = array.Length - 1;
while (array[j] <= array[i])
{
j--;
}
Swap(i, j);
for (int k = currentIndex, l = array.Length - 1; k < l; k++, l--)
{
Swap(k, l);
}
}
}
}
private void Swap(int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Example usage:
int[] array = { 1, 2, 3 };
CoroutinePermutations permutations = new CoroutinePermutations(array);
while (permutations.Next())
{
int[] current = permutations.Current;
Console.WriteLine(string.Join(", ", current));
}
阅读全文