using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication31 { class Program { static void Main(string[] args) { int[] test = new int[] { 1, 2, 4, 6 }; int threshold = 10; foreach (var item in CombinationIndexes(test).Where(ii => ii.Sum(ix => test[ix]) >= threshold)) { Console.WriteLine(string.Join(",", item.Select(i => i.ToString()))); } Console.ReadLine(); } const int BitsInUlong = 8 * sizeof(ulong); static IEnumerable<IEnumerable<int>> CombinationIndexes<T>(IList<T> collection) { if (collection.Count > BitsInUlong) throw new ArgumentOutOfRangeException("collection", "collection is too large"); ulong count = (~(ulong)0) >> (BitsInUlong - collection.Count); for (ulong bits = 0; bits <= count; bits++) { yield return BitNumbers(bits); } } static IEnumerable<int> BitNumbers(ulong bits) { if (bits == 0) yield break; ulong mask = 1; for (int i = 0; i < BitsInUlong; ++i) { if ((bits & mask) != 0) { yield return i; } mask <<= 1; } } } }
Matt T Heffron
yield Return BitNumbers(bits)
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)