A challenge by Decision Management Community.
A zoo has four monkeys, during the monkey lunchtime each one ate a different fruit in their favourite resting place. Sam, who doesn’t like bananas, likes sitting on the grass. The monkey who sat on the rock ate the apple. The monkey who ate the pear didn’t sit on the tree branch. Anna sat by the stream but she didn’t eat the pear. Harriet didn’t sit on the tree branch. Mike doesn’t like oranges.
- What kind of fruit each monkey ate?
- Where their favourite resting place was?
So, how to solve this in SQL? It is easy to identify domains, predicates and rules; after that it is straightforward.
Domains
Monkey {Sam, Anna, Harriet} Fruit {banana, pear, apple, orange} Place {grass, rock, tree, stream}
Rules
- Sam does not like bananas.
- Mike does not like oranges.
- Anna didn’t eat the pear.
- Harriet didn’t sit on the tree branch.
- Anna sat by the stream.
- Sam likes sitting on the grass.
- The monkey who sat on the rock ate the apple.
- The monkey who ate the pear didn’t sit on the tree branch.
Solution
The SQL code is easy to follow, it has been tested on PostgreSQL and MS SQL Server.
sol_no monkey place fruit ------------------------------- 1 Anna stream orange 1 Harriet rock apple 1 Mike tree banana 1 Sam grass pear