Given a field
, find the "cheapest" path from (0, 0)
to (3, 3)
. Only the moves up and to the right are allowed.
field([
[1, 1, 1, 1],
[3, 3, 4, 3],
[3, 3, 1, 3],
[3, 3, 1, 1]
]).
nth([A|_], 0, A).
nth([_|T], I, A) :- I #> 0, J #= I - 1, nth(T, J, A).
at(I, J, E) :- field(M), nth(M, I, R), nth(R, J, E).
Here's my recursive solution:
:- use_module(library(clpfd)).
price(0, 0, P) :- at(0, 0, P).
price(I, 0, P) :-
I #=< 3,
I #> 0,
I0 #= I - 1,
price(I0, 0, P0),
at(I, 0, P1),
P #= P0 + P1.
price(0, J, P) :-
J #=< 3,
J #> 0,
J0 #= J - 1,
price(0, J0, P0),
at(0, J, P1),
P #= P0 + P1.
price(I, J, P) :-
I #=< 3,
J #=< 3,
I #> 0,
J #> 0,
I0 #= I - 1,
J0 #= J - 1,
price(I0, J, P0),
price(I, J0, P1),
at(I, J, P2),
P #= min(P0, P1) + P2.
I can run it in different directions:
?- price(3, 3, P).
?- price(I, J, P), I #= 3, J #= 3.
?- price(I, J, P), P #> 10.
- Is it possible to memorize the intermediate steps, and is it strictly necessary?
- Is there a way to use memorization only when
I
andJ
are grounded? - How does CLPFD deal with the fact that there are 4 rules for the predicate
price
? Does the library merge the different rules into one big if? - Is it better to write a single rule
price
withif_
's inside?