How to generate all possible permutations and combinations of a list of chars in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

public class PermutationsAndCombinations
{
    // Print a list of characters
    static void PrintList(List<char> list) {
        foreach (char ch in list) {
            Console.Write(ch + " ");
        }
        Console.WriteLine();
    }

    // Generate all permutations in lexicographic order
    static void GeneratePermutations(List<char> list) {
        list.Sort(); // Ensure lexicographic order

        do {
            PrintList(list);
        } while (NextPermutation(list));
    }

    // Implementation of next_permutation (like C++ STL)
    static bool NextPermutation(List<char> list) {
        int size = list.Count;
        int i = size - 2;

        while (i >= 0 && list[i] >= list[i + 1]) {
            i--;
        }

        if (i < 0) return false;

        int j = size - 1;
        while (list[j] <= list[i]) {
            j--;
        }

        // Swap
        char temp = list[i];
        list[i] = list[j];
        list[j] = temp;

        // Reverse the suffix
        list.Reverse(i + 1, size - (i + 1));

        return true;
    }

    // Generate all combinations using bitmask
    static void GenerateCombinations(List<char> list) {
        int size = list.Count;

        for (int mask = 1; mask < (1 << size); mask++) {
            List<char> subset = new List<char>();
            for (int i = 0; i < size; i++) {
                if ((mask & (1 << i)) != 0) {
                    subset.Add(list[i]);
                }
            }
            PrintList(subset);
        }
    }

    public static void Main(string[] args)
    {
        List<char> list = new List<char> { 'a', 'b', 'c' };

        Console.WriteLine("All permutations:");
        GeneratePermutations(new List<char>(list));

        Console.WriteLine("\nAll combinations:");
        GenerateCombinations(list);
    }
}



/*
run:
 
All permutations:
a b c 
a c b 
b a c 
b c a 
c a b 
c b a 

All combinations:
a 
b 
a b 
c 
a c 
b c 
a b c 
 
*/

 



answered 16 hours ago by avibootz

Related questions

...