A prolog program that calculate 24

An idea just came up to me that using prolog to calculate 24.

Here is the code:


calc24(Lst, X, Y, Z) :-
    length(Lst, 4),
    reduce(Lst, X),
    reduce(X, Y),
    reduce(Y, Z),
    nth0(0, Z, 24).

reduce(Lst, X) :- nchoose(Lst, A, B, C), Y is A+B, append([Y], C, X).
reduce(Lst, X) :- nchoose(Lst, A, B, C), Y is A-B, append([Y], C, X).
reduce(Lst, X) :- nchoose(Lst, A, B, C), Y is A*B, append([Y], C, X).
reduce(Lst, X) :- nchoose(Lst, A, B, C),
		  B \= 0,
		  Y is A rdiv B,
		  append([Y], C, X).

nchoose(Lst, A, B, C) :-
    length(Lst, Len),
    Len > 2,
    nth0(0, Lst, A),
    select(A, Lst, Lst_rem),
    nchoose1(Lst_rem, B, C).

nchoose(Lst, A, B, C) :-
    length(Lst, Len),
    Len > 2,
    nth0(0, Lst, X),
    select(X, Lst, Lst_rem),
    nchoose(Lst_rem, A, B, D),
    append([X], D, C).

nchoose(Lst, A, B, []) :-
    length(Lst, 2),
    nth0(0, Lst, A),
    nth0(1, Lst, B).

nchoose1(Lst, B, []) :-
    length(Lst, 1),
    nth0(0, Lst, B).

nchoose1(Lst, B, C) :-
    length(Lst, Len),
    Len > 1,
    nth0(0, Lst, B),
    select(B, Lst, C).

nchoose1(Lst, B, C) :-
    length(Lst, Len),
    Len > 1,
    nth0(0, Lst, X),
    select(X, Lst, Lst_rem),
    nchoose1(Lst_rem, B, D),
    append([X], D, C).


equal_list(L1, L2) :-
    length(L1, Len),
    length(L2, Len),
    Len > 1,
    nth0(0, L1, E1),
    member(E1, L2),
    select(E1, L1, L1_rem),
    select(E1, L2, L2_rem),
    equal_list(L1_rem, L2_rem).

equal_list(L1, L2) :-
    length(L1, 1),
    length(L2, 1),
    nth0(0, L1, X),
    nth0(0, L2, X).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.