Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Starting state of the stacks
- start_stacks([[n,z],[d,c,m],[p]]).
- % move(Sequence, NumberOfCrates, FromStack, ToStack).
- move(1,1,2,1).
- move(2,3,1,3).
- move(3,2,2,1).
- move(4,1,1,2).
- % Replace element number Counter in the List with Y.
- replace([_|L], 1, Y, [Y|L]).
- replace([X|L], Counter, Y, [X|Result]) :- NextCounter is Counter - 1, replace(L, NextCounter, Y, Result).
- % Stacks
- pop([X|L], X, L).
- push(X, L, [X|L]).
- % Transfer Counter crates from one list to the other
- transfer(0, FromList, ToList, FromList, ToList).
- transfer(Counter, FromList, ToList, FromResult, ToResult) :- pop(FromList, Crate, RestFromList), push(Crate, ToList, IncreasedToList), NextCounter is Counter - 1, transfer(NextCounter, RestFromList, IncreasedToList, FromResult, ToResult).
- % Do a single move
- move_crates(InitialState, NumberOfCrates, FromStack, ToStack, ResultState) :- nth(FromStack, InitialState, FromList), nth(ToStack, InitialState, ToList), transfer(NumberOfCrates, FromList, ToList, ResultFromList, ResultToList), replace(InitialState, FromStack, ResultFromList, BetweenState), replace(BetweenState, ToStack, ResultToList, ResultState).
- % Do a sequence of moves
- execute_move([], State, State).
- execute_move([Counter|L], InState, OutState) :- move(Counter, NumCrates, FromStack, ToStack), move_crates(InState, NumCrates, FromStack, ToStack, BetweenState), execute_move(L, BetweenState, OutState).
- % Find the top crates of every stack
- top_crates([], []).
- top_crates([X|Y], [A|Z]) :- nth(1, X, A), top_crates(Y, Z).
- % Solve the puzzle
- solve(TopCrates) :- findall(X, move(X, _, _, _), CounterList), start_stacks(InState), execute_move(CounterList,InState, OutState), top_crates(OutState, TopCrates).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement