Here's a pretty simple implementation.
Use an array that represents the number of stones plus 2: -1 = a bank of frogs, and N = another bank.
Note the use of access macros A
and J
to allow a negative index:
// frogjmp/frogjmp -- jump frog across river #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #define sysfault(_fmt...) \ do { \ printf(_fmt); \ exit(1); \ } while (0) FILE *xfin; int Dmax; // maximum allowable jump distance int Nmax; // number of stones // list of positions in river: // value is number of rounds needed to uncover a stone as valid jump-to place // -1 -- no stone at position // position is usable as jump-to point iff value is zero // // special index values: // A(-1) is initial frog position (starting river bank) // A(Nmax) is the destination river bank // // the layout of this [and J] are: // frog bank position | stones[Nmax] | other bank position int *Aptr; // river state
Here is the output of the program to enter your example:
D: 3 N: 6 A[0]: 1 A[1]: -1 A[2]: 0 A[3]: 2 A[4]: 3 A[5]: 5 A: 0=1 1=-1 2=0 3=2 4=3 5=5 6=0 dotime: time 0 A: 0=1 1=-1 2=0 3=2 4=3 5=5 6=0 A: 0=1 1=-1 2=0< 3=2 4=3 5=5 6=0 dotime: time 1 A: 0=0 1=-1 2=0 3=1 4=2 5=4 6=0 A: 0=0 1=-1 2=0< 3=1 4=2 5=4 6=0 dotime: time 2 A: 0=0 1=-1 2=0 3=0 4=1 5=3 6=0 A: 0=0 1=-1 2=0< 3=0 4=1 5=3 6=0 A: 0=0 1=-1 2=0< 3=0< 4=1 5=3 6=0 dotime: frog landed at time 2 after 3 jumps A: 0=0 1=-1 2=0< 3=0< 4=1 5=3 6=0<
Update:
The program iterates over time periods, from the initial state to the last round (ie, the highest value of "stone"): T0, T1, ...
In each round, the frog begins on the banks of the river. For a given frog position, the farthest “jump” position is calculated based on the maximum possible range of frog jumps and the current state of the stones in this range. If such a valid transition position is found (that is, the transition point to the initial position has a zero value), the process is repeated until the frog is on the other side.
If no transition position is found (i.e. progress is blocked by non-existent and / or covered stones), the levels of "coverage" of the stone are reduced by one. Then a new round begins.
source share