Search code examples
prologeclipse-clp

How can I include a value to be included inside a coin counter currency program for Prolog?


So thisis a currency system that calculates the fewest amount of coins with 8 different values of coins. Ex: 1 cent, 2, cent, 4 cent, 33 cent, etc... One of the coins must have a value of '5'. So this program is trying to determine what other individual values the other 7 values of coins must have and how many coins for each value has that sums up between 1 and 99 cents.

So my question is, is there a way to write a piece of code without having to manually insert a '5' into the program ( Ex: Values = [_, _, _, _, 5, _, _, _] or Values = [ _, 5, _, _, _, _, _, _] )? So there should be more than one solutions here...

HERE'S THE CODE:

questionSix(Values, Coins) :-
    init_vars(Values, Coins),
    coin_cons(Values, Coins, Pockets),
    clever_cons(Values, Coins),
    Min #= sum(Coins),
    minimize((labeling(Values), labeling(Coins), check(Pockets)), Min).

init_vars(Values, Coins) :-
    length(Values, 8),
    Values = [_, _, _, 5, _, _, _, _],
    Values :: 1..99,
    increasing(Values),
    length(Coins, 8),
    Coins :: 0..99.

increasing(List) :-
    ( fromto(List, [This, Next | Rest], [Next | Rest], [_])
    do
        This #< Next
    ).

clever_cons(Values, Coins) :-
    ( fromto(Values, [V1 | NV], NV, []), 
      fromto(Coins, [N1 | NN], NN, [])
     do
        ( NV = [V2 | _]
            -> N1*V1 #< V2;
            N1*V1 #< 100
        )
    ).

Any help is appreciated. Thank you!


Solution

  • You could just use occurrences from ic_global library (http://eclipseclp.org/doc/bips/lib/ic_global/occurrences-3.html):

     occurrences(5, Values, 1)
    

    Another, more lengthy way, but without ic_global, is to build disjunction of constraints that first value is 5, or the second value is 5, etc. (I haven't tested this code):

    ( foreach(Vi, Values), fromto(0, Eprev, Ecurr, Expr) do
        Ecurr = Eprev or (Vi #= 5) ),
    1 #= eval(Expr)