Write a recursive method public static int teddy(int initial, int goal, int incr
ID: 3778658 • Letter: W
Question
Write a recursive method public static int teddy(int initial, int goal, int increment) that simulates a variant of the “Teddy Bears” game between the player (you) and your friend, and returns the minimum number of steps you would need to end up with goal bears. You start with an initial number of stuffed bears. During each step of the game you may perform one of the following actions: (a) ask for and receive increment more bears from your friend; (b) give away increment of your bears to your friend; (c) if you have an even number of bears, you can give exactly half your bears to your friend; or (d) if you have an even number of bears, you can take an additional number of bears equal to half your current number of bears. If you fail to obtain the goal within 10 steps, the method returns -1. You may write helper methods if you like.
Method Call : Return Value
bears(10,4,2) : 2
bears(9,5,3) : -1
bears(15,4,2) : -1
bears(20,3,5) : -1
bears(40,5,6) : 3
bears(30,56,5) : -1
bears(30,55,4) : 3
Return value should be a number! Not a yes or no
Explanation / Answer
## Minor edits
#include <bits/stdc++.h>
using namespace std;
int teddys(int init, int goal, int inc, int steps) {
if(steps>10) return -1;
if(init == goal) return steps;
int incp = teddys(init+inc,goal,inc,steps+1);
int incm = teddys(init-inc,goal,inc,steps+1);
int halfp = -1;
int halfm = -1;
if(init%2 == 0) {
halfp = teddys(init+init/2,goal,inc,steps+1);
halfm = teddys(init-init/2,goal,inc,steps+1);
}
int mini = incp;
if(incp<incm && incp!=-1) {
mini = incp;
} else if(incm != -1) {
mini = incm;
}
if(halfp<mini && halfp!=-1) {
mini = halfp;
} else if(mini == -1 && halfp !=-1) {
mini = halfp;
}
if(halfm<mini && halfm!=-1) {
mini = halfm;
} else if (mini == -1 && halfm != -1) {
mini = halfm;
}
return mini;
}
int teddy(int init, int goal, int inc) {
int incp = teddys(init+inc,goal,inc,1);
int incm = teddys(init-inc,goal,inc,1);
int halfp = -1;
int halfm = -1;
if(init%2 == 0) {
halfp = teddys(init+init/2,goal,inc,1);
halfm = teddys(init-init/2,goal,inc,1);
}
int mini = incp;
if(incp<incm && incp!=-1) {
mini = incp;
} else if(incm != -1) {
mini = incm;
}
if(halfp<mini && halfp!=-1) {
mini = halfp;
} else if(mini == -1 && halfp !=-1) {
mini = halfp;
}
if(halfm<mini && halfm!=-1) {
mini = halfm;
} else if (mini == -1 && halfm != -1) {
mini = halfm;
}
return mini;
}
int main() {
cout<<teddy(30,55,4);
return 0;
}
Recursive method for your problem. Return min-Steps as 2 for teddy(10,4,2).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.