C realizes full array arrangement through yield
- 2021-01-02 21:58:52
- OfStack
This article shows how C# achieves full array arrangement through yield. Share to everybody for everybody reference. The specific analysis is as follows:
Take any m (m≤n) elements from the different elements of n and arrange them in a definite order. This is called taking one of the m elements from the different elements of n. When m=n all permutations are called full permutations.
static void Swap<T>(ref T a, ref T b)
{
T t = a;
a = b;
b = t;
}
static IEnumerable<int[]> Perm(int[] arr, int pos)
{
if (pos == arr.Length)
{
yield return arr;
}
for (int i = pos; i < arr.Length; ++i)
{
Swap(ref arr[i], ref arr[pos]);
foreach (var j in Perm(arr, pos + 1)) yield return j;
Swap(ref arr[i], ref arr[pos]);
}
}
static void Main(string[] args)
{
foreach (var i in Perm(new int[] { 1, 2, 3, 4 }, 0))
{
Console.WriteLine(string.Join(",",i.Select(j=>j.ToString()).ToArray()));
}
}
Hopefully this article has helped you with your C# programming.