Monday, June 18, 2012

Seven Languages in Seven Weeks - Prolog Day 3 Self Study

Time to catch up with Seven Languages in Seven Weeks! This is the last chapter on Prolog and here are the tasks:

  • Modify the Sudoku solver to work on six-by-six puzzles (square are 3x2) and 9x9 puzzles
  • Make the Sudoku solver print prettier solutions

Note: since I am using SWI Prolog instead of gprolog as used in the book, there are a few differences:

Here's the solution for six-by-six puzzles:
:- use_module(library(clpfd)).
valid([]).
valid([H|T]) :- all_different(H), valid(T).

sudoku(Puzzle, Solution) :-
 Solution = Puzzle,
 Puzzle = [
  S11, S12, S13, S14, S15, S16,
  S21, S22, S23, S24, S25, S26,
  S31, S32, S33, S34, S35, S36,
  S41, S42, S43, S44, S45, S46,
  S51, S52, S53, S54, S55, S56,
  S61, S62, S63, S64, S65, S66
 ],
 Puzzle ins 1..6,
 Row1 = [S11, S12, S13, S14, S15, S16],
 Row2 = [S21, S22, S23, S24, S25, S26],
 Row3 = [S31, S32, S33, S34, S35, S36],
 Row4 = [S41, S42, S43, S44, S45, S46],
 Row5 = [S51, S52, S53, S54, S55, S56],
 Row6 = [S61, S62, S63, S64, S65, S66],
 Col1 = [S11, S21, S31, S41, S51, S61],
 Col2 = [S12, S22, S32, S42, S52, S62],
 Col3 = [S13, S23, S33, S43, S53, S63],
 Col4 = [S14, S24, S34, S44, S54, S64],
 Col5 = [S15, S25, S35, S45, S55, S65],
 Col6 = [S16, S26, S36, S46, S56, S66],
 Rect1 = [S11, S12, S13, S21, S22, S23],
 Rect2 = [S14, S15, S16, S24, S25, S26],
 Rect3 = [S31, S32, S33, S41, S42, S43],
 Rect4 = [S34, S35, S36, S44, S45, S46],
 Rect5 = [S51, S52, S53, S61, S62, S63],
 Rect6 = [S54, S55, S56, S64, S65, S66],
 valid([Row1, Row2, Row3, Row4, Row5, Row6,
  Col1, Col2, Col3, Col4, Col5, Col6,
  Rect1, Rect2, Rect3, Rect4, Rect5, Rect6]).

pretty_print(Puzzle) :-
 writef("\
 +-----+ +-----+\n\
 |%d %d %d| |%d %d %d|\n\
 |%d %d %d| |%d %d %d|\n\
 +-----+ +-----+\n\n\
 +-----+ +-----+\n\
 |%d %d %d| |%d %d %d|\n\
 |%d %d %d| |%d %d %d|\n\
 +-----+ +-----+\n\n\
 +-----+ +-----+\n\
 |%d %d %d| |%d %d %d|\n\
 |%d %d %d| |%d %d %d|\n\
 +-----+ +-----+", Puzzle).

No comments:

Post a Comment