Home > Uncategorized > More on constraint programming in Prolog (spoiler warning)

More on constraint programming in Prolog (spoiler warning)

I just could not resist to publish my prolog solution to problem 68 for project Euler. Prolog and the clpfd library really shines.

:- use_module(library(clpfd)).

threegonring(VARS,N) :-
    VARS = [A1,A2,A3,B1,B2,B3,C1,C2,C3],
    VARS ins 1..6,
    all_distinct([A1,A2,A3,B1,B3,C1]),
    A1+A2+A3 #= N,
    B1+B2+B3 #= N,
    C1+C2+C3 #= N,
    A2 #= C3,
    A3 #= B2,
    B3 #= C2,
    A1 #< B1, A1 #< C1,  % start enumeration from min node
    label(VARS).

fivegonring(VARS,N) :-
    VARS = [A1,A2,A3,B1,B2,B3,C1,C2,C3,D1,D2,D3,E1,E2,E3],
    VARS ins 1..10,
    all_distinct([A1,A2,A3,B1,B3,C1,C3,D1,D3,E1]),
    A1+A2+A3 #= N,
    B1+B2+B3 #= N,
    C1+C2+C3 #= N,
    D1+D2+D3 #= N,
    E1+E2+E3 #= N,
    A2 #= E3,
    A3 #= B2,
    B3 #= C2,
    C3 #= D2,
    D3 #= E2,
    A1 #< B1, A1 #< C1, A1 #< D1, A1 #< E1, % start enumeration from min node
    label(VARS).
   
ints2strh([],[]).
ints2strh([V|VS],[S|SS]) :- number_chars(V,S), ints2strh(VS,SS).
ints2str(VS,SS) :- ints2strh(VS,TEMP), append(TEMP,SS).

problem68(STRVAL) :-
    fivegonring(VARS,_),
    ints2str(VARS,STR),
    length(STR, 16),
    number_chars(STRVAL, STR).

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: