Puzzle Aritmetic

prolog_logo
Cod Sursa PROLOG

% Puzzle aritmetic:
% Dandu-se o lista de nr intregi, sa se gaseasca o modalitate
% de inserarea a operatiilor aritmetice (+,-,*,/) astfel incat
% rezultatul sa fie o ecuatie corecta.
% Exemplu:
% Dandu-se lista de numere [2,3,5,7,11] se poate forma ecuatia
% 2-3+5+7 = 11 sau 2 = (3*5+7)/11 sau inca 10.
% equation(L,LT,RT) :-
% L este lista de numere care sunt frunzele in termenii aritmetici LT si RT,
% termenul stang si drept. Ecuatia va avea acelasi rezultat pt termenul stang si
% pentru cel drept.
equation(L,LT,RT) :-
split(L,LL,RL), % descompune lista L in LL si RL
term(LL,LT), % construieste termenul stang
term(RL,RT), % construieste termenul drept
LT =:= RT. % evalueaza si compara termenii
% term(L,T) :-
% L este lista nr care sunt frunze in termenul aritmetic T, de la stanga la dreapta
term([X],X). % un nr este un termen
% term([X],-X). % minus unar
term(L,T) :- % cazul general: termen binar
split(L,LL,RL), % descompune lista L
term(LL,LT), % construieste termenul din stanga
term(RL,RT), % construieste termenul din dreapta
binterm(LT,RT,T). % construieste prin combinare termenul binar
% binterm(LT,RT,T) :-
% T este un termen binar combinat, construit din termenii stang, LT, si drept, RT
binterm(LT,RT,LT+RT).
binterm(LT,RT,LT-RT).
binterm(LT,RT,LT*RT).
binterm(LT,RT,LT/RT) :- RT =\= 0. % evita impartirea la 0
% split(L,L1,L2) :-
% imparte lista L in liste nevide L1 si L2 a.i. concatenate dau L
% append(L1,L2,L3) – concateneaza listele L1 si L2 in L3
append([],L,L).
append([X|L1],L2,[X|L3]) :-
append(L1,L2,L3).
split(L,L1,L2) :- append(L1,L2,L), L1 = [_|_], L2 = [_|_].
% do(L) :- gaseste toate solutiile ecuatiei date
do(L) :-
equation(L,LT,RT),
write(LT),write(‘ = ‘),write(RT),
nl,
fail.
do(_).

Interogari:
| ?- do([2,3,5,7,11]) .
2 = 3-(5+(7-11))
2 = 3-(5+7-11)
2 = 3-5-(7-11)
2 = 3-(5+7)+11
2 = 3-5-7+11
2 = (3*5+7)/11
2*(3-5) = 7-11
2-(3-(5+7)) = 11
2-(3-5-7) = 11
2-3+(5+7) = 11
2-(3-5)+7 = 11
2-3+5+7 = 11
yes
| ?- do([2,3,5,7]) .
yes
| ?- do([2,3,5]) .
2+3 = 5
yes
| ?- do([23,3,5,21,3,14]) .
23 = 3+5*(21-(3+14))
23 = 3+5*(21-3-14)
23+3 = 5-(21-3*14)
23+3 = 5+(21/3+14)
23+3 = 5-21+3*14
23+3 = 5+21/3+14
23-3 = 5*(21-(3+14))
23-3 = 5*(21-3-14)
23+(3-5) = 21/3+14
23+3*5 = 21+(3+14)
23+3*5 = 21+3+14
23+3-5 = 21/3+14
(23-3)/5 = 21-(3+14)
(23-3)/5 = 21-3-14
23+(3-(5-21)) = 3*14
23+(3-5+21) = 3*14
23+(3*5-21) = 3+14
23+3-(5-21) = 3*14
23+(3-5)+21 = 3*14
23+3*5-21 = 3+14
23+3-5+21 = 3*14
23+(3-(5+21/3)) = 14
23+(3-5-21/3) = 14
23+(3*5-(21+3)) = 14
23+(3*5-21-3) = 14
23+3-(5+21/3) = 14
23+(3-5)-21/3 = 14
23+3*5-(21+3) = 14
23+3-5-21/3 = 14
(23+(3-(5-21)))/3 = 14
(23+(3-5+21))/3 = 14
23+(3*5-21)-3 = 14
(23+3-(5-21))/3 = 14
(23+(3-5)+21)/3 = 14
23+3*5-21-3 = 14
(23+3-5+21)/3 = 14
yes

Leave a comment