Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- geovlahodim@gmail.com
- fact(0, 1).
- fact(N, newF) :- N>0, NewN is N - 1, fact(NewN, F), NewF is N * F.
- sum([], 0).
- sum([H | T], N) :- sum(T, NT), N is H + NT.
- #^ list head+tail
- #with accumulator
- sum2([], Acc, Acc). #<-- result
- sum2([H | T], Acc, Res) :- NewAcc is H + Acc, sum2(T, NewAcc, Res).
- #simplifying the call
- sum3(L, N) :- sum2(L, 0, N).
- rev([],[]).
- rev([H | T], R) :- rev(T, RT), append(RT, [H], R).
- # append(L1, L2, LF) => LF = L1@L2
- anagrams(S1, S2, Moves) :-
- string_to_list(S1, L1),
- reverse(L1, RL1), #reverse is built-in
- string_to_list(S2, L2),
- reverse(L2, RL2),
- length(Moves, _), #Initialy produces []
- solve(RL1, [], [], Moves, RL2), !.
- #after it fails it backtracks and gets Moves=[H]
- #'!' means no backtracking beyond success point
- # works for checking. both lists must exist
- is_permutation_of(L1, L2) :-
- msort(L1, S), #sorting two lists with same items
- msort(L2, S). #should give the same list
- # better way, works for producing aswell
- is_permutation_of2([], []).
- is_permutation_of2(L1, [X|LL2]) :-
- select(X, L1, LL1), # gets an item from L1, returns it on X. LL1 is the remaining
- is_permutation_of(LL1, LL2).
- length([], 0).
- length([_ | T], N) :- length(T, N1, N is N1 + 1.
- #1 C 2
- solve([], [], Goal, [], Goal).
- solve([H|T], [], L2, ['10'|Moves], Goal) :-
- allowed_from('10', Moves),
- solve(T, [H], L2, Moves, Goal).
- solve([H|T], C, L2, ['12'|Moves], Goal) :-
- solve(T, C, [H | L2], Moves, Goal).
- solve(L1, [], [H|T], ['20'|Moves], Goal) :-
- solve(L1, [H], T, Moves, Goal).
- solve(L1, C, [H|T], ['21'|Moves], Goal) :-
- solve([H|L1], C, T, Moves, Goal).
- solve(L1, [H], L2, ['01'|Moves], Goal) :-
- solve([H|L1], [], L2, Moves, Goal).
- solve(L1, [H], L2, ['02'|Moves], Goal) :-
- solve(L1, [], [H|L2], Moves, Goal).
- #Filters allowed move based on previous move
- #we list moves we dont want in sequence
- allowed_from(_, []).
- allowed_from(X, [Y | _]) :- allowed_next(X,Y).
- #listing all allowed consequent moves
- allowed_next('10', Y) :- \+ member(Y, ['10', '01', '02']
- allowed_next('12', Y) :- \+ member(Y, ['12', '01', '02']
- allowed_next('20', Y) :- \+ member(Y, ['12', '21', '02']
- allowed_next('10', Y) :- \+ member(Y, ['10', '01', '02'] #INCOMPLETE
- # '\+' means 'not'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement