I came across Owen Lacey’s article on optimising Rail Cube and wanted to try the problem in Prolog. Rail Cube is a toy train set whose tracks can run along walls and upside down. The challenge was to build a complete track and give it an interesting shape.
The score to beat when I started was 42. My best layout so far scores 47. I also ran a separate exhaustive count, which found more than 14 billion distinct layouts.
I used the article’s inventory:
| Letter | Piece | Count |
|---|---|---|
| S | Straight | 14 |
| L | Left curve | 4 |
| R | Right curve | 4 |
| I | Inside curve | 8 |
| O | Outside curve | 4 |
| X | Cross | 1 |
A layout must use every piece and form one complete circuit. The train passes through the same X block twice. There are 35 physical pieces, but a complete track string contains 36 letters.
The article gives points for close calls with other parts of the track and for each different orientation the train takes. It subtracts points for the longest side of the bounding box and for repeated pieces. Each piece after the second in a consecutive run counts as a repeat. A knot earns ten points.
score = close calls + orientations - longest side - repeats + knot bonus
This gives the search several competing goals. A smaller box can bring parts of the track closer together. Curves change the train’s orientation, but they also use space that another part of the layout may need.
Owen’s article describes a grid model for the pieces. I used the same model. A train’s pose contains its position, the direction of its floor, and its heading. Six floor directions and four headings on each face give 24 possible orientations.
Each piece changes the pose. These facts describe a straight and a left curve in their local coordinates:
piece(s, [1,0,0]-[[0,0,-1],[1,0,0]]).
piece(l, [1,2,0]-[[0,0,-1],[0,1,0]]).The straight moves one cell forward. The left curve moves one cell forward and two cells left, then points left. Before the program applies a move, it turns these local coordinates to match the incoming floor and heading.
A small recursive relation applies a list of pieces:
place_pieces(End, [], End).
place_pieces(Start, [Piece|Pieces], End) :-
place_piece(Start, Piece, Mid), place_pieces(Mid, Pieces, End).The solver also carries the remaining inventory and the occupied cells. When it tries a piece, it creates the next state. If that choice fails, Prolog backtracking returns to the previous state and tries another piece.
Material cannot overlap other material or the space needed by the train. Two parts of the train’s route can share an empty cell at different times. The second visit to X uses the existing block.
A finished circuit must return to its starting position and orientation. A track that reaches the right cell with the wrong heading does not close.
I wrote the solver with ordinary Prolog recursion and arithmetic. It runs under Scryer Prolog and Trealla, without a constraint library.
A search through every piece order would spend most of its time on tracks that cannot close. I reject a partial track as soon as a rule makes completion impossible.
For the score search, I also keep an upper bound on what a partial track could earn. A branch must still be able to tie or beat the current best. The program checks the cheaper score terms before it does the knot calculation.
The program saves the best layouts and distinct ties as ordinary Prolog terms. It checks these saved tracks again when the next search starts.
This is my best known layout under the article’s scoring rules:
XOISISLISSISSSOSLSLLOSXSRRIROSISIRIS
It fits in a box of 9 by 7 by 6 cubes and forms a trefoil knot.
| Metric | Value | Points |
|---|---|---|
| Longest side | 9 | -9 |
| Close calls | 32 | +32 |
| Different orientations | 15 | +15 |
| Repeats | 1 | -1 |
| Knotted | Yes | +10 |
| Total | 47 |
32 + 15 - 9 - 1 + 10 = 47
An earlier result scored 45 and fit inside a 7 by 7 by 7 box. The 47-point layout uses more space, but its extra close calls make up for that penalty.
The Prolog evaluator checks the 47-point layout directly:
?- evaluate('XOISISLISSISSSOSLSLLOSXSRRIROSISIRIS', Metrics).
Metrics = metrics(47,9,32,15,1,true,size(9,7,6)).The knot check follows the article’s Alexander-polynomial method. This test can miss some nontrivial knots.
I then wanted to know how many valid layouts the whole box could make.
For this question, I ran a separate exhaustive enumeration using the same inventory and collision rules. This search includes layouts of every score. It counts completed layouts in batches and saves their descriptions.
The X block gives a useful way to split the work:
X [first loop] X [second loop]
Each loop returns to the same physical X. The first loop uses part of the inventory, and the second must use exactly what remains.
I split the count into 6,251 jobs. Each job fixes the inventory and first piece of the first loop.
I collect a batch of first loops and search for compatible second loops. Each new piece of a second loop removes first-loop partners that would collide. If no partner remains, I reject that partial second loop immediately.
A finished second loop can fit several first loops. I count all those combinations together. The saved data stores the first loops once, then records the second loops and their compatible partners.
The completed search counted 14,137,062,002 layouts.
I also exported one canonical track string per line to a text file:
$ ls -lh tank/railcube-solutions.txt
-rw-r--r-- 1 bya bya 487G Nov 11 08:47 tank/railcube-solutions.txt
The export contains 523,071,294,074 bytes, about 523 GB or 487 GiB. Each layout takes 37 bytes: 36 piece letters and a newline. This file stores one canonical string per layout.
That number needs a definition of what makes two layouts the same. I count a layout once regardless of:
Distinct mirror images count separately. If a rotation makes a layout match its mirror, it already counts once. Layouts with the same knot type can still have different shapes and count separately.
Each layout gets one chosen track string, its canonical form. Every
cyclic start and reversed description of that layout gives the same
canonical string. I start at X with the train heading +X and its floor
facing -Z. I choose the X traversal whose first loop returns heading +Y.
Of the two travel directions, I keep the shorter first loop. Equal
lengths use the piece order
S < L < R < I < O.
A reversal of travel reverses the letters and exchanges L with R. Both halves reverse together. Independent choices of direction for each half can change the layout.
The Prolog canonicaliser checks a supplied track and prints its canonical form. For example, the 47-point layout above becomes:
$ scryer-prolog canonicalise.pl XOISISLISSISSSOSLSLLOSXSRRIROSISIRIS
XSILISISOLILLSXSORRSRSOSSSISSIRSISIO
Both strings describe the same layout. This gives me a consistent string to compare with the database, even when the input starts elsewhere or runs backwards.
One physical layout can have many different strings. A string may begin halfway through a loop, and the train can travel in either direction.
| Representation | Count |
|---|---|
| Canonical layouts | 14,137,062,002 |
| Strings beginning with X | 56,548,248,008 |
| Strings beginning at any piece | 1,017,868,464,144 |
For this inventory, every layout has 36 distinct cyclic starting points and two distinct travel directions:
14,137,062,002 × 36 × 2 = 1,017,868,464,144
This multiplication needs a symmetry check. A valid X-to-X loop contains an even number of straight pieces. A repeating half or a reversal that gives the same canonical form would require seven straights in each half. Seven is odd, so neither symmetry is possible.
Every layout contributes exactly 72 strings. Other inventories can have fewer forms because of symmetry. A rotation of the whole assembly adds no new strings, since the letters describe relative moves. Mirror layouts are already included in the layout count.
I repeated the full count from a fresh search directory. The second run used batches of 257 first loops instead of 512. Each job ran on one worker, without help from other workers. Both runs finished all 6,251 jobs and returned 14,137,062,002.
I also checked the results in several other ways:
The two full runs share the rule model and parts of the search implementation. Their agreement gives evidence for the count, but it does not replace a separate implementation or a proof of the search rules.
The counting runs do not compute scores, so 47 remains my best known score.
Keep rail-cube2.pl and its knot helper, rail-cube2-knot.pl, in the same folder. Then load the solver:
scryer-prolog rail-cube2.plUse evaluate/2 to check the example above. To start the
score search:
?- run.The Prolog search prints improvements and distinct ties, and saves
them in rail-cube2-solutions.pl.