I’m trying to write a method that does the following:
public class GridCounting {
/** Returns the total number of possible routes (paths) from
* (x,y) to (tx,ty).
* There are only three valid kinds of moves:
* Increment x by one.
* Increment x by two.
* Increment y by one.
*
* Hint: You'll need to two base cases.
*/
public static int count(int x,int y, int tx, int ty) {
if (x==tx && y==ty)
return 1;
if (x>tx || y>ty)
return 0;
if (x<tx)
return 1 + count(x+1, y, tx, ty);
if (x<tx) //if x is still less, then we can do another move
return 1 + count(x+2, y, tx, ty);
if (y<ty){
return 1 + count(x, y+1, tx, ty);
}
return 0;
}
}
The trouble that I’m having is that I’m always off by +1. It expects 4 but I give it 5. The confusing part is that if I feed the function count(10,15,10,15), then that still counts as 1 move. I dont know how to account for this.
Also y++ then x++ counts as 1 move, and x++ then y++ counts as another move.
Edit: Fixed code:
public static int count(int x,int y, int tx, int ty) {
if (x==tx && y==ty)
return 1;
if (x>tx || y>ty)
return 0;
if (x<tx)
return count(x+1, y, tx, ty) + count(x+2, y, tx, ty) + count(x,y+1,tx,ty);
if (y<ty) {
return count(x, y+1, tx, ty); // what does this do?
}
return 0;
}
The trouble that I’m having is that I’m always off by +1. It expects 4 but I give it 5.
In position
(x, y)we, generally speaking, have three choices (x+=1,x+=2,y+=1). Each of them produces separate paths and we need to find how many paths there’re in total.So, this part is wrong
That was a hint, let me know if you need more.
Also y++ then x++ counts as 1 move, and x++ then y++ counts as another move.
Well, that sounds like two different paths to me.
edit
Ok,
return count(x + 1, y, tx, ty) + count(x + 2, y, tx, ty) + count(x, y + 1, tx, ty);is all you need.If there’re 3 paths starting with first move
x + 1, 2 paths starting with first movex + 2and 2 paths starting with first movey + 1, then, obviously, there’re3 + 2 + 2paths total.