Brandon Peeples wrote:I tried to do something like (y-x)/2 but that didn't work out well since the value of x keeps increasing.
BEE MBA PMP SCJP-6
Brandon Peeples wrote:I increase x when I make the recursive call. I was thinking that it wouldn't seem right because if I did subtract x from y, it would always give me a different value each time since x increases. I am definitely doing something wrong here. Thank you for your comments Henry. I know your trying to get me to think about the logic more.
That is an interesting idea Jim. Unfortunately, it doesn't meet the requirements. Thanks though
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
I think its also not right because the (x-y)/2 is not midway between x and y, its just the distance between the two numbers..
y/2 is actually only the "midpoint" when x = 0, in fact.. but (I believe.. if I am reading this right) your code is making it look like its correct for x = 1 because you add 1 to it
before you print it out..
Rob Prime wrote:You get the center using the universal averaging code: (x_1 + x_2 + ... + x_n) / n. In this case, it's (x + y) / 2.
If x + y is even this will return you the exact center. If it doesn't it returns you 1/2 left of the center. To get the other side (1/2 right of it) simply add 1/2: (x + y + 1) /2. Now if x + y is even, then (x + y) / 2 and (x + y + 1) / 2 will both return the same value. Use that to your advantage.
Brandon Peeples wrote:I increase x when I make the recursive call. I was thinking that it wouldn't seem right because if I did subtract x from y, it would always give me a different value each time since x increases. I am definitely doing something wrong here. Thank you for your comments Henry. I know your trying to get me to think about the logic more.
That is an interesting idea Jim. Unfortunately, it doesn't meet the requirements. Thanks though
Henry Wong wrote:
Interesting note. For a recursive solution, you actually do not need to calculate the midpoint between x and y. You just need to handle the end conditions or otherwise setup for recursion.
The end conditions are... (1) if x > y (error), (2) if x = y, and (3) if x + 1 = y. And the recursive call is to increase x by 1 and decrease y by 1.
Henry
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions How To Answer Questions
Rob Prime wrote:Henry is right. If x + 1 == y, then x < y. Since only one of each conditions can be true, why not use if-else ifs?
Brandon Peeples wrote:
That makes sense. The problem I'm having is how can I make it stop without being infinite. If x+1 == y... how do I set the limit.
Consider Paul's rocket mass heater. |