Solving a Zebra Puzzle using Prolog

captain-americaIn this challenge, we are aiming to get the computer to solve Zebra Puzzles by creating Prolog programs.

Zebra Puzzle?


Zebra Puzzles, also known as Einstein’s Riddles, are a type of logic puzzles where you have to use the clues to make logic deductions in order to solve a given problem.

The most famous Zebra Puzzle was created by Einstein and published in 1962. You can find out more about this puzzle on this page.

Our zebra puzzle will be based on the following scenario:

Three kids went to a superheroes fancy dress birthday party.
The names of the three kids are Ethan, Ali and Anya.
They dressed up as Spiderman, Captain America and Iron Man.
The kids are 6, 8 and 10 years old.

We don’t know how each kid dressed up or how old each kid is but we have the following clues:

  • Anya was dressed up as Spiderman.
  • Ethan was not dressed up as Captain America.
  • The youngest kid dressed up as Spiderman.
  • The kid who is 8 years old dressed up as Captain America.

You can solve this puzzle manually using the following grid:
zebra-grid-puzzle

Prolog?


Prolog is a declarative language that uses a recursive approach to solve logic puzzles. To solve a logic Puzzle using Prolog, a programmer first needs to declare a knowledge base consisting of a collection of facts and rules. This knowledge base can then be used to run queries to try to solve the puzzle.

Setting up the knowledge base


Let’s first focus on declaring the key facts of our puzzle as follows:

We will then implement our clues as rules:

We will add two extra rules that will be used to solve this puzzle and to reinforce the fact that two kids cannot have the same age or the same costume.

Solving the puzzle…

We have created this knowledge base using an online Prolog Environment called Swish:
https://swish.swi-prolog.org/p/Superheroes%20Zebra%20Puzzle.pl

You can now run the following query to solve this puzzle:

Your Turn!


Pick up any Logic Grid Puzzle from this website and build your own set of facts and rules in Prolog to solve your puzzle.

Tagged with: