About these problems
These problems are dedicated to anyone who wants, or needs, to develop programming skills.
This list originated as the Ninety-Nine Prolog Problems by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland (the original site is offline). Later developments include other languages such as Java 8, Scala, and Haskell or Python.
Here the problems statements are language agnostic. Some languages already provide native or standard libraries to support to some features, such as lists, dictionaries, terms, etc. That is fine; just choose the depth at which you want to practice.
Working with Lists
Problem 01
easy
Find the last element of a list.
Problem 02
easy
Find the last but one element of a list. (penúltimo, zweitletztes Element, l'avant-dernier élément)
Problem 03
easy
Find the 'th element of a list. The first element in the list is number .
Problem 04
easy
Find the number of elements of a list.
Problem 05
easy
Reverse a list.
Problem 06
easy
Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g.
[r, a, d, a, r]
.
Problem 07
intermediate
Flatten a nested list structure. Transform a list, possibly holding lists as elements into a "flat" list by replacing each list with its elements (recursively).
Problem 08
intermediate
Eliminate consecutive duplicates of list elements. If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.
Example
compress([a, a, a, a, b, c, c, a, a, d, e, e, e, e]) == [a, b, c, a, d, e]
Problem 09
intermediate
Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists.
Example
pack([a, a, a, a, b, c, c, a, a, d, e, e, e, e]) ==
[
[ a, a, a, a ],
[ b ],
[ c, c ],
[ a, a ],
[ d ],
[ e, e, e, e ]
]
Problem 10
easy
Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as terms
[N, E]
whereN
is the number of duplicates of the elementE
.
Example
encode([a, a, a, a, b, c, c, a, a, d, e, e, e, e]) ==
[
[ 4, a ],
[ 1, b ],
[ 2, c ],
[ 2, a ],
[ 1, d ],
[ 4, e ]
]
Problem 11
easy
Modified run-length encoding.
Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as [N, E]
terms.
Example
encode_modified([a, a, a, a, b, c, c, a, a, d, e, e, e, e]) ==
[
[ 4, a ],
b,
[ 2, c ],
[ 2, a ],
d,
[ 4, e ]
]
Problem 12
intermediate
Decode a run-length encoded list.
Given a run-length code list generated as specified in problem P11. Construct its uncompressed version.
Problem 13
intermediate
Run-length encoding of a list (direct solution).
Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton terms [1, X]
by X
.
Example
encode_direct([a, a, a, a, b, c, c, a, a, d, e, e, e, e]) ==
[
[4, a],
b,
[2, c],
[2, a],
d,
[4, e]
]
Problem 14
easy
Duplicate the elements of a list.
Example
dupli([a, b, c, c, d]) == [a, a, b, b, c, c, c, c, d, d]
Problem 15
intermediate
Duplicate the elements of a list a given number of times.
Example
dupli([a, b, c], 3) == [a, a, a, b, b, b, c, c, c]
Problem 16
intermediate
Drop every 'th element from a list.
Example
drop([a, b, c, d, e, f, g, h, i, k], 3) == [a, b, d, e, g, h, k]
Problem 17
easy
Split a list into two parts; the length of the first part is given. Do not use any predefined functions.
Example
split([a, b, c, d, e, f, g, h, i, k], 3) ==
[
[a, b, c],
[d, e, f, g, h, i, k]
]
Problem 18
intermediate
Extract a slice from a list.
Given two indices, and , the slice is the list containing the elements between the 'th and 'th element of the original list (both limits included). Start counting the elements with 1.
Example
slice([a, b, c, d, e, f, g, h, i, k], 3, 7) == [c, d, e, f, g]
Problem 19
intermediate
Rotate a list places to the left.
Examples
rotate([a, b, c, d, e, f, g, h], 3) == [d, e, f, g, h, a, b, c]
rotate([a, b, c, d, e, f, g, h], -2) == [g, h, a, b, c, d, e, f]
Hint: Use the result of problem P17.
Problem 20
easy
Remove the 'th element from a list.
Example
remove_at([a, b, c, d], 2) == [a, c, d]
Problem 21
easy
Insert an element at a given position into a list.
Example
insert_at(alfa, [a, b, c, d], 2) == [a, alfa, b, c, d]
Problem 22
easy
Create a list containing all integers within a given range.
Example
range(4, 9) == [4, 5, 6, 7, 8, 9]
Problem 23
intermediate
Extract a given number of randomly selected elements from a list. The selected items shall be put into a result list.
Example
rnd_select([a, b, c, d, e, f, g, h], 3) == [e, d, a]
Hint: Use the result of problem P20.
Problem 24
easy
Lotto: Draw different random numbers from the set . The selected numbers shall be put into a result list.
Example
rnd_select(6, 49) == [23, 1, 17, 33, 21, 37]
Hint: Combine the solutions of problems P22 and P23.
Problem 25
easy
Generate a random permutation of the elements of a list.
Example
rnd_permu([a, b, c, d, e, f]) == [b, a, d, c, e, f]
Hint: Use the solution of problem P23.
Problem 26
intermediate
Generate the combinations of distinct objects chosen from the elements of a list.
In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are possibilities ( denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities.
Example
combination(3, [a, b, c, d, e, f]) ==
[
[a, b, c],
[a, b, d],
[a, b, e],
...
]
Problem 27
intermediate
Group the elements of a set into disjoint subsets.
- In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities.
Example
group3([aldo, beat, carla, david, evi, flip, gary, hugo, ida]) ==
[
[aldo, beat],
[carla, david, evi],
[flip, gary, hugo, ida]
]
- Generalize the above function in a way that we can specify a list of group sizes and the function will return a list of groups.
Example
group( [aldo, beat, carla, david, evi, flip, gary, hugo, ida],
[2, 2, 5]) ==
[
[aldo, beat],
[carla, david],
[evi, flip, gary, hugo, ida]
]
Note that we do not want permutations of the group members; i.e. [[aldo, beat], ...]
is the same solution as [[beat, aldo], . ..]
.
However, we make a difference between [[aldo, beat], [carla, david], ...]
and [[carla, david], [aldo, beat], ...]
.
You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients".
Problem 28
intermediate
Sort a list of lists according to length of sublist.
- We suppose that a list (InList) contains elements that are lists themselves. The objective is to sort the elements of InList according to their length. E.g. short lists first, longer lists later, or vice versa.
Example
lsort( [
[a, b, c],
[d, e],
[f, g, h],
[d, e],
[i, j, k, l],
[m, n],
[o] ]) ==
[
[o],
[d, e],
[d, e],
[m, n],
[a, b, c],
[f, g, h],
[i, j, k, l]
]
- Again, we suppose that a list (InList) contains elements that are lists themselves. But this time the objective is to sort the elements of InList according to their length frequency; i.e. in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later.
Example
lfsort( [ [a, b, c],
[d, e],
[f, g, h],
[d, e],
[i, j, k, l],
[m, n],
[o] ]) ==
[
[i, j, k, l],
[o],
[a, b, c],
[f, g, h],
[d, e],
[d, e],
[m, n]
]
Note that in the above example, the first two lists in the result have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears, there are two list of this length. And finally, the last three lists have length 2. This is the most frequent length.
Arithmetic
Problem 31
intermediate
Determine whether a given integer number is prime.
Example
is_prime(7) == true
Problem 32
intermediate
Determine the greatest common divisor of two positive integer numbers. Use Euclid's algorithm.
Example
gcd(36, 63) == 9
Problem 33
easy
Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.
Example
coprime(35, 64) == true
Problem 34
intermediate
Calculate Euler's totient function .
Euler's so-called totient function is defined as the number of positive integers that are coprime to .
Example
thus . Note the special case: .
- Find out what the value of is if is a prime number.
Euler's totient function plays an important role in one of the most widely used public key cryptography methods (RSA). In this exercise you should use the most primitive method to calculate this function (there are smarter ways that we shall discuss later).
Problem 35
intermediate
Determine the prime factors of a given positive integer.
Construct a flat list containing the prime factors in ascending order.
Example
prime_factors(315) == [3,3,5,7]
Problem 36
intermediate
Determine the prime factors of a given positive integer (2).
Construct a list containing the prime factors and their multiplicity.
Example
prime_factors_mult(315) == [[3,2],[5,1],[7,1]]
Hint: The problem is similar to problem P13.
Problem 37
intermediate
Calculate Euler's totient function (improved).
See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number is known in the form of problem P36 then the function can be efficiently calculated as follows: Let [[p1,m1],[p2,m2],[p3,m3],...]
be the list of prime factors (and their multiplicities) of a given number . Then can be calculated with the following formula:
Problem 38
easy
Compare the two methods of calculating Euler's totient function.
Use the solutions of problems P34 and P37 to compare the algorithms. Take the number of logical inferences as a measure for efficiency. Try to calculate as an example.
Problem 39
easy
A list of prime numbers.
Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
Problem 40
intermediate
Goldbach's conjecture.
Goldbach's conjecture says that every positive even number greater than is the sum of two prime numbers. Example: .
It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers. Write a function to find the two prime numbers that sum up to a given even integer.
Example
goldbach(28) == [5,23]
Problem 41
intermediate
A list of Goldbach compositions.
Given a range of integers by its lower and upper limit, return a list of all even numbers and their Goldbach composition.
Example
goldbach_list(9,20) == [
[ 10, 3, 7 ],
[ 12, 5, 7 ],
[ 14, 3, 11 ],
[ 16, 3, 13 ],
[ 18, 5, 13 ],
[ 20, 3, 17 ]
]
- In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than say 50. Try to find out how many such cases there are in the range .
Example (for a print limit of 50)
goldbach_list(1,2000,50) == [
[ 992, 73, 91 ],
[ 1382, 61, 132 ],
[ 1856, 67, 178 ],
[ 1928, 61, 186 ],
]
Logic and Codes
Problem 46
intermediate
Truth tables for logical expressions.
Notation: The expression f/n
means that function f
has arity n
. For example, sum/2
means that sum
has 2
arguments.
Define functions and/2
, or/2
, nand/2
, nor/2
, xor/2
, impl/2
and equ/2
(for logical equivalence) which succeed or false according to the result of their respective operations; e.g. and(A,B)
is true
, if and only if both A
and B
are true
succeed.
Note that A
and B
can be expressions (not only the constants true
and false
). A logical expression in two variables can then be written in prefix notation, as in the following example: and(or(A,B),nand(A,B))
.
Now, write a function table/3
which returns the truth table of a given logical expression in two variables.
Example
table(and(A,or(A,B))) == [
[ true, true, true],
[ true, false, true],
[ false, true, false],
[ false, false, false]
]
Problem 47
easy
Truth tables for logical expressions (2).
Continue problem P46 by defining and/2
, or/2
, etc as being operators.
This allows to write the logical expression in the more natural way, as in the example: A and (A or not B)
. Define operator precedence as usual; i.e. as in Java.
Example
table(A,B, A and (A or not B)) == [
[ true, true, true],
[ true, false, true],
[ false, true, false],
[ false, false, false]
]
Problem 48
intermediate
Truth tables for logical expressions (3).
Generalize problem P47 in such a way that the logical expression may contain any number of logical variables.
Define table/2
in a way that table(List,Expr)
prints the truth table for the expression Expr
, which contains the logical variables enumerated in List
.
Example
table([A,B,C], A and (B or C) equ A and B or A and C) ===
[
[ true, true, true, true],
[ true, true, false, true],
[ true, false, true, true],
[ true, false, false, true],
[ false, true, true, true],
[ false, true, false, true],
[ false, false, true, true],
[ false, false, false, true]
]
Problem 49
intermediate
Gray code.
An -bit Gray code is a sequence of -bit strings constructed according to certain rules. For example,
C(1) = ['0', '1']
C(2) = ['00', '01', '11', '10']
C(3) = ['000', '001', '011', '010', '110', '111', '101', '100']
Find out the construction rules and write a function with the following specification:
gray(N) == N-bit Gray code.
Can you apply the method of "result caching" in order to make the function more efficient, when it is to be used repeatedly?
Problem 50
hard
Huffman code.
First of all, consult a good book on discrete mathematics or algorithms for a detailed description of Huffman codes. We suppose a set of symbols with their frequencies, given as a list of fr(S,F)
terms.
Example:
[fr(a,45),fr(b,13),fr(c,12),fr(d,16),fr(e,9),fr(f,5)].
Our objective is to construct a list hc(S) = C
terms, where C
is the Huffman code word for the symbol S
.
In our example, the result could be
[hc(a,'0'), hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'), hc(f,'1100')]
[hc(a,'01'), ... ]
The task shall be performed by the function huffman/2
defined as follows:
huffman(F) == Hs is the Huffman code table for the frequency table F.
Binary Trees
A binary tree is either empty or it is composed of a root element and two successors, which are binary trees themselves.
We represent the empty tree by the empty list []
and the non-empty tree by [X,L,R]
, where X denotes the root node and L and R denote the left and right subtree, respectively.
%%{init: {'theme':'neutral'}}%% graph TD a((a)) --> b((b)) a --> c((c)) b --> d((d)) b --> e((e)) c --> n((.)) c --> f((f)) f --> g((g)) f --> n2((.))
The example tree depicted above is therefore represented by the following list:
[a,
[b,
[d,[],[]],
[e,[],[]]
],
[c,
[],
[f,
[g,[],[]],
[]
]
]
]
Other examples are a binary tree that consists of a root node only: [a, [], []]
, or an empty binary tree: []
. You can check your functions using these example trees.
Problem 54
easy
Check whether a given list represents a binary tree.
Write a function istree
which returns true
if and only if its argument is a list representing a binary tree. Example:
istree([a, [b,[],[]], []]) == true
istree([a, [b,[],[]]]) == false
Problem 55
intermediate
Construct completely balanced binary tree.
In a completely balanced binary tree, the following property holds for every node: The number of nodes in its left subtree and the number of nodes in its right subtree are almost equal, which means their difference is not greater than one.
Write a function cbal_tree/1
to construct completely balanced binary trees for a given number of nodes. The function should generate all solutions via backtracking. Put the letter x
as information into all nodes of the tree.
Example
cbal_tree(4) ==
t( x,
t( x, nil, nil),
t( x,
nil,
t( x, nil, nil)
)
)
Problem 56
intermediate
Symmetric binary tree.
Let us call a binary tree symmetric if you can draw a vertical line through the root node and then the right subtree is the mirror image of the left subtree.
Write a function symmetric/1
to check whether a given binary tree is symmetric.
Hint: Write a function mirror/2
first to check whether one tree is the mirror image of another. We are only interested in the structure, not in the contents of the nodes.
Problem 57
intermediate
Binary search trees (dictionaries).
Use the function add/3
, to write a function to construct a binary search tree from a list of integer numbers.
Example
construct([3,2,5,7,1]) ==
t( 3,
t( 2,
t( 1, nil, nil),
nil
),
t( 5,
nil,
t( 7, nil, nil)
)
)
Then use this function to test the solution of the problem P56.
Example
test_symmetric([5,3,18,1,4,12,21]) == true
test_symmetric([3,2,5,7,4]) == false
Problem 58
intermediate
Generate-and-test paradigm.
Apply the generate-and-test paradigm to construct all symmetric, completely balanced binary trees with a given number of nodes. Example: ?- sym_cbal_trees(5,Ts). Ts = [t(x, t(x, nil, t(x, nil, nil)), t(x, t(x, nil, nil), nil)), t(x, t(x, t(x, nil, nil), nil), t(x, nil, t(x, nil, nil))). How many such trees are there with 57 nodes? Investigate about how many solutions there are for a given number of nodes? What if the number is even? Write an appropriate function.
Problem 59
intermediate
Construct height-balanced binary tree.
In a height-balanced binary tree, the following property holds for every node: The height of its left subtree and the height of its right subtree are almost equal, which means their difference is not greater than one. Write a function hbal_tree/2 to construct height-balanced binary trees for a given height. The function should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree. Example: ?- hbal_tree(3) == t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), t(x, nil, nil))) . T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil), nil)) . etc......No
Problem 60
intermediate
Construct height-balanced binary trees with a given number of node.
Consider a height-balanced binary tree of height H. What is the maximum number of nodes it can contain. Clearly, MaxN = 2**H - 1. However, what is the minimum number MinN? This question is more difficult. Try to find a recursive statement and turn it into a function minNodes/2 defined as follwos:
% minNodes(H,N) :- N is the minimum number of nodes in a height-balanced binary tree of height H. (integer,integer), (+,?. On the other hand, we might ask: what is the maximum height H a height-balanced binary tree with N nodes can have?
% maxHeight(N,H) :- H is the maximum height of a height-balanced binary tree with N nodes (integer,integer), (+,?. Now, we can attack the main problem: construct all the height-balanced binary trees with a given nuber of nodes.
% hbal_tree_nodes(N,T) :- T is a height-balanced binary tree with N nodes. Find out how many height-balanced trees exist for N = 15.
Problem 61
easy
Count the leaves of a binary tre. A leaf is a node with no successors. Write a function count_leaves/2 to count them.
% count_leaves(T,N) :- the binary tree T has N leaves
Problem 61 A
easy
Collect the leaves of a binary tree in a list.
A leaf is a node with no successors. Write a function leaves/2 to collect them in a list.
% leaves(T,S) :- S is the list of all leaves of the binary tree T
Problem 62
easy
Collect the internal nodes of a binary tree in a list.
An internal node of a binary tree has either one or two non-empty successors. Write a function internals/2 to collect them in a list.
% internals(T,S) :- S is the list of internal nodes of the binary tree T.
Problem 62
B (easy) Collect the nodes at a given level in a lis. A node of a binary tree is at level N if the path from the root to the node has length N-1. The root node is at level 1. Write a function atlevel/3 to collect all nodes at a given level in a list.
% atlevel(T,L,S) :- S is the list of nodes of the binary tree T at level . Using atlevel/3 it is easy to construct a function levelorder/2 which creates the level-order sequence of the nodes. However, there are more efficient ways to do that.
Problem 63
intermediate
Construct a complete binary tree.
A complete binary tree with height H is defined as follows: The levels 1,2,3,...,H-1 contain the maximum number of nodes (i.e 2**(i-1) at the level i, note that we start counting the levels from 1 at the root). In level H, which may contain less than the maximum possible number of nodes, all the nodes are "left-adjusted". This means that in a levelorder tree traversal all internal nodes come first, the leaves come second, and empty successors (the nil's which are not really nodes!) come last. Particularly, complete binary trees are used as data structures (or addressing schemes) for heaps. We can assign an address number to each node in a complete binary tree by enumerating the nodes in levelorder, starting at the root with number 1. In doing so, we realize that for every node X with address A the following property holds: The address of X's left and right successors are 2A and 2A+1, respectively, supposed the successors do exist. This fact can be used to elegantly construct a complete binary tree structure. Write a function complete_binary_tree/2 with the following specification:
% complete_binary_tree(N,T) :- T is a complete binary tree with N nodes. (+,?. Test your function in an appropriate way.
Problem 64
intermediate
Layout a binary tree (1).
Given a binary tree as the usual Prolog term t(X,L,R) (or nil). As a preparation for drawing the tree, a layout algorithm is required to determine the position of each node in a rectangular grid. Several layout methods are conceivable, one of them is shown in the illustration below. In this layout strategy, the position of a node v is obtained by the following two rules. x(v) is equal to the position of the node v in the inorder sequenc. y(v) is equal to the depth of the node v in the tre. In order to store the position of the nodes, we extend the Prolog term representing a node (and its successors) as follows:
% nil represents the empty tree (as usual) % t(W,X,Y,L,R) represents a (non-empty) binary tree with root W "positioned" at (X,Y), and subtrees L and . Write a function layout_binary_tree/2 with the following specification:
% layout_binary_tree(T,PT) :- PT is the "positioned" binary tree obtained from the binary tree T. (+,?. Test your function in an appropriate way.
Problem 65
intermediate
Layout a binary tree (2).
An alternative layout method is depicted in the illustration opposite. Find out the rules and write the corresponding Prolog function. Hint: On a given level, the horizontal distance between neighboring nodes is constant. Use the same conventions as in problem P64 and test your function in an appropriate way.
Problem 66
hard
Layout a binary tree (3).
Yet another layout strategy is shown in the illustration opposite. The method yields a very compact layout while maintaining a certain symmetry in every node. Find out the rules and write the corresponding Prolog function. Hint: Consider the horizontal distance between a node and its successor nodes. How tight can you pack together two subtrees to construct the combined binary tree. Use the same conventions as in problem P64 and P65 and test your function in an appropriate way. Note: This is a difficult problem. Don't give up too early. Which layout do you like most?
Problem 67
intermediate
A string representation of binary tree.
Somebody represents binary trees as strings of the following type (see example opposite). a(b(d,e),c(,f(g,)). a) Write a Prolog function which generates this string representation, if the tree is given as usual (as nil or t(X,L,R) term). Then write a function which does this inverse; i.e. given the string representation, construct the tree in the usual form. Finally, combine the two functions in a single function tree_string/2 which can be used in both directions. b) Write the same function tree_string/2 using difference lists and a single function tree_dlist/2 which does the conversion between a tree and a difference list in both directions. For simplicity, suppose the information in the nodes is a single letter and there are no spaces in the string.
Problem 68
intermediate
Preorder and inorder sequences of binary tree.
We consider binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. a) Write functions preorder/2 and inorder/2 that construct the preorder and inorder sequence of a given binary tree, respectively. The results should be atoms, e.g. 'abdecfg' for the preorder sequence of the example in problem P67. b) Can you use preorder/2 from problem part a) in the reverse direction; i.e. given a preorder sequence, construct a corresponding tree? If not, make the necessary arrangements. c) If both the preorder sequence and the inorder sequence of the nodes of a binary tree are given, then the tree is determined unambiguously. Write a function pre_in_tree/3 that does the job. d) Solve problems a) to c) using difference lists. Cool! Use the predefined function time/1 to compare the solutions. What happens if the same character appears in more than one node. Try for instance pre_in_tree(aba,baa,T).
Problem 69
intermediate
Dotstring representation of binary tree.
We consider again binary trees with nodes that are identified by single lower-case letters, as in the example of problem P67. Such a tree can be represented by the preorder sequence of its nodes in which dots (.) are inserted where an empty subtree (nil) is encountered during the tree traversal. For example, the tree shown in problem P67 is represented as 'abd..e..c.fg...'. First, try to establish a syntax (BNF or syntax diagrams) and then write a function tree_dotstring/2 which does the conversion in both directions. Use difference lists.
Multiway Trees
A multiway tree is composed of a root element and a (possibly empty) set of successors which are multiway trees themselves.
- A multiway tree is never empty.
- The set of successor trees is sometimes called a forest.
We represent a multiway tree by an expression t(X,F)
, where X
denotes the root node and F
denotes the forest of successor trees (a list).
%%{init: {'theme':'neutral'}}%% graph TD a((a)) --> f((f)) a --> c((c)) a --> b((b)) f --> g((g)) b --> d((d)) b --> e((e))
The example tree depicted above is therefore represented by the following expression:
t( a, [ t( f, [ t( g, [] ) ]),
t( c, [ ]),
t( b, [ t( d, [] ),
t( e, [] ) ]) ])
Problem 70 B
easy
Check whether a given term represents a multiway tree.
Write a function istree/1
which succeeds if and only if its argument is an expressions representing a multiway tree.
Example
istree(
t( a, [ t( f, [ t( g, [] ) ]),
t( c, [ ]),
t( b, [ t( d, [] ),
t( e, [] ) ]) ])
) == true
Problem 70 C
easy
Count the nodes of a multiway tree.
Write a function nnodes/1
which counts the nodes of a given multiway tree.
Example
nnodes(t(a,[t(f,[])])) == 2.
Problem 70
intermediate
Tree construction from a node string.
We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character ^ has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level. By this rule, the tree in the figure opposite is represented as: afg^^c^bd^e^^. Define the syntax of the string and write a function tree(String,Tree) to construct the Tree when the String is given. Work with atoms (instead of strings). Make your function work in both directions.
Problem 71
easy
Determine the internal path length of a tree.
We define the internal path length of a multiway tree as the total sum of the path lengths from the root to all nodes of the tree. By this definition, the tree in the figure of problem P70 has an internal path length of 9. Write a function ipl(Tree,IPL) for the flow pattern (+,-).
Problem 72
easy
Construct the bottom-up order sequence of the tree node.
Write a function bottom_up(Tree,Seq) which constructs the bottom-up sequence of the nodes of the multiway tree Tree. Seq should be a Prolog list. What happens if you run your function backwords?
Problem 73
intermediate
Lisp-like tree representation.
There is a particular notation for multiway trees in Lisp. Lisp is a prominent functional programming language, which is used primarily for artificial intelligence problems. As such it is one of the main competitors of Prolog. In Lisp almost everything is a list, just as in Prolog everything is a term. The following pictures show how multiway tree structures are represented in Lisp. Note that in the "lispy" notation a node with successors (children) in the tree is always the first element in a list, followed by its children. The "lispy" representation of a multiway tree is a sequence of atoms and parentheses '(' and ')', which we shall collectively call "tokens". We can represent this sequence of tokens as a Prolog list; e.g. the lispy expression (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')', ')']. Write a function tree_ltl(T,LTL) which constructs the "lispy token list" LTL if the tree is given as term T in the usual Prolog notation. Example: ?- tree_ltl(t(a,[t(b,[]),t(c,[])]),LTL). LTL = ['(', a, '(', b, c, ')', ')'. As a second, even more interesting exercise try to rewrite tree_ltl/2 in a way that the inverse conversion is also possible: Given the list LTL, construct the Prolog tree T. Use difference lists.
Graphs
A graph is defined as a set of nodes and a set of edges, where each edge is a pair of nodes.
%%{init: {'theme':'neutral'}}%% graph TD b((b)) --- c((c)) b --- f((f)) g((g)) --- h((h)) c --- f b ~~~ g f --- k((k)) g ~~~ d((d))
There are several ways to represent graphs. One method is to represent each edge separately as one clause (fact). In this form, the graph depicted above is represented as the following list:
[ [h, g], [k, f], [f, b], ... ]
We call this the edge-list form. Obviously, isolated nodes cannot be represented.
Another method is to represent the whole graph as one data object. According to the definition of the graph as a pair of two sets (nodes and edges), we may use the following list to represent the graph above.
[
[ b, c, d, f, g, h, k],
[ [b, c], [b, f], [c, f], [f, k], [g, h] ]
]
We call this graph-list form. Note, that the lists are kept sorted, they are really sets, without duplicated elements. Each edge appears only once in the edge list (the second sublist); i.e. an edge from a node x
to another node y
is represented as [x, y]
, the list [y, x]
is not present.
The graph-list form is our default representation.
A third representation method is to associate with each node the set of nodes that are adjacent to that node. We call this the adjacency-list form. In our example:
[ [b, c, f], [c, b, f], [d], [f, b, c, k], ... ]
where a sublist [n, d1, d2, ..., dN]
states that node n
has edges to d1
, d2
, ... dN
.
The representations we introduced so far are lists and therefore well suited for automated processing, but their syntax is not very user-friendly. Typing the terms by hand is cumbersome and error-prone. We can define a more compact and "human-friendly" notation as follows: A graph is represented by a list of nodes and edges X-Y
. If an X
appears as an endpoint of an edge, it is automatically defined as a node. Our example could be written as:
[b-c, f-c, g-h, d, f-b, k-f, h-g]
We call this the human-friendly form. As the example shows, the list does not have to be sorted and may even contain the same edge multiple times. Notice the isolated node d
.
When the edges are directed we call them arcs. These are represented by ordered pairs. Such a graph is called directed graph. To represent a directed graph, the forms discussed above are slightly modified. The example graph opposite is represented as follows. Arc-clause for. arc(s,u). arc(u,r). ... Graph-term for. digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)]. Adjacency-list form [n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u]). Note that the adjacency-list does not have the information on whether it is a graph or a digraph.
Human-friendly form [s > r, t, u > r, s > u, u > s, v > u].
Finally, graphs and digraphs may have additional information attached to nodes and edges (arcs). For the nodes, this is no problem, as we can easily replace the single character identifiers with arbitrary compound terms, such as city('London',4711). On the other hand, for edges we have to extend our notation. Graphs with additional information attached to edges are called labelled graphs. Arc-clause for. arc(m,q,7). arc(p,q,9). arc(p,m,5).
Graph-term form. digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)].
Adjacency-list form [n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[]).
Notice how the edge information has been packed into a term with functor '/' and arity 2, together with the corresponding node.
Human-friendly form [p>q/9, m>q/7, k, p>m/5].
The notation for labelled graphs can also be used for so-called multi-graphs, where more than one edge (or arc) are allowed between two given nodes.
Problem 80
hard
Conversion.
Write functions to convert between the different graph representations.
With these functions, all representations are equivalent; i.e. for the following problems you can always pick freely the most convenient form. The reason this problem is rated "hard" is not because it's particularly difficult, but because it's a lot of work to deal with all the special cases.
Problem 81
intermediate
Paths from one node to another one.
Write a function paths(G,A,B)
to find the acyclic paths from node A
to node B'
in the graph G
. The function should return all paths.
Problem 82
easy
Cycles from a given node.
Write a function cycles(G,A)
to find the closed paths (cycles) starting at a given node A
in the graph G
. The function should return all cycles.
Problem 83
intermediate
Construct all spanning tree.
Write a function s_tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this function, find out how many spanning trees there are for the graph depicted to the left. The data of this example graph can be found in the file p83.dat. When you have a correct solution for the s_tree/2 function, use it to define two other useful functions: is_tree(Graph) and is_connected(Graph). Both are five-minutes tasks!
Problem 84
intermediate
Construct the minimal spanning tree.
Write a function ms_tree(Graph,Tree,Sum) to construct the minimal spanning tree of a given labelled graph. Hint: Use the algorithm of Prim. A small modification of the solution of P83 does the trick. The data of the example graph to the right can be found in the file p84.dat.
Problem 85
intermediate
Graph isomorphism.
Two graphs G1(N1,E1) and G2(N2,E2) are isomorphic if there is a bijection f: N1 -> N2 such that for any nodes X,Y of N1, X and Y are adjacent if and only if f(X) and f(Y) are adjacent. Write a function that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f.
Problem 86
intermediate
Node degree and graph coloration.
- Write a function degree(Graph,Node,Deg) that determines the degree of a given node.
- Write a function that generates a list of all nodes of a graph sorted according to decreasing degree.
- Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors.
Problem 87
intermediate
Depth-first order graph traversal (alternative solution).
Write a function that generates a depth-first order graph traversal sequence. The starting point should be specified, and the output should be a list of nodes that are reachable from this starting point (in depth-first order).
Problem 88
intermediate
Connected components (alternative solution).
Write a function that splits a graph into its connected components.
Problem 89
intermediate
Bipartite graph.
Write a function that finds out whether a given graph is bipartite.
Miscellaneous Problems
Problem 90
intermediate
Eight queens problem.
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.
Problem 91
intermediate
Knight's tour.
Another famous problem is this one: How can a knight jump on an chessboard in such a way that it visits every square exactly once.
Hints:
- Represent the squares by pairs of their coordinates of the form , where both and are integers between and . (Note that '' is just a convenient functor, not division!)
- Define the relation to express the fact that a knight can jump from to on a chessboard.
- And finally, represent the solution of our problem as a list of knight positions (the knight's tour).
Problem 92
hard
Von Koch's conjecture.
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 nodes (and hence edges). Find a way to enumerate the nodes from to and, accordingly, the edges from 1 to in such a way, that for each edge the difference of its node numbers equals to .
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 function that calculates a numbering scheme for a given tree. What is the solution for the larger tree pictured above?
Problem 93
hard
An arithmetic puzzle.
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 or (and ten others!).
Problem 94
hard
Generate -regular simple graphs with nodes.
In a -regular graph all nodes have a degree of ; i.e. the number of edges incident in each node is .
How many (non-isomorphic!) 3-regular graphs with 6 nodes are there?
Problem 95
intermediate
English number word.
On financial documents, like cheques, numbers must sometimes be written in full words. Example: 175 must be written as one-seven-five.
Write a function full_words/1
to print (non-negative) integer numbers in full words.
Problem 96
intermediate
Syntax checker (alternative solution with difference lists).
In a certain programming language (Ada) identifiers are defined by the syntax diagram (railroad chart) opposite. 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 function identifier/1
that can check whether or not a given string is a legal identifier.
identifier(Str) == true iff Str is a legal identifier
Problem 97
intermediate
Sudoku.
Sudoku puzzles go like this.
Problem statement
..4 | 8.. | .17 |
67. | 9.. | ... |
5.8 | .3. | ..4 |
--- | --- | --- |
3.. | 74. | 1.. |
.69 | ... | 78. |
..1 | .69 | ..5 |
--- | --- | --- |
1.. | .8. | 3.6 |
... | ..6 | .91 |
24. | ..1 | 5.. |
Solution
934 | 825 | 617 |
672 | 914 | 853 |
518 | 637 | 924 |
--- | --- | --- |
325 | 748 | 169 |
469 | 153 | 782 |
781 | 269 | 435 |
--- | --- | --- |
193 | 582 | 346 |
853 | 476 | 291 |
246 | 391 | 578 |
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 (denoted .
) 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.
Problem 98
hard
Nonogram.
Around 1994, a certain kind of puzzles 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.
Problem 99
hard
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. 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 opposite is defined in the file p99a.dat, other examples are p99b.dat and p99d.dat. There is also an example of a puzzle (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 p99-readfile.pl. Use the function 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.