Wednesday, 15 August 2012

Prolog - a program that finds a group of values that sum to a particular value -



Prolog - a program that finds a group of values that sum to a particular value -

i want create programme receives 3 arguments:

list1 of coins example: [5,2,1] value - sum want get list of coins sum particular value - list sub-list of list1 (it's allowed repeat same element , ex: reach 4, can have list [2,2])

so programme should 2 things:

change([5,2,1],4,[2,2]) homecoming yes (cause 2+2 =4)

change([5,2],6,coins) homecoming coins = [2,2,2]

this attempt:

change(_,0,res). change([x|xs],sum,cs):- sum <x, change(xs,sum,cs). change([x|y],sum,[x|res]):- sum>=x, sum2 sum - x, change([x|y],sum2,res).

you need alter res [] lastly argument of first rule. in addition, should add together cutting operator in same rule avoid getting same result multiple times.

change(_, 0, []):-!. change([x|y], sum, [x|res]):- sum >= x, !, % remove cutting operator solutions sum2 sum - x, change([x|y], sum2, res). change([_|xs],sum,cs):- change(xs, sum, cs).

prolog

No comments:

Post a Comment