Hey everyone. Just for fun I am doing this problem:
Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite set of numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produces that number?
So for example, if the target was 24, the output should be a string:
(((1 * 3) + 5) * 3)
It doesn't have to necessarily be the shortest sequence.
My current code solves this, however the output of the string is causing me an issue. It's outputting the whole iteration, instead of the actual path.
So current, it outputs:
1 +5 +5 +5 +5 +5 *3 *3 *3 *3 +5 +5 *3 *3 *3 +5 +5 +5 +5 +5 *3 *3 *3 *3
It's not removing the false iterations.
My code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
bool find(int current, string &history, int target){
if (current == target){
return true;
}
else if (current > target){
return false;
}
else{
return find(current + 5, history = history + " +5 ", target) || find(current * 3, history = history + " *3 " , target);
}
}
void sequence(int target){
string history = "1";
if (find(1, history, target)){
cout << history << endl;
}
else{
cout << "No Possible Solution" << endl;
}
}
|