110,535
社区成员
发帖
与我相关
我的任务
分享
static void Main(string[] args)
{
int[] values = { 100, 200, 200, 300, 400, 500 };
var testdata = values.Select((n, i) => new { id = i + 1, total = n }).ToArray();
var total = 1000;
Func<IEnumerable<int[]>, int[], IEnumerable<int[]>> comb = (x, y) =>
from a in x
from b in y
where a.Count() == 0 || a.Last() < b
select a.Concat(new[] { b }).ToArray();
var indices = Enumerable.Range(0, testdata.Length).ToArray();
var list = new int[][] { new int[] { } }.AsEnumerable();
var result = Enumerable.Range(1, testdata.Length)
.SelectMany(i => list = comb(list, indices))
.Where(c => c.Sum(i => testdata[i].total) == total)
.Select(c => c.Select(i => testdata[i]));
foreach (var c in result)
Console.WriteLine("({0})\t {1} = {2}",
string.Join(", ", c.Select(d => d.id)),
string.Join(" + ", c.Select(d => d.total)),
total);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>() { 100, 200, 300, 400, 500, 600 };
list.Combo(1, list.Count)
.Where(x => x.Sum() == 1000).ToList().ForEach(x => Console.WriteLine(String.Join("", x)) );
}
}
static class ListCombo
{
public static IEnumerable<List<T>> Combo<T>(this List<T> sourcelist, int min, int max)
{
for (int i = min; i <= max; i++)
foreach (var item in _Combo(sourcelist, i))
yield return item;
}
static IEnumerable<List<T>> _Combo<T>(this List<T> sourcelist, int len)
{
if (len <= 0)
{
yield return new List<T>();
}
else
{
int[] pos = new int[len];
for (int i = 0; i < len; i++) pos[i] = i;
while (pos[0] < sourcelist.Count - len)
{
List<T> newlist = new List<T>();
for (int i = 0; i < len; i++) newlist.Add(sourcelist[pos[i]]);
for (int i = len - 1; i >= 0; i--)
{
if (pos[i] < sourcelist.Count - len + i)
{
pos[i]++;
for (int j = i + 1; j <= len - 1; j++)
pos[j] = pos[i] + j - i;
break;
}
else
{
continue;
}
}
yield return newlist;
}
List<T> last = new List<T>();
for (int i = sourcelist.Count - len; i < sourcelist.Count; i++)
last.Add(sourcelist[i]);
yield return last;
}
}
}
}