All possible paths in a series of numbers - c++

I have a small problem where I need to find all possible paths given a set of numbers. For example, lets say we have numbers 1, 2 and 3. I need to find all the possible combinations. The result for this simple case is:
path_1 = 1
path_2 = 2
path_3 = 3
path_4 = 1, 2
path_5 = 1, 3
path_6 = 2, 3
path_7 = 1, 2, 3
It is simple to see that the number of paths is (2^n)-1, so for 3 elements, it is 7, and so on. It is quite simple to do this by hand for a small number of elements, but as the numbers get big, it gets harder and harder.
Someone has suggested that I can use the boost graph library for this problem, but am not quite sure how to do as I do not have enough experience with it. Any help would be much appreciated.
Thanks in advance

template< class It >
void compute_all_possible_paths( path_collection_t& res, It b, It e ) {
std::size_t curVecSize = res.size();
for( std::size_t i = 0; i < curVecSize; i++ ) {
path_t p;
p.reserve( res[i].size() + 1 );
std::copy( res[i].begin(), res[i].end(), std::back_inserter(p) );
p.push_back( *b );
res.push_back( p );
}
path_t p;
p.push_back( *b );
res.push_back( p );
if( ++b == e ) return ;
compute_all_possible_paths( res, b, e );
}

Related

Split number into sum of preselected other numbers

I have a number (for example 301, but can be even 10^11).
n = lenght of that number
I have to break it down to sum of max n components. Those components are 0^n, 1^n, 2^n, 3^n...9^n.
How can I do that?
Since you have 1^n included in your options, this becomes a really simple problem solvable through Greedy Approach.
Firstly, let me clarify that the way I understand this, for an input N of length n, you want some solution to this equation:
A.1^n + B.2^n + C.3^n + ... + H.8^n + I.9^n
There are infinitely many possible solutions (just by theory of equations). One possible solution can be found as follows:
a = [x ** n for x in range(0,10)]
consts = [0] * 10
ctr = 9
while N > 0:
consts[ctr] = N // a[ctr]
N = N % a[ctr]
ctr -= 1
return consts
This consts array will have the constant values for the above equation at respective indices.
PS: I've written this in python but you can translate it to C++ as you want. I saw that tag later. If you have any confusion regarding the code, feel free to ask in the comments.
You could use the following to determine the number of components.
int remain = 301; // Target number
int exp = 3; // Length of number (exponent)
int total = 0; // Number of components
bool first = true; // Used to determinie if plus sign is output
for ( int comp = 9; comp > 0; --comp )
{
int count = 0; // Number of times this component is needed
while ( pow(comp, exp) <= remain )
{
++total; // Count up total number of components
++count; // Count up number of times this component is used
remain -= int(pow(comp, exp));
}
if ( count ) // If count is not zero, component is used
{
if ( first )
{
first = false;
}
else
{
printf(" + ");
}
if ( count > 1 )
{
printf("%d(%d^%d)", count, comp, exp);
}
else
{
printf("%d^%d", comp, exp);
}
}
}
if ( total == exp )
{
printf("\r\nTarget number has %d components", exp);
}
else if ( total < exp )
{
printf("\r\nTarget number has less than %d components", exp);
}
else
{
printf("\r\nTarget number has more than %d components", exp);
}
Output for 301:
6^3 + 4^3 + 2(2^3) + 5(1^3)
Target number has more than 3 components
Output for 251:
6^3 + 3^3 + 2^3
Target number has 3 components

How to implement Cryptarithmetic using Constraint Satisfaction in C++

I'll start by explaining what a cryptarithmetic problem is, through an example:
T W O
+ T W O
F O U R
We have to assign a digit [0-9] to each letter such that no two letters share the same digit and it satisfies the above equation.
One solution to the above problem is:
7 6 5
+ 7 6 5
1 5 3 0
There are two ways to solve this problem, one is brute force, this will work but it's not the optimal way. The other way is using constraint satisfaction.
Solution using Constraint Satisfaction
We know that R will always be even because its 2 * O
this narrows down O's domain to {0, 2, 4, 6, 8}
We also know that F can't be anything but 1, since F isn't an addition of two letters, it must be getting its value from carry generated by T + T = O
This also implies that T + T > 9, only then will it be able to generate a carry for F;
This tells us that T > 4 {5, 6, 7, 8, 9}
And as we go on doing this, we keep on narrowing down the domain and this helps us reduce time complexity by a considerable amount.
The concept seems easy, but I'm having trouble implementing it in C++. Especially the part where we generate constraints/domain for each variable. Keep in mind that there are carries involved too.
EDIT: I'm looking for a way to generate a domain for each variable using the concept I stated.
This kind of problem is a good application for generic constraint programming packages like Google's open source OR-Tools. (See https://developers.google.com/optimization and https://developers.google.com/optimization/cp/cryptarithmetic).
The package is written in c++, so it should be a good match for you.
Then programming the problem is as simple as this (sorry, since I work with OR-Tools in c#, this is c# code, but the c++ code will look pretty much the same)
public void initModel(CpModel model)
{
// Make variables
T = model.NewIntVar(0, 9, "T");
W = model.NewIntVar(0, 9, "W");
O = model.NewIntVar(0, 9, "O");
F = model.NewIntVar(0, 9, "F");
U = model.NewIntVar(0, 9, "U");
R = model.NewIntVar(0, 9, "R");
// Constrain the sum
model.Add((2 * (100 * T + 10 * W + O)) == (1000 * F + 100 * O + 10 * U + R));
// Make sure the variables are all different
model.AddAllDifferent(decisionVariables);
// The leading digit shouldn't be 0
model.Add(T != 0);
model.Add(F != 0);
}
and then calling the Solve method.
In the constraint for the sum, the operators* + and == are all overridden in the package to create objects that can be used by the model to enforce the constraint.
This is the start of the output which enumerates the solution
Solution #0: time = 0,00 s;
T = 8
W = 6
O = 7
F = 1
U = 3
R = 4
Solution #1: time = 0,01 s;
T = 8
W = 4
O = 6
F = 1
U = 9
R = 2
Solution #2: time = 0,01 s;
T = 8
W = 3
O = 6
F = 1
U = 7
R = 2
Solution #3: time = 0,01 s;
T = 9
W = 3
O = 8
F = 1
U = 7
R = 6
And here's the complete code including solution printing and Main method for the execution:
using Google.OrTools.Sat;
using System;
using System.IO;
namespace SO69626335_CryptarithmicPuzzle
{
class Program
{
static void Main(string[] args)
{
try
{
Google.OrTools.Sat.CpModel model = new CpModel();
ORModel myModel = new ORModel();
myModel.initModel(model);
IntVar[] decisionVariables = myModel.decisionVariables;
// Creates a solver and solves the model.
CpSolver solver = new CpSolver();
VarArraySolutionPrinter solutionPrinter = new VarArraySolutionPrinter(myModel.variablesToPrintOut);
solver.SearchAllSolutions(model, solutionPrinter);
Console.WriteLine(String.Format("Number of solutions found: {0}",
solutionPrinter.SolutionCount()));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
throw;
}
Console.WriteLine("OK");
Console.ReadKey();
}
}
class ORModel
{
IntVar T;
IntVar W;
IntVar O;
IntVar F;
IntVar U;
IntVar R;
public void initModel(CpModel model)
{
// Make variables
T = model.NewIntVar(0, 9, "T");
W = model.NewIntVar(0, 9, "W");
O = model.NewIntVar(0, 9, "O");
F = model.NewIntVar(0, 9, "F");
U = model.NewIntVar(0, 9, "U");
R = model.NewIntVar(0, 9, "R");
// Constrain the sum
model.Add((2 * (100 * T + 10 * W + O)) == (1000 * F + 100 * O + 10 * U + R));
// Make sure the variables are all different
model.AddAllDifferent(decisionVariables);
// The leading digit shouldn't be 0
model.Add(T != 0);
model.Add(F != 0);
}
public IntVar[] decisionVariables
{
get
{
return new IntVar[] { T, W, O, F, U, R };
}
}
public IntVar[] variablesToPrintOut
{
get
{
return decisionVariables;
}
}
}
public class VarArraySolutionPrinter : CpSolverSolutionCallback
{
private int solution_count_;
private IntVar[] variables;
public VarArraySolutionPrinter(IntVar[] variables)
{
this.variables = variables;
}
public override void OnSolutionCallback()
{
// using (StreamWriter sw = new StreamWriter(#"C:\temp\GoogleSATSolverExperiments.txt", true, Encoding.UTF8))
using (TextWriter sw = Console.Out)
{
sw.WriteLine(String.Format("Solution #{0}: time = {1:F2} s;",
solution_count_, WallTime()));
foreach (IntVar v in variables)
{
sw.Write(
String.Format(" {0} = {1}\r\n", v.ShortString(), Value(v)));
}
solution_count_++;
sw.WriteLine();
}
if (solution_count_ >= 10)
{
StopSearch();
}
}
public int SolutionCount()
{
return solution_count_;
}
}
}
A full solution is way out of scope for a simple SO question, but I can sketch what you would need.
First, generate new letters for the carries:
0 T W O
0 T W O
+ Z Y X V
F O U R
You can then generate a std::map<char, std::set<int>> containing all the options. The letters have the standard range {0..9}, V is {0}, Z is {1} and Y and X have {0..1}.
Next, you need to encode the additions into a set of clauses.
enum class Op { Equal, SumMod10, SumDiv10, Even, Odd };
struct clause { Op op; std::vector<Var> children; };
std::vector<clause> clauses{
{Equal, { 'Z' , 'F'}},
{SumMod10, {'O', 'T', 'T', 'Y'}}, // O = (T+T+Y) mod 10
{SumMod10, {'U', 'W', 'W', 'X'}},
{SumMod10, {'R', 'O', 'O', 'V'}},
{SumDiv10, {'F', 'T', 'T', 'Y'}}, // F is the carry of T+T+Y
{SumDiv10, {'O', 'W', 'W', 'X'}},
{SumDiv10, {'U', 'O', 'O', 'V'}},
};
Then the fun part begins: you need to create a calculation that will try to simplify the constraints using the knowledge it has.
For example, {SumMod10, {'U', 'O', 'O', 'V'}} can be simplified to {SumMod10, {'U', 'O', 'O', 0}} since V=0.
Sometimes a clause can reduce the range of a variable, for example the {Equal, {'Z', 'F'}} constraint can immediately reduce the range of F to {0,1}.
Next, you need to teach your system about basic algebraic equalities for furhter simplification, such as:
{SumMod10, {A, 0, C}} === {SumMod10, {A, C, 0}} === {Equal, {A,C}}
and even more abstract things like "if A >= 5 and B >= 5 then A+B >= 10" or "if A is even and B is even then A + B is also even".
Finally, your system needs to be able to assume hypotheses and disprove them, or prove that a hypothesis is true no matter what, like you did in your post.
For example, assuming that R is odd would mean that O + O is odd, which can only happen if O is odd and even at the same time. Therefore R must be even.
At the end of the day, you will have implemented not only a formal system for describing and evaluating boolean clauses in the numbers domain, you will also have a goal-driven solution engine to go with it. If this is more than just an idle musing, I would strongly look into adoption an SMT system to solve this for you or at least learning Prolog and expressing your problem there.
Here is how I solved it using backtracking
My approach here was to smartly brute force it, I recursively assign every possible value [0-9] to each letter and check if there is any contradiction.
Contradictions can be one of the following:
Two or more letters end up having the same value.
Sum of letters don't match the value of the result letter.
Sum of letters is already assigned to some letter.
As soon as a contradiction occurs, the recursion for that particular combination ends.
#include <bits/stdc++.h>
using namespace std;
vector<string> words, wordOg;
string result, resultOg;
bool solExists = false;
void reverse(string &str){
reverse(str.begin(), str.end());
}
void printProblem(){
cout<<"\n";
for(int i=0;i<words.size();i++){
for(int j=0;j<words[i].size();j++){
cout<<words[i][j];
}
cout<<"\n";
}
cout<<"---------\n";
for(int i=0;i<result.size();i++){
cout<<result[i];
}
cout<<"\n";
}
void printSolution(unordered_map<char, int> charValue){
cout<<"\n";
for(int i=0;i<words.size();i++){
for(int j=0;j<words[i].size();j++){
cout<<charValue[wordOg[i][j]];
}
cout<<"\n";
}
cout<<"---------\n";
for(int i=0;i<result.size();i++){
cout<<charValue[resultOg[i]];
}
cout<<"\n";
}
void solve(int colIdx, int idx, int carry, int sum,unordered_map<char, int> charValue, vector<int> domain){
if(colIdx<words.size()){
if(idx<words[colIdx].size()){
char ch = words[colIdx][idx];
if(charValue.find(ch)!=charValue.end()){
solve(colIdx + 1, idx, carry, sum + charValue[ch], charValue, domain);
}
else{
for(int i=0;i<10;i++){
if(i==0 && idx==words[colIdx].size()-1) continue;
if(domain[i]==-1){
domain[i] = 0;
charValue[ch] = i;
solve(colIdx + 1, idx, carry, sum + i, charValue, domain);
domain[i] = -1;
}
}
}
}
else solve(colIdx + 1, idx, carry, sum, charValue, domain);
}
else{
if(charValue.find(result[idx])!=charValue.end()){
if(((sum+carry)%10)!=charValue[result[idx]]) return;
}
else{
if(domain[(sum + carry)%10]!=-1) return;
domain[(sum + carry)%10] = 0;
charValue[result[idx]] = (sum + carry)%10;
}
carry = (sum+carry)/10;
if(idx==result.size()-1 && (charValue[result[idx]]==0 || carry == 1)) return;
if(idx+1<result.size()) solve(0, idx+1, carry, 0, charValue, domain);
else{
solExists = true;
printSolution(charValue);
}
}
}
int main() {
unordered_map<char, int> charValue;
vector<int> domain(10,-1);
int n;
cout<<"\nEnter number of input words: ";
cin>>n;
cout<<"\nEnter the words: ";
for(int i=0;i<n;i++){
string inp;
cin>>inp;
words.push_back(inp);
}
cout<<"\nEnter the resultant word: ";
cin>>result;
printProblem();
wordOg = words;
resultOg = result;
reverse(result);
for(auto &itr: words) reverse(itr);
solve(0, 0, 0, 0, charValue, domain);
if(!solExists) cout<<"\nNo Solution Exists!";
return 0;
}

How can I convert the given code to a mathematical function?

I am trying to convert a recursion into a mathematical formula. The code snippet (c++) below is a simplified variant. The values look like an exponential function, however I am trying to find a closed form. For example, rec(8, 6) is 1287. As an assumption, I first assumed 6 to be constant and tried to find an exponential function for rec(?, 6). However, these results were extremely inaccurate. Does anyone have an idea how I could achieve a closed function?
Many thanks
int rec(const int a, const int b, const int c = 0, const int d = 0)
{
int result = 0;
if (d == a)
++result;
else
for (int i = 0; c + i < b; ++i)
result += rec(a, b, c + i, d + 1);
return result;
}
There is no universal method of converting a recursive function to a mathematical, closed function. In your case the answer is the number of "b-1" combinations from an "a"-element set, that is, a!/((a-b+1)!(b-1)!).
Proof: Your rec is equivalent to
int rec(const int a, const int b)
{
if (0 == a)
return 1;
int result = 0;
for (int i = 0; i < b; ++i)
result += rec(a - 1, b - i);
return result;
}
because all that matters is a-d and b-c.
If a==0, rec returns 1
If a>0, it returns the sum of rec(a-1, i) where i is in (0, b). This is true and only true for the combinations. If you ask me to prove that, I will, but the plain text format is not good for mathematical proofs
Edit: A general idea.: print all rec(i,j) as a table and try to spot the rule by looking at the table. I did:
for (int i = 0; i != 10 ; ++i){
for (int j = 0; j != 10; ++j){
cout << rec(i, j) << "\t";
}
cout << endl;
}
In this way I spotted that it is the Pascals_triangle
I will give a hint how you could have guessed the result yourself, with the stress on guess.
Take the sequence for rec(i, 6), i = 0,...,10. This is the sequence that you had already investigated. The answer is:
1 6 21 56 126 252 462 792 1287 2002
Now, insert it into Google (I don't know if other search engines can do the trick; Google certainly can). The first result should point you to this famous online encyclopedia:
https://oeis.org/A000389
This the Online Encyclopedia of Integer Sequences! Now, read the description:
A000389 Binomial coefficients C(n,5).
You may be not familiar with the C(*,*) notation, but you can easily understatand its "Binomial coefficient" description.
You certainly notice the relation between 6 in your function and 5 in the answer formula, but to be sure you can repeat your experiment for several other numbers other than 6.
The next step is to see how the A000389 sequence looks like:
0, 0, 0, 0, 0, 1, 6, 21, 56, 126, 252, 462, 792, 1287, 2002, ...
Well, C(i,j) is undefined (or zero, depending on the convention) if i < j. Aha! A000389 is this:
C(0,5) = 0, C(1,5) = 0, ... , C(4,5) = 0, C(5,5) = 1, C(6,5) = 6,...
This is your sequence if you started from the term of index 5, if we start counting from 0.
res(0,6) = C(5,5), res(1,6) = C(6,5),..., res(k, 6) = C(5+k, 5)
You can generalize it to
res(k, j) = C(k + j - 1, j -1)
and then start thinking how to prove it in a mathematically strict way. The usual method is by mathematical induction - I'll skip it.
This final result is already given by #Botond_Horwath, I just show to you the magic of Google search engine + the OEIS website. (If you know the latter, the former is redundant).

Fastest way of computing the power that a "power of 2" number used?

What would be the quickest way to find the power of 2, that a certain number (that is a power of two) used?
I'm not very skilled at mathematics, so I'm not sure how best to describe it. But the function would look similar to x = 2^y where y is the output, and x is the input. Here's a truth table of what it'd look like if that helps explain it.
0 = f(1)
1 = f(2)
2 = f(4)
3 = f(8)
...
8 = f(256)
9 = f(512)
I've made a function that does this, but I fear it's not very efficient (or elegant for that matter). Would there be a simpler and more efficient way of doing this? I'm using this to compute what area of a texture is used to buffer how drawing is done, so it's called at least once for every drawn object. Here's the function I've made so far:
uint32 getThePowerOfTwo(uint32 value){
for(uint32 n = 0; n < 32; ++n){
if(value <= (1 << n)){
return n;
}
}
return 32; // should never be called
}
Building on woolstar's answer - I wonder if a binary search of a lookup table would be slightly faster? (and much nicer looking)...
int getThePowerOfTwo(int value) {
static constexpr int twos[] = {
1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7,
1<<8, 1<<9, 1<<10, 1<<11, 1<<12, 1<<13, 1<<14, 1<<15,
1<<16, 1<<17, 1<<18, 1<<19, 1<<20, 1<<21, 1<<22, 1<<23,
1<<24, 1<<25, 1<<26, 1<<27, 1<<28, 1<<29, 1<<30, 1<<31
};
return std::lower_bound(std::begin(twos), std::end(twos), value) - std::begin(twos);
}
This operation is sufficiently popular for processor vendors to come up with hardware support for it. Check out find first set. Compiler vendors offer specific functions for this, unfortunately there appears to be no standard how to name it. So if you need maximum performance you have to create compiler-dependent code:
# ifdef __GNUC__
return __builtin_ffs( x ) - 1; // GCC
#endif
#ifdef _MSC_VER
return CHAR_BIT * sizeof(x)-__lzcnt( x ); // Visual studio
#endif
If input value is only 2^n where n - integer, optimal way to find n is to use hash table with perfect hash function. In that case hash function for 32 unsigned integer could be defined as value % 37
template < size_t _Div >
std::array < uint8_t, _Div > build_hash()
{
std::array < uint8_t, _Div > hash_;
std::fill(hash_.begin(), hash_.end(), std::numeric_limits<uint8_t>::max());
for (size_t index_ = 0; index_ < 32; ++index_)
hash_[(1 << index_) % _Div] = index_;
return hash_;
}
uint8_t hash_log2(uint32_t value_)
{
static const std::array < uint8_t, 37 > hash_ = build_hash<37> ();
return hash_[value_%37];
}
Check
int main()
{
for (size_t index_ = 0; index_ < 32; ++index_)
assert(hash_log2(1 << index_) == index_);
}
Your version is just fine, but as you surmised, its O(n) which means it takes one step through the loop for every bit. You can do better. To take it to the next step, try doing the equivalent of a divide and conquer:
unsigned int log2(unsigned int value)
{
unsigned int val = 0 ;
unsigned int mask= 0xffff0000 ;
unsigned int step= 16 ;
while ( value )
{
if ( value & mask ) { val += step ; value &= ~ mask ; }
step /= 2 ;
if ( step ) { mask >>= step ; } else { mask >>= 1 ; }
}
return val ;
}
Since we're just hunting for the highest bit, we start out asking if any bits are on in the upper half of the word. If there are, we can throw away all the lower bits, else we just narrow the search down.
Since the question was marked C++, here's a version using templates that tries to figure out the initial mask & step:
template <typename T>
T log2(T val)
{
T result = 0 ;
T step= ( 4 * sizeof( T ) ) ; // half the number of bits
T mask= ~ 0L - ( ( 1L << ( 4 * sizeof( T )) ) -1 ) ;
while ( val && step )
{
if ( val & mask ) { result += step ; val >>= step ; }
mask >>= ( step + 1) / 2 ;
step /= 2 ;
}
return result ;
}
While performance of either version is going to be a blip on a modern x86 architecture, this has come up for me in embedded solutions, and in the last case where I was solving a bit search very similar to this, even the O(log N) was too slow for the interrupt and we had to use a combo of divide and conquer plus table lookup to squeeze the last few cycles out.
If you KNOW that it is indeed a power of two (which is easy enough to verify),
Try the variant below.
Full description here: http://sree.kotay.com/2007/04/shift-registers-and-de-bruijn-sequences_10.html
//table
static const int8 xs_KotayBits[32] = {
0, 1, 2, 16, 3, 6, 17, 21,
14, 4, 7, 9, 18, 11, 22, 26,
31, 15, 5, 20, 13, 8, 10, 25,
30, 19, 12, 24, 29, 23, 28, 27
};
//only works for powers of 2 inputs
static inline int32 xs_ILogPow2 (int32 v){
assert (v && (v&(v-1)==0));
//constant is binary 10 01010 11010 00110 01110 11111
return xs_KotayBits[(uint32(v)*uint32( 0x04ad19df ))>>27];
}

permutations of N balls in M boxes in C++

I asked a question last week about permutations in C++ (List of combinations of N balls in M boxes in C++).
The answers have helped me a lot but my problem has now changed.
What i would like to do is a translation from this python function to C++, keeping the same order in the result :
def combinations_with_replacement_counts(n, r): #(n-boxes, r-balls)
size = n + r - 1
for indices in itertools.combinations(range(size), n-1):
#print indices
starts = [0] + [index+1 for index in indices]
stops = indices + (size,)
yield tuple(map(operator.sub, stops, starts))
I've no skill in python and despite my readings of the doc, I don't understand this function.
You know python is interpreted, right? You can just type the lines you don't understand directly into python and see what happens ... start with small values first.
I don't understand the itertools.combinations() algorithm
The documentation is here, and includes example output.
Note that the value returned from combinations is lazy, so you need to force evaluation to see it:
>>> import itertools
>>> itertools.combinations(range(4), 2)
<itertools.combinations object at 0x979a964>
>>> list(itertools.combinations(range(4), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
Is it clear what combinations does now? If not, have a play with it.
... and the syntax of "stops = indices + (size,)"
So try it, it won't bite:
>>> indices=list(itertools.combinations(range(4), 2))[0]
>>> size=4
>>> stops=indices + (size,)
>>> indices
(0, 1)
>>> stops
(0, 1, 4)
The syntax (x,) creates a one-element tuple (an invariant sequence - just like a list you can't change but with round parentheses () instead of square ones []). You can use [x] to create a one-element list, but (x) would be ambiguous since round parentheses are also used for other things, like function arguments and grouping.
Concerning map(), ...
Read the doc, have a play with it, it isn't hard.
This C++ code seems to have the same results as your python sample. It is far from the perfect one, still you could understand the algorithm and even use this implementation.
#include <deque>
typedef std::deque<size_t> BoxList;
class Generator {
size_t boxNum, ballNum, ownBox;
Generator* recursive;
public:
~Generator() { if ( recursive == NULL ) delete recursive; }
Generator( size_t boxes, size_t balls ) : boxNum(boxes), ballNum(balls) {
if ( boxes > 1 ) {
recursive = new Generator( boxes-1, balls );
ownBox = 0;
} else {
recursive = NULL;
ownBox = balls;
}
}
BoxList operator()() {
if ( ownBox > ballNum ) throw 1;
if ( boxNum <= 1 ) return BoxList( 1, ownBox++ );
try {
BoxList res = recursive->operator()();
res.push_front( ownBox );
return res;
}
catch(...) {
delete recursive;
ownBox++;
recursive = new Generator( boxNum-1, ballNum-ownBox );
return operator()();
}
}
};
Class interface allows you to use it as a standard generator. Operator () will generate exception when all possible options have been already iterated.
Generator g( boxes, balls );
try{
while( true )
g();
}
catch(...) {}
The Python code you quoted is implementing the algorithm I described in my answer to your question: it's iterating over the possible ways to place r − 1 boxes in n + r − 1 positions, and then making a list of the differences between adjacent positions (which count the number of balls that are swept into that box).