Prolog : coin change -
i new prolog, trying solve classic coin change problem.
change(m,p,n,d) formula m>=0 , m = p+5*n+10*d here approach
change(m,p,n,d) :- m p+5*n+10*d, p m - (5*n+10*10).
couple of test-cases
change(100,10,8,5). true change(x,10,8,5). x = 100.
however, if try
change(100,p,8,5).
it gives me "arguments not sufficiently instantiated" instead of p = 10. casuing ?
edit : fix code using between predicate between(0,m,p),between(0,m,n),between(0,m,d),m p+5*n+10*d.
use clpfd!
:- use_module(library(clpfd)).
all need express change/4
one equation:
change(money,pennies,nickels,dimes) :- money #= pennies + nickels*5 + dimes*10.
let's run ground query given op!
?- change(100,10,8,5). true.
next up, 4 queries having one variable:
?- change(money,10,8,5). money = 100. ?- change(100,pennies,8,5). pennies = 10. ?- change(100,10,nickels,5). nickels = 8. ?- change(100,10,8,dimes). dimes = 5.
as using clpfd, can ask more general queries, 1 three variables:
?- change(100,pennies,nickels,dimes). 100 #= pennies + 5*nickels + 10*dimes.
note not (yet) enumerate possible combinations... takes 2 steps:
state "all counts non-negative" using
ins/2
:?- [pennies,nickels,dimes] ins 0..sup, change(100,pennies,nickels,dimes). 100 #= pennies + 5*nickels + 10*dimes, pennies in 0..100, nickels in 0..20, dimes in 0..10.
use enumeration predicate
labeling/2
:?- zs = [pennies,nickels,dimes], zs ins 0..sup, change(100,pennies,nickels,dimes), labeling([],zs). pennies = 0 , nickels = 0, dimes = 10 ; pennies = 0 , nickels = 2, dimes = 9 ; pennies = 0 , nickels = 4, dimes = 8 % next 115 answers omitted sake of brevity ; pennies = 90 , nickels = 2, dimes = 0 ; pennies = 95 , nickels = 1, dimes = 0 ; pennies = 100, nickels = 0, dimes = 0 ; false.
Comments
Post a Comment