I have a listbox where users can enter decimal numbers. Let’s say they’ll enter 5 numbers:
1.1
1.2
1.3
1.4
1.5
I need to get the sum of all the variations in those 5 numbers. For example sum of 1.1 and 1.2 then 1.1 1.2 1.3 then 1.1 1.2 1.3 1.4, then 1.2 1.4 1.5 then 1.1 1.3 1.5.
I started something but that goes through all the variations only skipping one number at a time:
List<Double[]> listNumber = new List<double[]>();
Double[] array;
for (int i = 0; i < listBox1.Items.Count; i++)
{
array = new Double[listBox1.Items.Count];
for (int k = 0; k < listBox1.Items.Count; k++)
{
if (!k.Equals(i))
{
array[k] = (Convert.ToDouble(listBox1.Items[k]));
}
}
listNumber.Add(array);
}
I need to find a way how to calculate the way I want.
In your initial attempt, your code only calculates the sum of all possible pairs. From your description, you also want to find the sum of three numbers, etc..
If there are always 5 decimal numbers, then you can simply have 5 for loops. However a more generic design would be cleaner
Here it is without any code for avoiding the addition of the same number twice (I’ll let you try to finish that off. HINT: You can simply do so after the increment counters section, containing both the “Increment Counters” section and the new “Check Counters” section inside a while loop, breaking outside the while loop when the counters are unique…
NOTE: I haven’t tested this code, but it’ll be close, and will likely have one or two bugs in it – let me know if you need any help with the bugs.