How to get all possible combinations from an array of numbers in C#

1 Answer

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

class Program
{
    public static IEnumerable<T[]> Combinations<T>(IEnumerable<T> arr) {
        T[] combination = arr.ToArray();
    
        return Enumerable
            .Range(0, 1 << (combination.Length))
            .Select(index => combination
            .Where((val, idx) => (index & (1 << idx)) != 0)
            .ToArray());
    }
    static void Main() {
        var arr = new int[] { 3, 6, 0, 8 };

        var result = Combinations(arr);

        foreach (var element in result) {
            string str = string.Join(", ", element);
            if (str != "") Console.WriteLine($"[{str}]");
        }
    }
}




/*
run:

[3]
[6]
[3, 6]
[0]
[3, 0]
[6, 0]
[3, 6, 0]
[8]
[3, 8]
[6, 8]
[3, 6, 8]
[0, 8]
[3, 0, 8]
[6, 0, 8]
[3, 6, 0, 8]

*/

 



answered Oct 15, 2022 by avibootz
...