Question

Write two clauses in PROLOG that determines if there are three values in a list that sum up to a ...

Write two clauses in PROLOG that determines if there are three values in a list that sum up to a value of N.

The output should be a single true if there exist three values whose sum is N or a single false if there are not.

If there are multiple values whose sum is N then the program should only print true once.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

We just need to find that are there elements present in the list that add up to our sum

If the elements are present then we check if the size of that list is 3 if yes then our answer is true else false.

Code :

1 findthree (Sum, Answer, List) 2 Answer = L,-,-], findAny(Sun, Answer, List). % This is to ensure that our final answer only

Function Call :

findthree (12,Answer, [7,6,5,8,4,2])

Result :

Answer false [6, 4, 2]

Code :

findthree(Sum,Answer,List) :-
Answer = [_,_,_], % This is to ensure that our final answer only
findAny(Sum,Answer,List). % contains three elements

findAny(0,[],_L). % Base Case to ensure Zero sum of elements
findAny(Sum,[H|T1],[H|T2]) :-   
Currsum is Sum-H, % Take the current element in our answer and
findAny(Currsum,T1,T2).   % Make a recursive call to find furthur.

findAny(Sum,Answer,[_H|T]) :- % This will help skipping the elements
dif(Answer,[]), % so that a sublist can be formed
findAny(Sum,Answer,T).

Add a comment
Know the answer?
Add Answer to:
Write two clauses in PROLOG that determines if there are three values in a list that sum up to a ...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT