% Rail Cube in ISO Prolog.
%
%   ?- run.                    % Search, print and save best tracks and ties.
%   ?- evaluate('...', M).     % Check and score a complete track.
%   ?- solve(Route, Metrics).  % Enumerate tracks by backtracking.
%
% The defaults use the article's inventory and a track with score 42.
% The first crossing uses the positive direction.
% The search stores suffixes of six pieces and checks reachability for
% seven pieces. It prints progress and saves tracks.
% On restart, it checks saved tracks again and starts the search from
% the beginning.
% The exhaustive search uses one thread. The C solver uses a hybrid search.
%
% Metrics = metrics(Score,Side,CloseCalls,Orientations,Repeats,Knot,size(X,Y,Z)).
%
%    ^ ^
%  =(o.o)=
%    m m
% ~byakuren

% ------ configuration ------

inventory(box(14,4,4,8,4)).
start_pose([0,0,0]-[[0,0,-1],[1,0,0]]).
article_track('IRSSIIXLSLSOLLSSOSSIIRISSIXSORROSSSI').
solutions_file('rail-cube2-solutions.pl').

% ------ entry points ------

run :-
    inventory(Box),
    article_track(Article),
    rc_checked(Box, Article, Route, Metrics),
    rc_resume(Box, best(solution(Route,Metrics),[]), Saved),
    rc_start_report(Saved, Initial),
    rc_tables(Tables),
    rc_initial(Box, Start),
    rc_train_bound(Box, TrainBound),
    rc_best_node(Start, Tables, TrainBound, Initial, _).

% These two relations do not print or save anything.
solve(Route, Metrics) :-
    inventory(Box),
    rc_tables(Tables),
    rc_generate(Box, Tables, Route, Node),
    rc_measure(Node, Metrics).

evaluate(Input, Metrics) :-
    rc_route(Input, Route),
    rc_count(Route, Box, 2),
    rc_validate(Box, Route, Node),
    rc_measure(Node, Metrics).

valid_track(Input) :-
    rc_route(Input, Route),
    rc_count(Route, Box, 2),
    rc_validate(Box, Route, _).

% ------ pieces and movement ------

% The floor and heading give one of 24 possible orientations.
% Rotate the incoming displacement, then add it to the current position.
piece(s, [1,0,0]-[[0,0,-1],[1,0,0]]).
piece(l, [1,2,0]-[[0,0,-1],[0,1,0]]).
piece(r, [1,-2,0]-[[0,0,-1],[0,-1,0]]).
piece(i, [1,0,2]-[[1,0,0],[0,0,1]]).
piece(o, [0,0,-1]-[[-1,0,0],[0,0,-1]]).
piece(x, [1,0,0]-[[0,0,-1],[1,0,0]]).

place_piece(Start, Piece, End) :-
    piece(Piece, Delta),
    move(Start, Delta, End).

place_pieces(End, [], End).
place_pieces(Start, [Piece|Pieces], End) :-
    place_piece(Start, Piece, Mid),
    place_pieces(Mid, Pieces, End).

move(Position-Orientation, Delta-[LocalFloor,LocalHeading], End-[Floor,Heading]) :-
    rc_frame(Orientation, Frame),
    rc_transform(Frame, Delta, Displacement),
    rc_add(Position, Displacement, End),
    rc_transform(Frame, LocalFloor, Floor),
    rc_transform(Frame, LocalHeading, Heading).

rc_frame([Floor,Heading], frame(Heading,Left,Up)) :-
    rc_negate(Floor, Up),
    rc_cross(Up, Heading, Left).

rc_transform(frame(D,L,U), [X,Y,Z], [A,B,C]) :-
    D = [Dx,Dy,Dz],
    L = [Lx,Ly,Lz],
    U = [Ux,Uy,Uz],
    A is X*Dx+Y*Lx+Z*Ux,
    B is X*Dy+Y*Ly+Z*Uy,
    C is X*Dz+Y*Lz+Z*Uz.

rc_add([A,B,C], [D,E,F], [X,Y,Z]) :-
    X is A+D,
    Y is B+E,
    Z is C+F.

rc_subtract([A,B,C], [D,E,F], [X,Y,Z]) :-
    X is A-D,
    Y is B-E,
    Z is C-F.

rc_negate([X,Y,Z], [A,B,C]) :-
    A is -X,
    B is -Y,
    C is -Z.

rc_scale([X,Y,Z], K, [A,B,C]) :-
    A is K*X,
    B is K*Y,
    C is K*Z.

rc_dot([A,B,C], [D,E,F], X) :-
    X is A*D+B*E+C*F.

rc_cross([A,B,C], [D,E,F], [X,Y,Z]) :-
    X is B*F-C*E,
    Y is C*D-A*F,
    Z is A*E-B*D.


% ------ occupied cells ------

% Material cells use the material cube at the entrance as their origin.
% The train's anchor is one cube above it.
% Inside curves account for the train within the piece.
rc_footprint(s, [[0,0,0]], [[0,0,1]]).
rc_footprint(x, [[0,0,0]], [[0,0,1]]).
rc_footprint(l, [[0,0,0],[1,0,0],[0,1,0],[1,1,0]],
                [[0,0,1],[1,0,1],[0,1,1],[1,1,1]]).
rc_footprint(r, [[0,0,0],[1,0,0],[0,-1,0],[1,-1,0]],
                [[0,0,1],[1,0,1],[0,-1,1],[1,-1,1]]).
rc_footprint(i, [[0,0,0],[1,0,0],[0,0,1],[1,0,1]], []).
rc_footprint(o, [[0,0,0]], [[0,0,1],[1,0,1],[1,0,0]]).
rc_cells([], _, _, []).
rc_cells([Local|Locals], Frame, Position, [World|Worlds]) :-
    rc_transform(Frame, Local, Delta),
    rc_add(Position, Delta, World),
    rc_cells(Locals, Frame, Position, Worlds).

rc_geometry(Piece, Position-Orientation, Material, Train) :-
    rc_footprint(Piece, M, T),
    rc_frame(Orientation, Frame),
    rc_cells(M, Frame, Position, Ms),
    sort(Ms, Material),
    rc_cells(T, Frame, Position, Ts),
    sort(Ts, Train).


% ------ piece inventory ------

rc_total(box(S,L,R,I,O), N) :-
    N is S+L+R+I+O.

rc_curves(box(_,L,R,I,O), N) :-
    N is L+R+I+O.

rc_inventory_parity(box(S,L,R,I,O)) :-
    0 is S mod 2,
    0 is (L+R+I+O) mod 2.

rc_take(s, box(S,L,R,I,O), C, box(T,L,R,I,O), C) :-
    S > 0,
    T is S-1.
rc_take(l, box(S,L,R,I,O), C, box(S,T,R,I,O), C) :-
    L > 0,
    T is L-1.
rc_take(r, box(S,L,R,I,O), C, box(S,L,T,I,O), C) :-
    R > 0,
    T is R-1.
rc_take(i, box(S,L,R,I,O), C, box(S,L,R,T,O), C) :-
    I > 0,
    T is I-1.
rc_take(o, box(S,L,R,I,O), C, box(S,L,R,I,T), C) :-
    O > 0,
    T is O-1.
rc_take(x, Box, 1, Box, 0).

rc_count([], box(0,0,0,0,0), 0).
rc_count([P|Ps], Box, Crosses) :-
    rc_count(Ps, Rest, C),
    rc_put(P, Rest, C, Box, Crosses).

rc_put(s, box(S,L,R,I,O), C, box(T,L,R,I,O), C) :-
    T is S+1.
rc_put(l, box(S,L,R,I,O), C, box(S,T,R,I,O), C) :-
    T is L+1.
rc_put(r, box(S,L,R,I,O), C, box(S,L,T,I,O), C) :-
    T is R+1.
rc_put(i, box(S,L,R,I,O), C, box(S,L,R,T,O), C) :-
    T is I+1.
rc_put(o, box(S,L,R,I,O), C, box(S,L,R,I,T), C) :-
    T is O+1.
rc_put(x, Box, C, Box, D) :-
    D is C+1.


% ------ search state ------

% Each state holds everything that backtracking must restore:
% node(Pose, Inventory, CrossingsLeft, space(Material,Clearance), Bounds,
%      Orientations, run(Repeats,Last,Previous), ReversePlacedPieces).
% Keep occupied cells in sorted sets.
% States and lookup trees do not change after they are built.

rc_initial(Box, node(Pose,Box,1,Space,Bounds,[Orientation],run(0,x,none),Placed)) :-
    start_pose(Start),
    Start = _-Orientation,
    place_piece(Start, x, Pose),
    Space = space([[0,0,0]],[[0,0,1]]),
    Bounds = bounds(0,0,0,0,0,0),
    Placed = [placed(x,Start,[[0,0,0]],[[0,0,1]])].

rc_cross_return([0,0,0]-[[0,0,-1],[0,Y,0]]) :-
    abs(Y) =:= 1.

rc_extend(Piece,
          node(Pose,Box,C,space(M,T),Bounds,Seen,run(R,Last,Before),Placed),
          Tables,
          node(Next,Rest,D,space(Ms,Ts),NewBounds,NewSeen,run(Q,Piece,Last),
               [placed(Piece,Pose,Material,Train)|Placed])) :-
    rc_take(Piece, Box, C, Rest, D),
    place_piece(Pose, Piece, Next),
    % Reject impossible movement before building lists of occupied cells.
    rc_endpoint(Next, Rest, D, Tables),
    (   Piece == x
    ->  rc_cross_return(Pose),
        Material = [],
        Train = []
    ;   rc_geometry(Piece, Pose, Material, Train),
        rc_disjoint(Material, M),
        rc_disjoint(Material, T),
        rc_disjoint(Train, M)
    ),
    rc_union(Material, M, Ms),
    rc_union(Train, T, Ts),
    rc_grow(Material, Bounds, NewBounds),
    Next = _-Orientation,
    sort([Orientation|Seen], NewSeen),
    ( Piece == Last, Piece == Before -> Q is R+1 ; Q = R ).

rc_complete(node(Pose,box(0,0,0,0,0),0,_,_,_,_,_)) :-
    start_pose(Pose).

rc_remaining(node(_,Box,C,_,_,_,_,_), N) :-
    rc_total(Box, K),
    N is K+C.


% ------ validation ------

% Validate without search tables. Accept either starting direction at X.
rc_validate(Box, [x|Pieces], Node) :-
    rc_initial(Box, Start),
    rc_validate_pieces(Pieces, Start, Node),
    rc_complete(Node).

rc_checked(Box, Input, Route, Metrics) :-
    rc_route(Input, Route),
    rc_count(Route, Box, 2),
    rc_validate(Box, Route, Node),
    rc_measure(Node, Metrics).


% ------ search pruning ------

% Check distance, checkerboard colour, and the number and parity of turns.
% Near the end, check reachability and whether a suffix matches the inventory
% and pose exactly.
% Each piece changes the cube's checkerboard colour.
% Each curve turns the train by one quarter-turn.
rc_endpoint(_, _, _, none).
rc_endpoint(Pose, Box, C, tables(Tails,Reachable,Rotations)) :-
    rc_total(Box, Pieces),
    N is Pieces+C,
    Box = box(S,L,R,I,O),
    Pose = [X,Y,Z]-_,
    Distance is abs(X)+abs(Y)+abs(Z),
    Distance =< S+3*(L+R+I)+O+C,
    0 is (Distance+N) mod 2,
    (   Distance =:= 0
    ->  (   N =:= 0
        ->  start_pose(Pose)
        ;   C =:= 1,
            rc_cross_return(Pose)
        )
    ; true
    ),
    start_pose(Target),
    rc_relative(Pose, Target, Relative),
    Relative = _-Orientation,
    rc_lookup(Orientation, Rotations, Turns),
    rc_curves(Box, Curves),
    Curves >= Turns,
    0 is (Curves-Turns) mod 2,
    ( N =< 7 -> rc_lookup(reach(N,Relative), Reachable, yes) ; true ),
    (   N =< 6
    ->  rc_tail_box(Box, C, KeyBox),
        rc_lookup(tail(KeyBox,Relative), Tails, _)
    ; true
    ).

rc_relative(Position-Orientation, Target-End, LocalPosition-[Floor,Heading]) :-
    rc_frame(Orientation, frame(D,L,U)),
    rc_subtract(Target, Position, Delta),
    rc_in_frame(D, L, U, Delta, LocalPosition),
    End = [F,H],
    rc_in_frame(D, L, U, F, Floor),
    rc_in_frame(D, L, U, H, Heading).

rc_in_frame(D,L,U,V,[X,Y,Z]) :-
    rc_dot(D, V, X),
    rc_dot(L, V, Y),
    rc_dot(U, V, Z).


% ------ route generation ------

% S and X move the train in the same way. Store them under the same key.
% When using a stored suffix, check the actual X position and perpendicular rail.
rc_tail_box(box(S,L,R,I,O), C, box(T,L,R,I,O)) :-
    T is S+C.

rc_cross_suffix(0, Pieces, Pieces).
rc_cross_suffix(1, [s|Pieces], [x|Pieces]).
rc_cross_suffix(1, [P|Pieces], [P|Rest]) :-
    rc_cross_suffix(1, Pieces, Rest).

rc_tables(tables(Tails,Reachable,Rotations)) :-
    rc_tail_table(6, Tails),
    rc_reach_table(7, Reachable),
    rc_rotation_table(Rotations).

% Each choice is a short list of pieces.
% Normal steps and stored suffixes use the same recursion.
% Choose +y at X to avoid searching both orders of the two halves.
rc_choices(Node, tables(Tree,_,_), Choices) :-
    rc_remaining(Node, N),
    (   N > 6
    ->  Choices = [[i],[l],[r],[o],[s],[x]]
    ;   Node = node(Pose,Box,C,_,_,_,_,_),
        start_pose(Target),
        rc_relative(Pose, Target, Relative),
        rc_tail_box(Box, C, KeyBox),
        (   rc_lookup(tail(KeyBox,Relative), Tree, Sequences)
        ->  findall(Seq,
                    ( rc_member(S, Sequences),
                      rc_cross_suffix(C, S, Seq)
                    ),
                    Choices)
        ;   Choices = []
        )
    ).

rc_canonical_step(x, node([0,0,0]-[[0,0,-1],[0,1,0]],_,_,_,_,_,_,_)).
rc_canonical_step(Piece, _) :-
    Piece \== x.

rc_validate_pieces([], Node, Node).
rc_validate_pieces([Piece|Pieces], Node, End) :-
    rc_extend(Piece, Node, none, Next),
    rc_validate_pieces(Pieces, Next, End).

rc_search_sequence([], Node, _, Node).
rc_search_sequence([Piece|Pieces], Node, Tables, End) :-
    rc_canonical_step(Piece, Node),
    rc_extend(Piece, Node, Tables, Next),
    rc_search_sequence(Pieces, Next, Tables, End).

rc_generate(Box, Tables, [x|Pieces], Node) :-
    rc_inventory_parity(Box),
    rc_initial(Box, Start),
    rc_walk(Start, Tables, Pieces, Node).

rc_walk(Node, Tables, Route, End) :-
    (   rc_complete(Node)
    ->  Route = [],
        End = Node
    ;   rc_choices(Node, Tables, Choices),
        rc_member(Pieces, Choices),
        rc_append(Pieces, Rest, Route),
        rc_search_sequence(Pieces, Node, Tables, Next),
        rc_walk(Next, Tables, Rest, End)
    ).


% ------ branch-and-bound search ------

% Pass the best result so far as an ordinary argument through the search tree.
% Each remaining curve can add at most one orientation.
% Neither the longest side nor the repeat count can decrease.
% Close calls cannot exceed the available train cells.
% Add the largest knot bonus to get a safe score bound that includes ties.
rc_train_bound(box(S,L,R,I,O), Bound) :-
    Bound is S+4*L+4*R+I+3*O+1.

rc_upper_bound(node(_,Box,_,_,Bounds,Seen,run(Repeats,_,_),_), TrainBound, Upper) :-
    rc_dimensions(Bounds, _, Side),
    rc_length(Seen, Count),
    rc_curves(Box, Curves),
    Possible is Count+Curves,
    rc_min(24, Possible, Orientations),
    Upper is TrainBound+Orientations-Side-Repeats+10.

rc_best_node(Node, Tables, TrainBound, Best0, Best) :-
    Best0 = best(solution(_,metrics(Score,_,_,_,_,_,_)),_),
    rc_upper_bound(Node, TrainBound, Upper),
    (   Upper < Score
    ->  Best = Best0
    ;   rc_complete(Node)
    ->  rc_cheap_metrics(Node, Cheap),
        Cheap = cheap(Base,_,_,_,_,_,_),
        (   Base+10 >= Score
        ->  rc_finish_metrics(Cheap, Metrics),
            rc_node_route(Node, Route),
            rc_consider(solution(Route,Metrics), Best0, Best, Status),
            rc_report(Status, Route, Metrics)
        ;   Best = Best0
        )
    ;   rc_choices(Node, Tables, Choices),
        rc_best_choices(Choices, Node, Tables, TrainBound, Best0, Best)
    ).

rc_best_choices([], _, _, _, Best, Best).
rc_best_choices([Pieces|Choices], Node, Tables, TrainBound, Best0, Best) :-
    (   rc_search_sequence(Pieces, Node, Tables, Next)
    ->  rc_best_node(Next, Tables, TrainBound, Best0, Best1)
    ;   Best1 = Best0
    ),
    rc_best_choices(Choices, Node, Tables, TrainBound, Best1, Best).

rc_node_route(node(_,_,_,_,_,_,_,Reverse), Route) :-
    rc_reverse(Reverse, Placed),
    rc_placed_route(Placed, Route).

rc_placed_route([], []).
rc_placed_route([placed(P,_,_,_)|Ps], [P|Pieces]) :-
    rc_placed_route(Ps, Pieces).


% ------ scoring ------

% Calculate the cheap metrics first.
% Starting at X breaks any run of repeated pieces at the boundary.
% Count triples as pieces are added to get the repeat count around the
% complete loop.
rc_measure(Node, Metrics) :-
    rc_cheap_metrics(Node, Cheap),
    rc_finish_metrics(Cheap, Metrics).

rc_cheap_metrics(node(_,_,_,_,Bounds,Seen,run(Repeats,_,_),Reverse),
                 cheap(Base,Side,Close,Orient,Repeats,Size,Placed)) :-
    rc_dimensions(Bounds, Size, Side),
    rc_length(Seen, Orient),
    rc_reverse(Reverse, Placed),
    rc_close_calls(Placed, Close),
    Base is Close+Orient-Side-Repeats.

rc_finish_metrics(cheap(Base,Side,Close,Orient,Repeats,Size,Placed),
                  metrics(Score,Side,Close,Orient,Repeats,Knot,Size)) :-
    rc_knot(Placed, Knot),
    ( Knot == true -> Score is Base+10 ; Score = Base ).

rc_grow([], B, B).
rc_grow([[X,Y,Z]|Ps], bounds(A,B,C,D,E,F), Bounds) :-
    rc_min(A, X, G),
    rc_max(B, X, H),
    rc_min(C, Y, I),
    rc_max(D, Y, J),
    rc_min(E, Z, K),
    rc_max(F, Z, L),
    rc_grow(Ps, bounds(G,H,I,J,K,L), Bounds).

rc_dimensions(bounds(A,B,C,D,E,F), size(X,Y,Z), Longest) :-
    X is B-A+1,
    Y is D-C+1,
    Z is F-E+1,
    rc_max(X, Y, XY),
    rc_max(XY, Z, Longest).


% ------ route input ------

rc_route(Input, Pieces) :-
    ground(Input),
    ( atom(Input) -> atom_chars(Input, Chars) ; Chars = Input ),
    rc_read_pieces(Chars, Raw),
    rc_append(Before, [x|After], Raw),
    !,
    rc_append([x|After], Before, Pieces).

rc_read_pieces([], []).
rc_read_pieces([C|Cs], Pieces) :-
    (   char_code(C, N),
        N =< 32
    ->  rc_read_pieces(Cs, Pieces)
    ;   ( rc_letter(P, C) -> true ; piece(C, _), P = C ),
        Pieces = [P|Ps],
        rc_read_pieces(Cs, Ps)
    ).

rc_letter(s, 'S').
rc_letter(l, 'L').
rc_letter(r, 'R').
rc_letter(i, 'I').
rc_letter(o, 'O').
rc_letter(x, 'X').


% ------ close calls ------

rc_close_calls(Placed, Count) :-
    rc_length(Placed, N),
    rc_cross_indices(Placed, 0, Crosses),
    rc_owners(Placed, 0, Crosses, Materials, Trains),
    keysort(Materials, SortedM),
    rc_group_owners(SortedM, MapM),
    rc_tree(MapM, Tree),
    keysort(Trains, SortedT),
    rc_group_owners(SortedT, MapT),
    rc_count_close(MapT, Tree, N, 0, Count).

rc_cross_indices([], _, []).
rc_cross_indices([placed(P,_,_,_)|Ps], I, Indices) :-
    ( P == x -> Indices = [I|Rest] ; Indices = Rest ),
    J is I+1,
    rc_cross_indices(Ps, J, Rest).

rc_owners([], _, _, [], []).
rc_owners([placed(P,Position-Orientation,Mat,Train)|Ps], I, Crosses, Ms, Ts) :-
    ( P == x -> Owners = Crosses ; Owners = [I] ),
    rc_owner_cells(Mat, Owners, M, Mr),
    rc_frame(Orientation, frame(_,_,Up)),
    rc_add(Position, Up, Anchor),
    sort([Anchor|Train], Cells),
    rc_owner_cells(Cells, Owners, T, Tr),
    J is I+1,
    rc_owners(Ps, J, Crosses, Mr, Tr),
    Ms = M,
    Ts = T.

rc_owner_cells([], _, Rest, Rest).
rc_owner_cells([C|Cs], Owners, [C-Owners|Pairs], Rest) :-
    rc_owner_cells(Cs, Owners, Pairs, Rest).

rc_group_owners([], []).
rc_group_owners([Cell-Owners|Rest], [Cell-All|Groups]) :-
    rc_same_owners(Rest, Cell, Owners, All, Tail),
    rc_group_owners(Tail, Groups).

rc_same_owners([C-Os|Rest], Cell, Owners, All, Tail) :-
    C == Cell,
    !,
    rc_union(Os, Owners, Next),
    rc_same_owners(Rest, Cell, Next, All, Tail).
rc_same_owners(Rest, _, Owners, Owners, Rest).

rc_count_close([], _, _, Count, Count).
rc_count_close([Cell-Owners|Cs], Tree, N, A, Count) :-
    ( rc_close_cell(Cell, Owners, Tree, N) -> B is A+1 ; B = A ),
    rc_count_close(Cs, Tree, N, B, Count).

rc_close_cell(Cell, Owners, Tree, N) :-
    rc_neighbour(Delta),
    rc_add(Cell, Delta, Next),
    rc_lookup(Next, Tree, Other),
    rc_nonadjacent(Owners, Other, N),
    !.

rc_neighbour([1,0,0]).
rc_neighbour([-1,0,0]).
rc_neighbour([0,1,0]).
rc_neighbour([0,-1,0]).
rc_neighbour([0,0,1]).
rc_neighbour([0,0,-1]).

rc_nonadjacent([], _, _).
rc_nonadjacent([I|Is], Js, N) :-
    rc_distant(Js, I, N),
    rc_nonadjacent(Is, Js, N).

rc_distant([], _, _).
rc_distant([J|Js], I, N) :-
    D is abs(I-J),
    D > 1,
    D < N-1,
    rc_distant(Js, I, N).


% ------ search tables ------

% Build balanced lookup trees once per query that generates tracks.
% The trees do not change during the search.
rc_tail_table(Limit,Tree) :-
    findall(Key-Seq, rc_tail_entry(Limit,Key,Seq), Entries),
    sort(Entries, Sorted),
    rc_group(Sorted, Groups),
    rc_tree(Groups, Tree).

rc_tail_entry(Limit,tail(Box,End),Pieces) :-
    rc_between(0, Limit, N),
    rc_word(N, Pieces),
    start_pose(Start),
    place_pieces(Start, Pieces, End),
    rc_count(Pieces, Box, 0).

rc_word(0, []).
rc_word(N, [P|Ps]) :-
    N > 0,
    rc_member(P, [s,l,r,i,o]),
    M is N-1,
    rc_word(M, Ps).

rc_group([], []).
rc_group([Key-Value|Rest], [Key-[Value|Values]|Groups]) :-
    rc_same_key(Rest, Key, Values, Tail),
    rc_group(Tail, Groups).

rc_same_key([K-V|Rest], Key, [V|Vs], Tail) :-
    K == Key,
    !,
    rc_same_key(Rest, Key, Vs, Tail).
rc_same_key(Rest, _, [], Rest).

rc_reach_table(Limit,Tree) :-
    start_pose(Start),
    rc_reach_layers(0, Limit, [Start], Entries, []),
    sort(Entries, Sorted),
    rc_tree(Sorted, Tree).

rc_reach_layers(N,Limit,Layer,Entries,Tail) :-
    rc_reach_entries(Layer, N, Entries, Rest),
    (   N < Limit
    ->  findall(Next,
                ( rc_member(Pose, Layer),
                  rc_member(P, [s,l,r,i,o]),
                  place_piece(Pose, P, Next)
                ),
                All),
        sort(All, NewLayer),
        M is N+1,
        rc_reach_layers(M, Limit, NewLayer, Rest, Tail)
    ;   Rest = Tail
    ).

rc_reach_entries([], _, Rest, Rest).
rc_reach_entries([P|Ps], N, [reach(N,P)-yes|Entries], Tail) :-
    rc_reach_entries(Ps, N, Entries, Tail).

rc_rotation_table(Tree) :-
    start_pose(_-Orientation),
    rc_rotation_layers([Orientation-0], [], Entries),
    sort(Entries, Sorted),
    rc_tree(Sorted, Tree).

rc_rotation_layers([], _, []).
rc_rotation_layers([Orientation-Distance|Queue],Seen,Entries) :-
    (   rc_member(Orientation, Seen)
    ->  rc_rotation_layers(Queue, Seen, Entries)
    ;   Entries = [Orientation-Distance|Rest],
        NextDistance is Distance+1,
        findall(Next-NextDistance,
                ( rc_member(P, [l,r,i,o]),
                  place_piece([0,0,0]-Orientation, P, _-Next)
                ),
                Next),
        rc_append(Queue, Next, NewQueue),
        rc_rotation_layers(NewQueue, [Orientation|Seen], Rest)
    ).

rc_tree(Pairs, Tree) :-
    rc_length(Pairs, N),
    rc_tree_n(N, Pairs, [], Tree).

rc_tree_n(0, Pairs, Pairs, empty).
rc_tree_n(N,Pairs,Tail,tree(Key,Value,Left,Right)) :-
    N > 0,
    A is N//2,
    B is N-A-1,
    rc_tree_n(A, Pairs, [Key-Value|Rest], Left),
    rc_tree_n(B, Rest, Tail, Right).

rc_lookup(Key,tree(K,V,Left,Right),Value) :-
    compare(Order, Key, K),
    (   Order == (=)
    ->  Value = V
    ;   Order == (<)
    ->  rc_lookup(Key, Left, Value)
    ;   rc_lookup(Key, Right, Value)
    ).


% ------ saved solutions ------

% Compare scores, then remove duplicate ties using the two cyclic
% descriptions that start at X.
% Keep mirror images and reversed tracks separate.
rc_route_key([x|Pieces], Key) :-
    rc_append(First, [x|Second], Pieces), !,
    rc_append([x|Second], [x|First], Other),
    Original = [x|Pieces],
    ( Original @=< Other -> Key = Original ; Key = Other ).

rc_consider(solution(Route,Metrics), Best0, Best, Status) :-
    Best0 = best(solution(_,metrics(Old,_,_,_,_,_,_)), Keys),
    Metrics = metrics(Score,_,_,_,_,_,_),
    rc_route_key(Route, Key),
    (   Score > Old
    ->  Best = best(solution(Route,Metrics),[Key]),
        Status = improved
    ;   Score =:= Old,
        \+ rc_member(Key, Keys)
    ->  rc_union([Key], Keys, NewKeys),
        Best0 = best(Representative,_),
        Best = best(Representative,NewKeys),
        Status = tie
    ;   Best = Best0,
        Status = unchanged
    ).

rc_start_report(best(solution(Route,Metrics),Keys), Best) :-
    rc_route_key(Route, Key),
    (   rc_member(Key, Keys)
    ->  Best = best(solution(Route,Metrics),Keys),
        rc_show(resumed, Route, Metrics)
    ;   rc_union([Key], Keys, NewKeys),
        Best = best(solution(Route,Metrics),NewKeys),
        rc_report(initial, Route, Metrics)
    ).

% Use only the saved routes as input. Always calculate their metrics again.
rc_resume(Box, Best0, Best) :-
    solutions_file(File),
    catch(open(File, read, Stream),
          error(existence_error(source_sink,_), _),
          Stream = missing),
    (   Stream == missing
    ->  Best = Best0
    ;   catch(( rc_read_best(Stream, Box, Best0, Best),
                close(Stream)
              ),
              Error,
              ( close(Stream),
                throw(Error)
              ))
    ).

rc_read_best(Stream, Box, Best0, Best) :-
    read(Stream, Term),
    (   Term == end_of_file
    ->  Best = Best0
    ;   (   Term = solution(Input,_),
            rc_checked(Box, Input, Route, Metrics)
        ->  rc_consider(solution(Route,Metrics), Best0, Best1, _)
        ;   Best1 = Best0
        ),
        rc_read_best(Stream, Box, Best1, Best)
    ).

rc_report(Status, Route, Metrics) :-
    (   Status == unchanged
    ->  true
    ;   rc_show(Status, Route, Metrics),
        solutions_file(File),
        open(File, append, Stream),
        catch(( write_term(Stream, solution(Route,Metrics), [quoted(true)]),
                put_char(Stream, '.'),
                nl(Stream),
                flush_output(Stream)
              ),
              Error,
              ( close(Stream),
                throw(Error)
              )),
        close(Stream)
    ).

rc_show(Status, Route, Metrics) :-
    write_term(best(Status,Route,Metrics), [quoted(true)]),
    write('.'),
    nl,
    flush_output.


% ------ list and set utilities ------

% These small predicates handle lists and sorted sets without libraries
% specific to a Prolog implementation.
% All set elements are ground (they contain no variables).
rc_member(X, [X|_]).
rc_member(X, [_|Xs]) :-
    rc_member(X, Xs).

rc_append([], Ys, Ys).
rc_append([X|Xs], Ys, [X|Zs]) :-
    rc_append(Xs, Ys, Zs).

rc_reverse(Xs, Ys) :-
    rc_reverse(Xs, [], Ys).

rc_reverse([], Ys, Ys).
rc_reverse([X|Xs], Acc, Ys) :-
    rc_reverse(Xs, [X|Acc], Ys).

rc_length(Xs, N) :-
    rc_length(Xs, 0, N).

rc_length([], N, N).
rc_length([_|Xs], A, N) :-
    B is A+1,
    rc_length(Xs, B, N).

rc_between(A, B, A) :-
    A =< B.
rc_between(A, B, N) :-
    A < B,
    C is A+1,
    rc_between(C, B, N).

rc_union([], Ys, Ys).
rc_union([X|Xs], [], [X|Xs]).
rc_union([X|Xs], [Y|Ys], Union) :-
    compare(Order, X, Y),
    (   Order == (=)
    ->  Union = [X|Rest],
        rc_union(Xs, Ys, Rest)
    ;   Order == (<)
    ->  Union = [X|Rest],
        rc_union(Xs, [Y|Ys], Rest)
    ;   Union = [Y|Rest],
        rc_union([X|Xs], Ys, Rest)
    ).

rc_disjoint([], _).
rc_disjoint([_|_], []).
rc_disjoint([X|Xs], [Y|Ys]) :-
    compare(Order, X, Y),
    (   Order == (<)
    ->  rc_disjoint(Xs, [Y|Ys])
    ;   Order == (>)
    ->  rc_disjoint([X|Xs], Ys)
    ).


% ------ numeric utilities ------

rc_min(A, B, M) :-
    ( A =< B -> M = A ; M = B ).

rc_max(A, B, M) :-
    ( A >= B -> M = A ; M = B ).


% ------ knot scoring ------

% Keep the knot calculation in a separate file to make the search easier to read.
:- include("rail-cube2-knot.pl").
