Sergii Dymchenko

Solving "Vietnam snake" puzzle with constraint logic programming

The puzzle asks to fill empty cells with integer numbers 1..9, using every number only once, such that the equality holds
(order of operations: multiply and divide first, then add and subtract; colon : represents division).

The first line imports interval arithmetic constraint programming library ic.
The puzzle predicate defines the linearized version of the snake puzzle from the picture.

snake constrains all variables in Puzzle to be integers in 1..9 range and pairwise different, forces the Puzzle constraint (using call),
and finds a possible concrete assignment of the variables that satisfy all constraints (using labeling).

main assigns the definition of the puzzle to the Puzzle variable (it's not hard to modify this to input the puzzle definition from the user at runtime),
and then uses Prolog's findall to find and print every solution.

Note that constraint programming is not just brute-force approach: clever algorithms are used behind the scenes to prune the search space.

This version assumes that every intermediate step should result in an integer (# in #= means integrality constraint on the intermediate values).
After running the program we get 20 solutions: