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













1















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?










share|improve this question






















  • 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















1















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?










share|improve this question






















  • 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













1












1








1








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?










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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

















  • 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












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
);



);













draft saved

draft discarded


















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















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved