/* Kyudoku in Picat. https://www.brainzilla.com/logic/kyudoku/ """ In this logic puzzle you have to choose nine unique numbers (1 through 9) so that each row and column has a sum of 9 or less. ... Each puzzle consists of a 6x6 grid of numbers, where one number is already selected (black circle); """ This program 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,Grid,Hint), println([p=P,hint=Hint]), kyodoku(Grid,Hint, X), N = Grid.len, foreach(I in 1..N) foreach(J in 1..N) if X[I,J] == 1 then printf("%d ",Grid[I,J]) else printf("%w ","_") end end, nl end, nl, fail, nl. go => true. kyodoku(Grid,[Row,Col,Val],X) => N = Grid.len, X = new_array(N,N), X :: 0..1, % The hint X[Row,Col] #= 1, % Exactly 9 distinct numbers sum([X[I,J] : I in 1..N, J in 1..N]) #= 9, all_different_except_0([T : I in 1..N, J in 1..N, T#=X[I,J]*Grid[I,J]]), % Sum of the selected numbers in each row and column must be <= 9 foreach(I in 1..N) sum([X[I,J]*Grid[I,J] : J in 1..N]) #<= 9, sum([X[J,I]*Grid[J,I] : J in 1..N]) #<= 9 end, solve(X). % % Data % From https://www.brainzilla.com/logic/kyudoku/ % /* Very easy _ _ 8 _ _ _ _ _ _ _ 1 7 _ 4 _ _ 3 _ 6 _ _ _ 2 _ _ _ _ 9 _ _ _ 5 _ _ _ _ */ puzzle(0,Grid,Hint) :- Grid = [[5,1,8,4,9,4], [7,3,7,4,1,7], [7,4,9,7,3,7], [6,9,9,1,2,9], [5,3,9,9,3,6], [7,5,9,6,8,6] ], Hint=[3,2,4]. /* Easy 7 _ _ _ _ _ _ 6 _ _ 3 _ _ _ 8 1 _ _ 2 _ _ 5 _ _ _ _ _ _ 4 _ _ _ _ _ _ 9 */ puzzle(1,Grid,Hint) :- Grid = [[7,9,2,7,2,5], [6,6,4,1,3,1], [9,3,8,1,2,4], [2,8,8,5,7,3], [1,6,7,9,4,7], [6,1,6,1,6,9] ], Hint=[4,1,2]. /* Medium 2 _ 5 _ _ _ _ _ _ _ _ 8 _ _ _ 9 _ _ _ _ _ _ 6 _ _ 4 3 _ 1 _ 7 _ _ _ _ _ */ puzzle(2,Grid,Hint) :- Grid = [[2,7,5,2,6,3], [4,2,9,6,5,8], [5,8,8,9,9,1], [1,9,8,4,6,8], [2,4,3,8,1,8], [7,6,6,3,7,8] ], Hint=[2,6,8]. /* Hard _ _ 8 _ _ _ 1 _ _ 3 _ _ _ _ _ _ 7 _ 5 _ _ 4 _ _ _ _ _ _ _ 9 2 6 _ _ _ _ */ puzzle(3,Grid,Hint) :- Grid = [[8,5,8,9,6,6], [1,9,9,3,3,8], [9,7,9,4,7,6], [5,7,3,4,6,8], [7,7,8,2,1,9], [2,6,7,3,7,9] ], Hint=[2,4,3]. /* Very hard _ _ 7 _ _ _ _ 4 _ 5 _ _ _ _ _ _ _ 8 _ _ _ _ 9 _ _ 2 1 3 _ _ 6 _ _ _ _ _ */ puzzle(4,Grid,Hint) :- Grid = [[7,6,7,4,3,6], [3,4,5,5,9,7], [7,7,4,8,1,8], [6,3,4,9,9,2], [5,2,1,3,3,7], [6,9,2,1,7,1] ], Hint=[5,3,1].