# combinatory exploration c++ [closed]

I have n spots with 2 possible positions each.

I would like to explore all of this possibilities in C++ using loops (or something else if there is a better option).

I was thinking of looping from 0 to power(2,n) and convert it to a binary number, for position j, take j-th digit of the binary number use 0 for first possibility and 1 for second possibility.

Is there a better way? Because this way of doing introduces parsing operations and is limited to a binary positions problem, I mean if the problem had more possibilities for each position Ill be in trouble.

• Search the web for the term "backtracking." After that, you might also want to replace recursion by iteration. – Juan M. Bello-Rivas Mar 23 '18 at 11:40

I would generalize this problem the following way (if I understood your problem right):

Create a function bool nextVariant(const &prev_x, &new_x) that is going to generate a new candidate new_x based on the previously explored one prev_x. Then you can organize your code as follows (I made a sketch of a pseudocode using C-style syntaxis)

int main()
{
CandidateType x(0); //initialize the starting candidate (possibility)
do
{
performAnalysis(x); //do whatever you want with the candidate
CandidateType prev_x = x; //maybe you need to save it, maybe not....
bool isThereNext = nextVariant(prev_x,x);
}
while (isThereNext);
}

bool nextVariant(const CandidateType& prev_x, CandidateType& x)
{
if (notReachTheEnd)
{
//your logic to create x from prev_x. (assign x)
return true;
}
else return false;
}


Here, CandidateType is the "type" of your "possibility". You will define it based on your problem, whether it is an N-spot with 2-positions, or something more complicated.

With that, you moved the complication towards generating a new possibility from a previous one, which is usually an easy thing to do. Since I don't know exactly what could be the possible intent of generating those "candidates", I might have introduced certain inefficiencies that could be avoided.