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
double[] input = double[5]; //Pretend the user has entered these
int[] counters = int[input.Length]; //One for each "dimension"
List<double> sums = new List<double>();
for (int i = 0; i < counters.Length; i++)
counters[i] = -1; //The -1 value allows the process to begin with sum of single digits, then pairs, etc..
while (true)
{
double thisSum = 0;
//Apply counters
for (int i = 0; i < counters.Length; i++)
{
if (counters[i] == -1) continue;
thisSum += input[counters[i]];
}
//Increment counters
counters[0]++; //Increment at base
for (int i = 0; i < counters.Length; i++)
{
if (counters[i] >= counters.Length)
{
if (i == counters.Length - 1) //Check if this is the last dimension
return sums; //Exhausted all possible combinations
counters[i] = 0;
counters[i+1]++;
}
else
break;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With