/* Suguru puzzle in Picat. From https://krazydad.com/suguru/ """ Suguru, also known as Tectonics or Number Blocks were invented in Japan by Naoki Inaba, a very prolific puzzle designer. ... Suguru puzzles are quite different than Sudoku, so you'll want to read these rules carefully: You'll see that the grid is subdivided into containers or cages, each of which is 1 to 5 cells in size. You need to fill each container with unique digits, counting up from 1. So for example a 2-square container contains the numbers 1 and 2. A 5-square container contains the numbers from 1 to 5. Adjacent (touching) cells may never contain the same number, and this includes diagonally adjacent cells. That's it! """ Compared to suguru.pi this model has a different representation of the cages. This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. main => go. go ?=> puzzle(P,X,Cages), println(puzzle=P), suguru(X,Cages), foreach(Row in X) println(Row) end, nl, fail, nl. go => true. % % Solve a Suguru puzzle % suguru(X,Cages) => Rows = X.len, Cols = X[1].len, NumCages = max(Cages.flatten), % % Numbers in the cages must be distinct. % foreach(C in 1..NumCages) T = [X[I,J] : I in 1..Rows, J in 1..Cols, Cages[I,J] == C], Len = T.len, T :: 1..Len, all_distinct(T) end, % % All neighbours are distinct, including diagonals. % foreach(I in 1..Rows, J in 1..Cols) foreach(A in -1..1, membchk(I+A, 1..Rows), B in -1..1, membchk(J+B,1..Cols), (A != 0 ; B != 0)) X[I,J] #!= X[I+A,J+B] end end, solve($[],X). /* The first example at https://krazydad.com/suguru/ (5x5) Solution: [1,3,2,5,1] [4,5,4,3,2] [1,3,2,1,4] [2,5,4,5,3] [4,3,1,2,1] */ puzzle(1,Grid,Cages) :- Grid = [[1,_,_,5,_], [_,_,_,_,_], [1,_,2,_,4], [_,_,_,_,_], [_,3,_,_,_] ], Cages = [ [1,1,1,2,2], [1,3,3,4,2], [3,3,4,4,2], [3,4,4,5,2], [5,5,5,5,6] ]. /* From Alireza Soroudi: "Suguru Puzzle in CP" https://www.linkedin.com/pulse/suguru-puzzle-cp-alireza-soroudi-sgzke/ https://github.com/OptimizationExpert/Pyomo/blob/main/Suguru_CP.ipynb (7x10) Solution: [1,5,4,1,5,1,5,2,1] [3,2,3,2,3,2,4,3,5] [4,1,4,5,4,1,5,1,4] [5,2,3,1,3,2,3,2,3] [4,1,5,2,4,1,5,1,4] [2,3,4,3,5,3,4,3,2] [4,1,2,1,2,1,2,1,5] */ puzzle(2,Grid,Cages) :- Grid = [[1,_,_,1,_,_,_,_,_], [_,2,_,_,_,_,_,3,_], [4,_,4,_,_,_,_,_,4], [_,_,_,1,_,_,_,_,_], [4,_,5,_,4,_,5,_,_], [_,_,_,_,_,_,_,3,_], [_,_,_,_,2,_,_,_,5] ], Cages = [[ 1, 1, 2, 2, 2, 3, 3, 4, 5], [ 1, 1, 2, 2, 3, 3, 4, 4, 5], [ 1, 6, 7, 7, 3, 4, 4, 8, 5], [ 6, 6, 6, 7, 7, 9, 9, 5, 5], [ 6,10,10, 7,11, 9, 9,12,13], [14,14,10,10,11,11, 9,13,13], [14,14,10,11,11,15,15,13,13] ].