/* Killer Sudoku in Picat. http://en.wikipedia.org/wiki/Killer_Sudoku """ Killer sudoku (also killer su doku, sumdoku, sum doku, addoku, or samunamupure) is a puzzle that combines elements of sudoku and kakuro. Despite the name, the simpler killer sudokus can be easier to solve than regular sudokus, depending on the solver's skill at mental arithmetic; the hardest ones, however, can take hours to crack. ... The objective is to fill the grid with numbers from 1 to 9 in a way that the following conditions are met: * Each row, column, and nonet contains each number exactly once. * The sum of all numbers in a cage must match the small number printed in its corner. * No number appears more than once in a cage. (This is the standard rule for killer sudokus, and implies that no cage can include more than 9 cells.) In 'Killer X', an additional rule is that each of the long diagonals contains each number once. """ Here we solve the problem from the Wikipedia page, also shown here http://en.wikipedia.org/wiki/File:Killersudoku_color.svg The output is: 2 1 5 6 4 7 3 9 8 3 6 8 9 5 2 1 7 4 7 9 4 3 8 1 6 5 2 5 8 6 2 7 4 9 3 1 1 4 2 5 9 3 8 6 7 9 7 3 8 1 6 4 2 5 8 2 1 7 3 9 5 4 6 6 5 9 4 2 8 7 1 3 4 3 7 1 6 5 2 8 9 Compare with killer_sudoku.pi. In this current model there is an alternative way of representing the hints, namely as segments in the segment grid. This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util,cp. main => go. go => problem(1,N,NumSegments,Segments,SegmentSums), X = new_array(N,N), X :: 1..N, % Standard Sudoku constraints % rows and columns foreach(I in 1..N) all_different([X[I,J] : J in 1..N]), all_different([X[J,I] : J in 1..N]) end, % blocks foreach(I in 0..2, J in 0..2) all_different([X[R,C] : R in I*3+1..I*3+3, C in J*3+1..J*3+3] ) end, % Handle the segments foreach(P in 1..NumSegments) SegmentSums[P] #= sum([X[I,J] : I in 1..N, J in 1..N, Segments[I,J] == P]) end, solve(X), foreach(Row in X) println(Row.to_list) end, nl, fail, nl. % The Wikipedia problem instance (op.cit) % For a better view of the problem, see % http://en.wikipedia.org/wiki/File:Killersudoku_color.svg problem(1,N,NumSegments,Segments,SegmentSums) => N = 9, NumSegments = 29, Segments = chunks_of([ 1, 1, 2, 2, 2, 3, 4, 5, 6, % 1 7, 7, 8, 8, 3, 3, 4, 5, 6, % 2 7, 7, 9, 9, 3,10,11,11, 6, % 3 13,14,14, 9,15,10,11,12, 6, % 4 13,16,16,17,15,10,12,12,18, % 5 19,16,20,17,15,21,22,22,18, % 6 19,20,20,17,23,21,21,24,24, % 7 19,25,26,23,23,27,27,24,24, % 8 19,25,26,23,28,28,28,29,29 % 9 ],9), SegmentSums = [ 3, % 1 15, % 2 22, % 3 4, % 4 16, % 5 15, % 6 25, % 7 17, % 8 9, % 9 8, % 10 20, % 11 17, % 12 6, % 13 14, % 14 17, % 15 13, % 16 20, % 17 12, % 18 27, % 19 6, % 20 20, % 21 6, % 22 10, % 23 14, % 24 8, % 25 16, % 26 15, % 27 13, % 28 17 % 29 ].