The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
You are given a list of positive numbers, @n, having at least 3 numbers. Write a script to find the triplets (a, b, c) from the given list that satisfies a set of rules.
magical_triple_sum(Numbers, Triple, TripleSum):- sublist([A, B, C], Numbers), A + B > C, B + C > A, A + C > B, Triple = [A, B, C], sum_list(Triple, TripleSum). magical_triple(Numbers, Triple):- fd_maximize(magical_triple_sum(Numbers, Triple, TripleSum), TripleSum).
$ gprolog --consult-file prolog/ch-2.p | ?- magical_triple([4, 2, 3], Triple). Triple = [4,2,3] ? (1 ms) yes | ?- magical_triple([1, 3, 2], Triple). no | ?- magical_triple([1, 1, 3, 2], Triple). no | ?- magical_triple([1, 2, 3, 2], Triple). Triple = [2,3,2] ? yes
The "magical" rules, if not clear from the above code are:
a + b > c
b + c > a
a + c > b
a + b + c is maximum.
I don't routinely do a lot of constraint programming, but I don't think a smaller solution for this can be written! Indeed, the code here is largely a rewriting of the given rules in slightly modified Prolog form.