My experience with day three of exploring Prolog through Seven Languages in Seven Weeks.
I’m feeling a mixture of excitement and scared entering day 3 of Prolog. Today I’m going to see how Prolog can be used to solve problems like Sudoku which is going to be really interesting but I know it’s going to be a lot to get my head around.
I’m sure you’ve seen a Suduko puzzle before. It’s a grid with rows, columns and boxes. Some spaces are filled in and some are blank and it’s your job to fit the numbers so that each row, column and square has one each of all the digits.
The code below shows how you can use Prolog to approach solving it. Check out the comments for an explanation of how it works.
- A board has eight queens.
- Each queen has a row from 1–8 and a column from 1–8.
- No two queens can share the same row.
- No two queens can share the same column.
- No two queens can share the same diagonal (southwest to northeast).
- No two queens can share the same diagonal (northwest to southeast).
Prolog has some input/output features as well. Find print predicates that print out variables. Find a way to use the print predicates to print only successful solutions. How do they work?
Modify the Sudoku solver to work on six-by-six puzzles (squares are 3x2) and 9x9 puzzles. Make the Sudoku solver print prettier solutions.
Same idea as the example above. You can check out my code at github. I haven’t the time at the moment but I’ve seen some really nice examples of people creating general solutions that can handle a range of board sizes. Something to come back to when I get some spare time!
If you’re a puzzle enthusiast, you can get lost in Prolog. If you want to dive deeper into the puzzles I’ve presented, Eight Queens is a good place to start.
Solve the Eight Queens problem by taking a list of queens. Rather than a tuple, represent each queen with an integer, from 1–8. Get the row of a queen by its position in the list and the column by the value in the list.
Check out my code at github