Searching for all combinations of numbers from a set of numbers which equal a target, code misses some but not allFind out which combinations of numbers in a set add up to a given totalPassed value is not returnedUsing Recursion to get combinations of Numbers in C# that equal the same sumc# method overload, with other methodsMulti threading with a list of input in C#Get set of random numbers from input List having fixed sum using C#c# Efficient algorithm to find a combination, which summation is equal to two known number, in two set of numberHow to build an algorithm to find a combination, which summation is nearest to a number and its difference is within a range in c#Algorithm to find the set of values which are repeatable to fit upto a maximum Total valueQuery to find most number of rows with greatest sum
Plagiarism or not?
Mathematica command that allows it to read my intentions
How did the Super Star Destroyer Executor get destroyed exactly?
Is it acceptable for a professor to tell male students to not think that they are smarter than female students?
GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?
Expand and Contract
How do I deal with an unproductive colleague in a small company?
How do conventional missiles fly?
What does “the session was packed” mean in this context?
How could indestructible materials be used in power generation?
Unlock My Phone! February 2018
Venezuelan girlfriend wants to travel the USA to be with me. What is the process?
One verb to replace 'be a member of' a club
Avoiding the "not like other girls" trope?
How can saying a song's name be a copyright violation?
Examples of smooth manifolds admitting inbetween one and a continuum of complex structures
How to Recreate this in LaTeX? (Unsure What the Notation is Called)
Forgetting the musical notes while performing in concert
How much of data wrangling is a data scientist's job?
If human space travel is limited by the G force vulnerability, is there a way to counter G forces?
Im going to France and my passport expires June 19th
How to compactly explain secondary and tertiary characters without resorting to stereotypes?
What is a romance in Latin?
Are there any examples of a variable being normally distributed that is *not* due to the Central Limit Theorem?
Searching for all combinations of numbers from a set of numbers which equal a target, code misses some but not all
Find out which combinations of numbers in a set add up to a given totalPassed value is not returnedUsing Recursion to get combinations of Numbers in C# that equal the same sumc# method overload, with other methodsMulti threading with a list of input in C#Get set of random numbers from input List having fixed sum using C#c# Efficient algorithm to find a combination, which summation is equal to two known number, in two set of numberHow to build an algorithm to find a combination, which summation is nearest to a number and its difference is within a range in c#Algorithm to find the set of values which are repeatable to fit upto a maximum Total valueQuery to find most number of rows with greatest sum
I used this question Find out which combinations of numbers in a set add up to a given total which uses a C# example to attempt to find all the possible combinations of numbers which add up to a given number.
I used the code as provided and have attempted to understand it and I think I do, however, I can't figure out why this error is occurring.
Here is the setup:
public class Program
public static void Main(string[] args)
// subtotal list
List<double> totals = new List<double>(new double[] 17.5, 14.3, 10.9, 7.8, 6.3, 3.8, 3.2, 2.7, 1.8, 1.0 );
List<double> totals2 = new List<double>(new double[] 17.5, 14.3, 7.8, 6.3, 3.2, 1.8);
// get matches
List<double[]> results = Knapsack.MatchTotal(50.9, totals2);
// print results`
foreach (var result in results)
Console.WriteLine(string.Join(",", result));
Console.WriteLine("Done.");
Console.ReadKey();
and the main bulk of the code is unchanged from the example.
public class Knapsack
internal static List<double[]> MatchTotal(double theTotal, List<double> subTotals)
List<double[]> results = new List<double[]>();
while (subTotals.Contains(theTotal))
results.Add(new double[1] theTotal );
subTotals.Remove(theTotal);
// if no subtotals were passed
// or all matched the Total
// return
if (subTotals.Count == 0)
return results;
subTotals.Sort();
double mostNegativeNumber = subTotals[0];
if (mostNegativeNumber > 0)
mostNegativeNumber = 0;
// if there aren't any negative values
// we can remove any values bigger than the total
if (mostNegativeNumber == 0)
subTotals.RemoveAll(d => d > theTotal);
// if there aren't any negative values
// and sum is less than the total no need to look further
if (mostNegativeNumber == 0 && subTotals.Sum() < theTotal)
return results;
// get the combinations for the remaining subTotals
// skip 1 since we already removed subTotals that match
for (int choose = 2; choose <= subTotals.Count; choose++)
// get combinations for each length
IEnumerable<IEnumerable<double>> combos = Combination.Combinations(subTotals.AsEnumerable(), choose);
// add combinations where the sum mathces the total to the result list
results.AddRange(from combo in combos
where combo.Sum() == theTotal
select combo.ToArray());
return results;
public static class Combination
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int choose)
return choose == 0 ? // if choose = 0
new[] new T[0] : // return empty Type array
elements.SelectMany((element, i) => // else recursively iterate over array to create combinations
elements.Skip(i + 1).Combinations(choose - 1).Select(combo => (new[] element ).Concat(combo)));
I have provided the set of numbers which is in totals
which are used to try and calculate the total.
I entered 50.9 as the total and return no results.
The second set of numbers totals2
is a set of numbers which add up to 50.9 and they are a subset of totals
. This also fails to return a result for 50.9
For some reason the code is unable to find 50.9 in the master set or in the subset (which itself sums to 50.9).
I can't figure out why it does this, can anyone tell me?
c# knapsack-problem
|
show 1 more comment
I used this question Find out which combinations of numbers in a set add up to a given total which uses a C# example to attempt to find all the possible combinations of numbers which add up to a given number.
I used the code as provided and have attempted to understand it and I think I do, however, I can't figure out why this error is occurring.
Here is the setup:
public class Program
public static void Main(string[] args)
// subtotal list
List<double> totals = new List<double>(new double[] 17.5, 14.3, 10.9, 7.8, 6.3, 3.8, 3.2, 2.7, 1.8, 1.0 );
List<double> totals2 = new List<double>(new double[] 17.5, 14.3, 7.8, 6.3, 3.2, 1.8);
// get matches
List<double[]> results = Knapsack.MatchTotal(50.9, totals2);
// print results`
foreach (var result in results)
Console.WriteLine(string.Join(",", result));
Console.WriteLine("Done.");
Console.ReadKey();
and the main bulk of the code is unchanged from the example.
public class Knapsack
internal static List<double[]> MatchTotal(double theTotal, List<double> subTotals)
List<double[]> results = new List<double[]>();
while (subTotals.Contains(theTotal))
results.Add(new double[1] theTotal );
subTotals.Remove(theTotal);
// if no subtotals were passed
// or all matched the Total
// return
if (subTotals.Count == 0)
return results;
subTotals.Sort();
double mostNegativeNumber = subTotals[0];
if (mostNegativeNumber > 0)
mostNegativeNumber = 0;
// if there aren't any negative values
// we can remove any values bigger than the total
if (mostNegativeNumber == 0)
subTotals.RemoveAll(d => d > theTotal);
// if there aren't any negative values
// and sum is less than the total no need to look further
if (mostNegativeNumber == 0 && subTotals.Sum() < theTotal)
return results;
// get the combinations for the remaining subTotals
// skip 1 since we already removed subTotals that match
for (int choose = 2; choose <= subTotals.Count; choose++)
// get combinations for each length
IEnumerable<IEnumerable<double>> combos = Combination.Combinations(subTotals.AsEnumerable(), choose);
// add combinations where the sum mathces the total to the result list
results.AddRange(from combo in combos
where combo.Sum() == theTotal
select combo.ToArray());
return results;
public static class Combination
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int choose)
return choose == 0 ? // if choose = 0
new[] new T[0] : // return empty Type array
elements.SelectMany((element, i) => // else recursively iterate over array to create combinations
elements.Skip(i + 1).Combinations(choose - 1).Select(combo => (new[] element ).Concat(combo)));
I have provided the set of numbers which is in totals
which are used to try and calculate the total.
I entered 50.9 as the total and return no results.
The second set of numbers totals2
is a set of numbers which add up to 50.9 and they are a subset of totals
. This also fails to return a result for 50.9
For some reason the code is unable to find 50.9 in the master set or in the subset (which itself sums to 50.9).
I can't figure out why it does this, can anyone tell me?
c# knapsack-problem
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05
|
show 1 more comment
I used this question Find out which combinations of numbers in a set add up to a given total which uses a C# example to attempt to find all the possible combinations of numbers which add up to a given number.
I used the code as provided and have attempted to understand it and I think I do, however, I can't figure out why this error is occurring.
Here is the setup:
public class Program
public static void Main(string[] args)
// subtotal list
List<double> totals = new List<double>(new double[] 17.5, 14.3, 10.9, 7.8, 6.3, 3.8, 3.2, 2.7, 1.8, 1.0 );
List<double> totals2 = new List<double>(new double[] 17.5, 14.3, 7.8, 6.3, 3.2, 1.8);
// get matches
List<double[]> results = Knapsack.MatchTotal(50.9, totals2);
// print results`
foreach (var result in results)
Console.WriteLine(string.Join(",", result));
Console.WriteLine("Done.");
Console.ReadKey();
and the main bulk of the code is unchanged from the example.
public class Knapsack
internal static List<double[]> MatchTotal(double theTotal, List<double> subTotals)
List<double[]> results = new List<double[]>();
while (subTotals.Contains(theTotal))
results.Add(new double[1] theTotal );
subTotals.Remove(theTotal);
// if no subtotals were passed
// or all matched the Total
// return
if (subTotals.Count == 0)
return results;
subTotals.Sort();
double mostNegativeNumber = subTotals[0];
if (mostNegativeNumber > 0)
mostNegativeNumber = 0;
// if there aren't any negative values
// we can remove any values bigger than the total
if (mostNegativeNumber == 0)
subTotals.RemoveAll(d => d > theTotal);
// if there aren't any negative values
// and sum is less than the total no need to look further
if (mostNegativeNumber == 0 && subTotals.Sum() < theTotal)
return results;
// get the combinations for the remaining subTotals
// skip 1 since we already removed subTotals that match
for (int choose = 2; choose <= subTotals.Count; choose++)
// get combinations for each length
IEnumerable<IEnumerable<double>> combos = Combination.Combinations(subTotals.AsEnumerable(), choose);
// add combinations where the sum mathces the total to the result list
results.AddRange(from combo in combos
where combo.Sum() == theTotal
select combo.ToArray());
return results;
public static class Combination
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int choose)
return choose == 0 ? // if choose = 0
new[] new T[0] : // return empty Type array
elements.SelectMany((element, i) => // else recursively iterate over array to create combinations
elements.Skip(i + 1).Combinations(choose - 1).Select(combo => (new[] element ).Concat(combo)));
I have provided the set of numbers which is in totals
which are used to try and calculate the total.
I entered 50.9 as the total and return no results.
The second set of numbers totals2
is a set of numbers which add up to 50.9 and they are a subset of totals
. This also fails to return a result for 50.9
For some reason the code is unable to find 50.9 in the master set or in the subset (which itself sums to 50.9).
I can't figure out why it does this, can anyone tell me?
c# knapsack-problem
I used this question Find out which combinations of numbers in a set add up to a given total which uses a C# example to attempt to find all the possible combinations of numbers which add up to a given number.
I used the code as provided and have attempted to understand it and I think I do, however, I can't figure out why this error is occurring.
Here is the setup:
public class Program
public static void Main(string[] args)
// subtotal list
List<double> totals = new List<double>(new double[] 17.5, 14.3, 10.9, 7.8, 6.3, 3.8, 3.2, 2.7, 1.8, 1.0 );
List<double> totals2 = new List<double>(new double[] 17.5, 14.3, 7.8, 6.3, 3.2, 1.8);
// get matches
List<double[]> results = Knapsack.MatchTotal(50.9, totals2);
// print results`
foreach (var result in results)
Console.WriteLine(string.Join(",", result));
Console.WriteLine("Done.");
Console.ReadKey();
and the main bulk of the code is unchanged from the example.
public class Knapsack
internal static List<double[]> MatchTotal(double theTotal, List<double> subTotals)
List<double[]> results = new List<double[]>();
while (subTotals.Contains(theTotal))
results.Add(new double[1] theTotal );
subTotals.Remove(theTotal);
// if no subtotals were passed
// or all matched the Total
// return
if (subTotals.Count == 0)
return results;
subTotals.Sort();
double mostNegativeNumber = subTotals[0];
if (mostNegativeNumber > 0)
mostNegativeNumber = 0;
// if there aren't any negative values
// we can remove any values bigger than the total
if (mostNegativeNumber == 0)
subTotals.RemoveAll(d => d > theTotal);
// if there aren't any negative values
// and sum is less than the total no need to look further
if (mostNegativeNumber == 0 && subTotals.Sum() < theTotal)
return results;
// get the combinations for the remaining subTotals
// skip 1 since we already removed subTotals that match
for (int choose = 2; choose <= subTotals.Count; choose++)
// get combinations for each length
IEnumerable<IEnumerable<double>> combos = Combination.Combinations(subTotals.AsEnumerable(), choose);
// add combinations where the sum mathces the total to the result list
results.AddRange(from combo in combos
where combo.Sum() == theTotal
select combo.ToArray());
return results;
public static class Combination
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int choose)
return choose == 0 ? // if choose = 0
new[] new T[0] : // return empty Type array
elements.SelectMany((element, i) => // else recursively iterate over array to create combinations
elements.Skip(i + 1).Combinations(choose - 1).Select(combo => (new[] element ).Concat(combo)));
I have provided the set of numbers which is in totals
which are used to try and calculate the total.
I entered 50.9 as the total and return no results.
The second set of numbers totals2
is a set of numbers which add up to 50.9 and they are a subset of totals
. This also fails to return a result for 50.9
For some reason the code is unable to find 50.9 in the master set or in the subset (which itself sums to 50.9).
I can't figure out why it does this, can anyone tell me?
c# knapsack-problem
c# knapsack-problem
asked Mar 7 at 22:51
JamesDonnellyJamesDonnelly
1,04241231
1,04241231
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05
|
show 1 more comment
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05
|
show 1 more comment
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054079%2fsearching-for-all-combinations-of-numbers-from-a-set-of-numbers-which-equal-a-ta%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054079%2fsearching-for-all-combinations-of-numbers-from-a-set-of-numbers-which-equal-a-ta%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What does the second set add up to according to the computer? double is imperfect
– Make StackOverflow Good Again
Mar 7 at 23:08
Please do not provide your entire code, but unly the relevant parts and some sample data.
– HimBromBeere
Mar 8 at 0:40
@MakeStackOverflowGoodAgain when debugging it shows it as 50.9 rather than 50.900000000001 or something. I tested it by rounding it with no luck. I also ran it for all numbers between 1 and the sum of the set in increments of 0.1, again rounding and it fines lots, but not 50.9.
– JamesDonnelly
Mar 8 at 5:46
@HimBromBeere I believe all the code I have provided is necessary to allow for the question to be understood and explored.
– JamesDonnelly
Mar 8 at 5:50
You should switch to decimal instead of double and try again. I had a similar challenge today and had a similar issue. Switching to decimal fixed it.
– Skyqula
Mar 8 at 21:05