How to generate Permutations without repetition recursively in C#

using System;

class GroupPermutations
{
    static void Main(string[] args)
    {
        string[] array = { "apple", "peach", "orange" };
        Perm(array, 0);
    }

    static void Perm<T>(T[] arr, int k)
    {
        if (k >= arr.Length)
            Print(arr);
        else
        {
            Perm(arr, k + 1);
            for (int i = k + 1; i < arr.Length; i++)
            {
                Swap(ref arr[k], ref arr[i]);
                Perm(arr, k + 1);
                Swap(ref arr[k], ref arr[i]);
            }
        }
    }

    private static void Swap<T>(ref T item1, ref T item2)
    {
        T temp = item1;
        item1 = item2;
        item2 = temp;
    }

    private static void Print<T>(T[] arr)
    {
        Console.WriteLine("{" + string.Join(", ", arr) + "}");
    }
}

//Result:
//{apple, peach, orange}
//{apple, orange, peach}
//{peach, apple, orange}
//{peach, orange, apple}
//{orange, peach, apple}
//{orange, apple, peach}

Leave a Reply

Your email address will not be published. Required fields are marked *