The Weekly Challenge 187 (Prolog Solutions)

The examples used here are from the weekly challenge problem statement and demonstrate the working solution.

Part 2

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). 

Sample Run

$ 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). 

| ?- magical_triple([1, 1, 3, 2], Triple).

| ?- magical_triple([1, 2, 3, 2], Triple).

Triple = [2,3,2] ? 



The "magical" rules, if not clear from the above code are:

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.


Challenge 187

posted at: 17:25 by: Adam Russell | path: /prolog | permanent link to this entry