These are Haskell translations of [http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems].

+

This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems].

If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields.

If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields.

By definition/data representation no two queens can occupy the same column. "try `elem` alreadySet" checks for a queen in the same row, "abs(try - q) == col" checks for a queen in the same diagonal.

+

[[99 questions/Solutions/90 | Solutions]]

−

This is a modification of a function I wrote when I was just learning haskell, so there's certainly much to improve here! For one thing there is speedup potential in caching "blocked" rows, columns and diagonals.

Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once?

+

Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? A set of solutions is given on the [[The_Knights_Tour]] page.

Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour).

Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour).

This is just the naive backtracking approach. I tried a speedup using Data.Map, but the code got too verbose to post.

== Problem 92 ==

== Problem 92 ==

Line 149:

Line 71:

Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been solved since.

Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been solved since.

−

http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p92a.gif

+

https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/p92a.gif

Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible.

Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible.

Line 157:

Line 79:

Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured below?

Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured below?

This is a simple brute-force solver. This function will permute all assignments of the different node numbers and will then verify that all of the edge differences are different. This code uses the List Monad.

== Problem 93 ==

== Problem 93 ==

Line 187:

Line 100:

Example in Haskell:

Example in Haskell:

−

<pre>

+

−

P93> putStr $ unlines $ puzzle [2,3,5,7,11]

+

<haskell>

+

P93> mapM_ putStrLn $ puzzle [2,3,5,7,11]

2 = 3-(5+7-11)

2 = 3-(5+7-11)

2 = 3-5-(7-11)

2 = 3-5-(7-11)

Line 199:

Line 113:

2-(3-5)+7 = 11

2-(3-5)+7 = 11

2-3+5+7 = 11

2-3+5+7 = 11

−

</pre>

+

</haskell>

+

The other two solutions alluded to in the problem description are dropped by the Haskell solution as trivial variants:

The other two solutions alluded to in the problem description are dropped by the Haskell solution as trivial variants:

+

<pre>

<pre>

2 = 3-(5+(7-11))

2 = 3-(5+(7-11))

Line 206:

Line 122:

</pre>

</pre>

−

Solution:

+

[[99 questions/Solutions/93 | Solutions]]

−

<haskell>

+

−

module P93 where

+

−

import Control.Monad

−

import Data.List

−

import Data.Maybe

−

−

type Equation = (Expr, Expr)

−

data Expr = Const Integer | Binary Expr Op Expr

−

deriving (Eq, Show)

−

data Op = Plus | Minus | Multiply | Divide

−

deriving (Bounded, Eq, Enum, Show)

−

type Value = Rational

−

−

-- top-level function: all correct equations generated from the list of

On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five. Write a predicate full-words/1 to print (non-negative) integer numbers in full words.

In a certain programming language (Ada) identifiers are defined by the syntax diagram below.

+

−

+

−

http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p96.gif

+

−

+

−

Transform the syntax diagram into a system of syntax diagrams which do not contain loops; i.e. which are purely recursive. Using these modified diagrams, write a predicate identifier/1 that can check whether or not a given string is a legal identifier.

The functions <tt>hyphen</tt> and <tt>alphas</tt> correspond to states in the automaton at the start of the loop and before a compulsory alphanumeric, respectively.

+

−

+

−

Here is a solution that parses the identifier using Parsec, a parser library that is commonly used in Haskell code:

+

−

<haskell>

+

−

isRight (Right _) = True

+

−

isRight (Left _) = False

+

−

+

−

identifier x = isRight $ parse parser "" x where

+

−

parser = letter >> many (optional (char '-') >> alphaNum)

+

−

</haskell>

+

−

== Problem 97 ==

+

−

+

−

(**) Sudoku

+

−

+

−

Sudoku puzzles go like this:

+

−

+

−

<pre>

+

−

Problem statement Solution

+

−

+

−

. . 4 | 8 . . | . 1 7 9 3 4 | 8 2 5 | 6 1 7

+

−

| | | |

+

−

6 7 . | 9 . . | . . . 6 7 2 | 9 1 4 | 8 5 3

+

−

| | | |

+

−

5 . 8 | . 3 . | . . 4 5 1 8 | 6 3 7 | 9 2 4

+

−

--------+---------+-------- --------+---------+--------

+

−

3 . . | 7 4 . | 1 . . 3 2 5 | 7 4 8 | 1 6 9

+

−

| | | |

+

−

. 6 9 | . . . | 7 8 . 4 6 9 | 1 5 3 | 7 8 2

+

−

| | | |

+

−

. . 1 | . 6 9 | . . 5 7 8 1 | 2 6 9 | 4 3 5

+

−

--------+---------+-------- --------+---------+--------

+

−

1 . . | . 8 . | 3 . 6 1 9 7 | 5 8 2 | 3 4 6

+

−

| | | |

+

−

. . . | . . 6 | . 9 1 8 5 3 | 4 7 6 | 2 9 1

+

−

| | | |

+

−

2 4 . | . . 1 | 5 . . 2 4 6 | 3 9 1 | 5 7 8

+

−

</pre>

+

−

+

−

Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square.

+

−

+

−

Solutions: see [[Sudoku]]

+

−

+

−

== Problem 98 ==

+

−

+

−

(***) Nonograms

+

−

+

−

Around 1994, a certain kind of puzzle was very popular in England. The "Sunday Telegraph" newspaper wrote: "Nonograms are puzzles from Japan and are currently published each week only in The Sunday Telegraph. Simply use your logic and skill to complete the grid and reveal a picture or diagram." As a Prolog programmer, you are in a better situation: you can have your computer do the work! Just write a little program ;-).

+

−

+

−

The puzzle goes like this: Essentially, each row and column of a rectangular bitmap is annotated with the respective lengths of its distinct strings of occupied cells. The person who solves the puzzle must complete the bitmap given only these lengths.

+

−

+

−

Problem statement: Solution:

+

−

+

−

|_|_|_|_|_|_|_|_| 3 |_|X|X|X|_|_|_|_| 3

+

−

|_|_|_|_|_|_|_|_| 2 1 |X|X|_|X|_|_|_|_| 2 1

+

−

|_|_|_|_|_|_|_|_| 3 2 |_|X|X|X|_|_|X|X| 3 2

+

−

|_|_|_|_|_|_|_|_| 2 2 |_|_|X|X|_|_|X|X| 2 2

+

−

|_|_|_|_|_|_|_|_| 6 |_|_|X|X|X|X|X|X| 6

+

−

|_|_|_|_|_|_|_|_| 1 5 |X|_|X|X|X|X|X|_| 1 5

+

−

|_|_|_|_|_|_|_|_| 6 |X|X|X|X|X|X|_|_| 6

+

−

|_|_|_|_|_|_|_|_| 1 |_|_|_|_|X|_|_|_| 1

+

−

|_|_|_|_|_|_|_|_| 2 |_|_|_|X|X|_|_|_| 2

+

−

1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3

+

−

2 1 5 1 2 1 5 1

+

−

+

−

+

−

For the example above, the problem can be stated as the two lists [[3],[2,1],[3,2],[2,2],[6],[1,5],[6],[1],[2]] and [[1,2],[3,1],[1,5],[7,1],[5],[3],[4],[3]] which give the "solid" lengths of the rows and columns, top-to-bottom and left-to-right, respectively. Published puzzles are larger than this example, e.g. 25 x 20, and apparently always have unique solutions.

This is a solution done for simplicity rather than performance. It's SLOOOOW.

+

−

+

−

It builds all combinations of blocks in a row (stolen from solution 2 :) and then builds all combinations of rows. The resulting columns are then contracted into the short block block form and the signature compared to the target.

+

−

+

−

We can make the search much faster (but more obscure) by deducing the values of as many squares as possible before guessing, as in this solution:

+

−

<haskell>

+

−

module Nonogram where

+

−

+

−

import Control.Monad

+

−

import Data.List

+

−

import Data.Maybe

+

−

+

−

data Square = Filled | Blank | Unknown

+

−

deriving (Eq, Show)

+

−

type Row = [Square]

+

−

type Grid = [Row]

+

−

+

−

-- Print the first solution (if any) to the nonogram

+

−

nonogram :: [[Int]] -> [[Int]] -> String

+

−

nonogram rs cs = case solve rs cs of

+

−

[] -> "Inconsistent\n"

+

−

(grid:_) -> showGrid rs cs grid

+

−

+

−

-- All solutions to the nonogram

+

−

solve :: [[Int]] -> [[Int]] -> [Grid]

+

−

solve rs cs = [grid' |

+

−

-- deduce as many squares as we can

+

−

grid <- maybeToList (deduction rs cs),

+

−

-- guess the rest, governed by rs

+

−

grid' <- zipWithM (rowsMatching nc) rs grid,

+

−

-- check each guess against cs

+

−

map contract (transpose grid') == cs]

+

−

where nc = length cs

+

−

contract = map length . filter (\(x:_) -> x==Filled) . group

+

−

+

−

-- A nonogram with all the values we can deduce

+

−

deduction :: [[Int]] -> [[Int]] -> Maybe Grid

+

−

deduction rs cs = converge step init

+

−

where nr = length rs

+

−

nc = length cs

+

−

init = replicate nr (replicate nc Unknown)

+

−

step = (improve nc rs . transpose) <.> (improve nr cs . transpose)

+

−

improve n = zipWithM (common n)

+

−

(g <.> f) x = f x >>= g

+

−

+

−

-- repeatedly apply f until a fixed point is reached

+

−

converge :: (Monad m, Eq a) => (a -> m a) -> a -> m a

+

−

converge f s = do

+

−

s' <- f s

+

−

if s' == s then return s else converge f s'

+

−

+

−

-- common n ks partial = commonality between all possible ways of

+

−

-- placing blocks of length ks in a row of length n that match partial.

We build up knowledge of which squares must be filled and which must be blank, until we can't make any more deductions.

+

−

Some puzzles cannot be completely solved in this way, so then we guess values by the same method as the first solution for any remaining squares.

+

−

+

−

== Problem 99 ==

+

−

+

−

(***) Crossword puzzle

+

−

+

−

Given an empty (or almost empty) framework of a crossword puzzle and a set of words. The problem is to place the words into the framework.

+

−

+

−

http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99.gif

+

−

+

−

The particular crossword puzzle is specified in a text file which first lists the words (one word per line) in an arbitrary order. Then, after an empty line, the crossword framework is defined. In this framework specification, an empty character location is represented by a dot (.). In order to make the solution easier, character locations can also contain predefined character values. The puzzle above is defined in the file [http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99a.dat p99a.dat], other examples are [http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99b.dat p99b.dat] and [http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99d.dat p99d.dat]. There is also an example of a puzzle ([http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99c.dat p99c.dat]) which does not have a solution.

+

−

+

−

Words are strings (character lists) of at least two characters. A horizontal or vertical sequence of character places in the crossword puzzle framework is called a site. Our problem is to find a compatible way of placing words onto sites.

+

−

+

−

Hints: (1) The problem is not easy. You will need some time to thoroughly understand it. So, don't give up too early! And remember that the objective is a clean solution, not just a quick-and-dirty hack!

+

−

+

−

(2) Reading the data file is a tricky problem for which a solution is provided in the file [http://www.hta-bi.bfh.ch/~hew/informatik3/prolog/p-99/p99-readfile.pl p99-readfile.pl]. See the predicate read_lines/2.

+

−

+

−

(3) For efficiency reasons it is important, at least for larger puzzles, to sort the words and the sites in a particular order. For this part of the problem, the solution of P28 may be very helpful.

This is a simplistic solution with no consideration for speed. Especially sites and words aren't ordered as propesed in (3) of the problem. Words of the correct length are naively tried for all blanks (without heuristics) and the possible solutions are then backtracked.

+

−

+

−

To test for collisions, all (Word, Site) pairs are merged to result in a list of (Coord, Char) elements which represent all letters placed so far. If all (two) characters of the same coordinate are identical, there exist no collisions between words.

+

[[Category:Tutorials]]

[[Category:Tutorials]]

Latest revision as of 20:38, 22 November 2013

If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in Haskell>,<solution in haskell> and <description of implementation> fields.

This is a classical problem in computer science. The objective is to place eight queens on a chessboard so that no two queens are attacking each other; i.e., no two queens are in the same row, the same column, or on the same diagonal.

Hint: Represent the positions of the queens as a list of numbers 1..N. Example: [4,2,7,3,6,8,5,1] means that the queen in the first column is in row 4, the queen in the second column is in row 2, etc. Use the generate-and-test paradigm.

Another famous problem is this one: How can a knight jump on an NxN chessboard in such a way that it visits every square exactly once? A set of solutions is given on the The_Knights_Tour page.

Hints: Represent the squares by pairs of their coordinates of the form X/Y, where both X and Y are integers between 1 and N. (Note that '/' is just a convenient functor, not division!) Define the relation jump(N,X/Y,U/V) to express the fact that a knight can jump from X/Y to U/V on a NxN chessboard. And finally, represent the solution of our problem as a list of N*N knight positions (the knight's tour).

There are two variants of this problem:

find a tour ending at a particular square

find a circular tour, ending a knight's jump from the start (clearly it doesn't matter where you start, so choose (1,1))

Several years ago I met a mathematician who was intrigued by a problem for which he didn't know a solution. His name was Von Koch, and I don't know whether the problem has been solved since.

Anyway the puzzle goes like this: Given a tree with N nodes (and hence N-1 edges). Find a way to enumerate the nodes from 1 to N and, accordingly, the edges from 1 to N-1 in such a way, that for each edge K the difference of its node numbers equals to K. The conjecture is that this is always possible.

For small trees the problem is easy to solve by hand. However, for larger trees, and 14 is already very large, it is extremely difficult to find a solution. And remember, we don't know for sure whether there is always a solution!

Write a predicate that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured below?

Given a list of integer numbers, find a correct way of inserting arithmetic signs (operators) such that the result is a correct equation. Example: With the list of numbers [2,3,5,7,11] we can form the equations 2-3+5+7 = 11 or 2 = (3*5+7)/11 (and ten others!).

Division should be interpreted as operating on rationals, and division by zero should be avoided.