The posts already made demonstrate how to make the code more succint.
I thought it would be interesting to generalise it.
Here is a class that will do the job for user-defined totals and sequence length.
To use it, do something like:
Proposed p = new Proposed();
p.OutputCombinations (3,6); // 3 numbers that total 6
p.OutputCombinations (4,5); // 4 numbers that total 5
p.OutputCombinations (3,10); // you get the idea ....
class Proposed
{
private int _targetTotal;
private int _numItems;
private int[] _row;
public void OutputCombinations(int numItems, int targetTotal)
{
_targetTotal = targetTotal;
_numItems = numItems;
_row = new int[numItems];
_outputCombinations(0, 0);
}
private void _outputCombinations(int currentIndex, int currentTotal)
{
if (currentIndex == _numItems - 1)
{
/* We are at the last positionso set the only legal remaining value */
_row[currentIndex] = _targetTotal - currentTotal;
/* Output the line */
StringBuilder sb = new StringBuilder();
for (int i = 0; (i < _numItems); i++)
{
if (sb.Length > 0) sb.Append(',');
sb.Append(_row.ToString());
}
}
else
{
/* Recursive call to this routine to fill the rest of the row */
for (int currentValue =0 ; currentValue < _targetTotal - currentTotal; currentValue++)
{
_row[currentIndex] = currentValue;
_outputCombinations(currentIndex + 1, currentTotal + currentValue);
}
The posts already made demonstrate how to make the code more succint.
I thought it would be interesting to generalise it.
Here is a class that will do the job for user-defined totals and sequence length.
To use it, do something like:
Proposed p = new Proposed();
p.OutputCombinations (3,6); // 3 numbers that total 6
p.OutputCombinations (4,5); // 4 numbers that total 5
p.OutputCombinations (3,10); // you get the idea ....
class Proposed
{
private int _targetTotal;
private int _numItems;
private int[] _row;
public void OutputCombinations(int numItems, int targetTotal)
{
_targetTotal = targetTotal;
_numItems = numItems;
_row = new int[numItems];
_outputCombinations(0, 0);
}
private void _outputCombinations(int currentIndex, int currentTotal)
{
if (currentIndex == _numItems - 1)
{
/* We are at the last positionso set the only legal remaining value */
_row[currentIndex] = _targetTotal - currentTotal;
/* Output the line */
StringBuilder sb = new StringBuilder();
for (int i = 0; (i < _numItems); i++)
{
if (sb.Length > 0) sb.Append(',');
sb.Append(_row.ToString());
}
System.Diagnostics.Debug.W
}
else
{
/* Recursive call to this routine to fill the rest of the row */
for (int currentValue =0 ; currentValue < _targetTotal - currentTotal; currentValue++)
{
_row[currentIndex] = currentValue;
_outputCombinations(curren
}
}
}
}