How to generate Permutations without repetition iteratively in C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 1, 2, 3
// 2, 1, 3
// 3, 1, 2
// 1, 3, 2
// 2, 3, 1
// 3, 2, 1
// Total permutations: 6
 
using System;
using System.Linq;
 
public static class GeneratePermutationsIteratively
{
    public static void Main()
    {
        var num = int.Parse(Console.ReadLine());
 
        var numberOfPerm = 1;
        var elements = Enumerable.Range(1, num).ToArray();
        var workArr = Enumerable.Range(0, elements.Length + 1).ToArray();
 
        PrintPerm(elements);
        var index = 1;
        while (index < elements.Length)
        {
            workArr[index]--;
            var j = 0;
            if (index % 2 == 1)
            {
                j = workArr[index];
            }
 
            SwapInts(ref elements[j], ref elements[index]);
            index = 1;
            while (workArr[index] == 0)
            {
                workArr[index] = index;
                index++;
            }
 
            numberOfPerm++;
            PrintPerm(elements);
        }
 
        Console.WriteLine($"Total permutations: {numberOfPerm}");
    }
 
    private static void PrintPerm(int[] elements)
    {
        Console.WriteLine(string.Join(", ", elements));
    }
 
    private static void SwapInts(ref int a, ref int b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}