c# - How can I find out which numbers in a defined set add up to another number? -
i have number 6
, need search inside array of ints if of numbers can added 6
.
example:
1,2,3,5,4
in above array can take 1+2+3
makes 6
.
i can take 4+2
6
.
the question how find individual numbers can sum number 6.
one possible option list of combinations of items in array, check 1 of has sum of target number.
i found extension method getting combinations here (copied below).
public static ienumerable<t[]> combinations<t>(this ilist<t> arglist, int argsetsize) { if (arglist == null) throw new argumentnullexception("arglist"); if (argsetsize <= 0) throw new argumentexception("argsetsize must greater 0", "argsetsize"); return combinationsimpl(arglist, 0, argsetsize - 1); } private static ienumerable<t[]> combinationsimpl<t>(ilist<t> arglist, int argstart, int argiteration, list<int> argindicies = null) { argindicies = argindicies ?? new list<int>(); (int = argstart; < arglist.count; i++) { argindicies.add(i); if (argiteration > 0) { foreach (var array in combinationsimpl(arglist, + 1, argiteration - 1, argindicies)) { yield return array; } } else { var array = new t[argindicies.count]; (int j = 0; j < argindicies.count; j++) { array[j] = arglist[argindicies[j]]; } yield return array; } argindicies.removeat(argindicies.count - 1); } }
now need call number of combinations want in groups. example, if wanted find groups of 2:
list<int> ints = new list<int>() { 1, 2, 3, 4, 5 }; int target = 6; var combs2 = ints.combinations(2) .where(x => x.sum() == target);
this return 1,5
, 2,4
. can repeat maximum number of items want in group.
if want results @ once, make new extension method unioning you:
public static ienumerable<t[]> allcombinations<t>(this ilist<t> argslist) { (int = 1; <= argslist.count; i++) { foreach (var combo in argslist.combinations(i)) { yield return combo; } } }
then can combinations @ once running
var allcombos = ints.allcombinations() .where(x => x.sum() == target);
so example, return 1,5
, 2,4
, , 1,2,3
in 1 collection.
Comments
Post a Comment