Advertisement
FubFubFub

Day 5

Dec 5th, 2022
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Prolog 1.68 KB | Source Code | 0 0
  1. % Starting state of the stacks
  2. start_stacks([[n,z],[d,c,m],[p]]).
  3.  
  4. % move(Sequence, NumberOfCrates, FromStack, ToStack).
  5. move(1,1,2,1).
  6. move(2,3,1,3).
  7. move(3,2,2,1).
  8. move(4,1,1,2).
  9.  
  10. % Replace element number Counter in the List with Y.
  11. replace([_|L], 1, Y, [Y|L]).
  12. replace([X|L], Counter, Y, [X|Result]) :- NextCounter is Counter - 1, replace(L, NextCounter, Y, Result).
  13.  
  14. % Stacks
  15. pop([X|L], X, L).
  16. push(X, L, [X|L]).
  17.  
  18. % Transfer Counter crates from one list to the other
  19. transfer(0, FromList, ToList, FromList, ToList).
  20. transfer(Counter, FromList, ToList, FromResult, ToResult) :- pop(FromList, Crate, RestFromList), push(Crate, ToList, IncreasedToList), NextCounter is Counter - 1, transfer(NextCounter, RestFromList, IncreasedToList, FromResult, ToResult).
  21.  
  22. % Do a single move
  23. 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).
  24.  
  25. % Do a sequence of moves
  26. execute_move([], State, State).
  27. execute_move([Counter|L], InState, OutState) :- move(Counter, NumCrates, FromStack, ToStack), move_crates(InState, NumCrates, FromStack, ToStack, BetweenState), execute_move(L, BetweenState, OutState).
  28.  
  29. % Find the top crates of every stack
  30. top_crates([], []).
  31. top_crates([X|Y], [A|Z]) :- nth(1, X, A), top_crates(Y, Z).
  32.  
  33. % Solve the puzzle
  34. 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