<title>Solutions to the L-99: Ninety-Nine Lisp Problems</title>
<!-- TOP-END -->
<!-- This section is automatically generated by html-update, -->
<!-- from data in 'node.el'.    Please, do not edit it here. -->
 <A HREF="../../../toc.html">Contents</a> |
 <A HREF="../../../index.html">Home</a> |
 <A HREF="../com/informatimago/small-cl-pgms/intersection-r5rs-common-lisp-emacs-lisp/index.html">Previous</a> |
 <A HREF="../../../index.html">Up</a> |
 <A HREF="../../emacs/index.html">Next</a> |
<!-- MENU-END -->

<h1 align="center">Solutions to Ninety-Nine Lisp Problems</h1>

<p>Here are solutions to the
<a href="http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html">
L-99: Ninety-Nine Lisp Problems</a>, (which themselves are derived from
<a href="http://www.scribd.com/doc/18339544/99-prolog-problems">a list of prolog problems</a>).</p>

<h2>Working with lists</h2>
<li><a href="p01.lisp">p01.lisp</a> P01 (*) Find the last box of a list.</li>
<li><a href="p02.lisp">p02.lisp</a> P02 (*) Find the last but one box of a list.</li>
<li><a href="p03.lisp">p03.lisp</a> P03 (*) Find the K'th element of a list.</li>
<li><a href="p04.lisp">p04.lisp</a> P04 (*) Find the number of elements of a list.</li>
<li><a href="p05.lisp">p05.lisp</a> P05 (*) Reverse a list.</li>
<li><a href="p06.lisp">p06.lisp</a> P06 (*) Find out whether a list is a palindrome.</li>
<li><a href="p07.lisp">p07.lisp</a> P07 (**) Flatten a nested list structure.</li>
<li><a href="p08.lisp">p08.lisp</a> P08 (**) Eliminate consecutive duplicates of list elements.</li>
<li><a href="p09.lisp">p09.lisp</a> P09 (**) Pack consecutive duplicates of list elements into sublists.</li>
<li><a href="p10.lisp">p10.lisp</a> P10 (*) Run-length encoding of a list.</li>
<li><a href="p11.lisp">p11.lisp</a> P11 (*) Modified run-length encoding.</li>
<li><a href="p12.lisp">p12.lisp</a> P12 (**) Decode a run-length encoded list.</li>
<li><a href="p13.lisp">p13.lisp</a> P13 (**) Run-length encoding of a list (direct solution).</li>
<li><a href="p14.lisp">p14.lisp</a> P14 (*) Duplicate the elements of a list.</li>
<li><a href="p15.lisp">p15.lisp</a> P15 (**) Replicate the elements of a list a given number of times.</li>
<li><a href="p16.lisp">p16.lisp</a> P16 (**) Drop every N'th element from a list.</li>
<li><a href="p17.lisp">p17.lisp</a> P17 (*) Split a list into two parts; the length of the first part is given.</li>
<li><a href="p18.lisp">p18.lisp</a> P18 (**) Extract a slice from a list.</li>
<li><a href="p19.lisp">p19.lisp</a> P19 (**) Rotate a list N places to the left.</li>
<li><a href="p20.lisp">p20.lisp</a> P20 (*) Remove the K'th element from a list.</li>
<li><a href="p21.lisp">p21.lisp</a> P21 (*) Insert an element at a given position into a list.</li>
<li><a href="p22.lisp">p22.lisp</a> P22 (*) Create a list containing all integers within a given range.</li>
<li><a href="p23.lisp">p23.lisp</a> P23 (**) Extract a given number of randomly selected elements from a list.</li>
<li><a href="p24.lisp">p24.lisp</a> P24 (*) Lotto: Draw N different random numbers from the set 1..M.</li>
<li><a href="p25.lisp">p25.lisp</a> P25 (*) Generate a random permutation of the elements of a list.</li>
<li><a href="p26.lisp">p26.lisp</a> P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list</li>
<li><a href="p27.lisp">p27.lisp</a> P27 (**) Group the elements of a set into disjoint subsets.</li>
<li><a href="p28.lisp">p28.lisp</a> P28 (**) Sorting a list of lists according to length of sublists</li>
<li><a href="p31.lisp">p31.lisp</a> P31 (**) Determine whether a given integer number is prime.</li>
<li><a href="p32.lisp">p32.lisp</a> P32 (**) Determine the greatest common divisor of two positive integer numbers.</li>
<li><a href="p33.lisp">p33.lisp</a> P33 (*) Determine whether two positive integer numbers are coprime.</li>
<li><a href="p34.lisp">p34.lisp</a> P34 (**) Calculate Euler's totient function phi(m).</li>
<li><a href="p35.lisp">p35.lisp</a> P35 (**) Determine the prime factors of a given positive integer.</li>
<li><a href="p36.lisp">p36.lisp</a> P36 (**) Determine the prime factors of a given positive integer (2).</li>
<li><a href="p37.lisp">p37.lisp</a> P37 (**) Calculate Euler's totient function phi(m) (improved).</li>
<li><a href="p38.lisp">p38.lisp</a> P38 (*) Compare the two methods of calculating Euler's totient function.</li>
<li><a href="p39.lisp">p39.lisp</a> P39 (*) A list of prime numbers.</li>
<li><a href="p40.lisp">p40.lisp</a> P40 (**) Goldbach's conjecture.</li>
<li><a href="p41.lisp">p41.lisp</a> P41 (**) A list of Goldbach compositions.</li>
<h2>Logic and Codes</h2>
<li><a href="p46.lisp">p46.lisp</a> P46 (**) Truth tables for logical expressions.</li>
<li><a href="p47.lisp">p47.lisp</a> P47 (*) Truth tables for logical expressions (2).</li>
<li><a href="p48.lisp">p48.lisp</a> P48 (**) Truth tables for logical expressions (3).</li>
<li><a href="p49.lisp">p49.lisp</a> P49 (**) Gray code.</li>
<li><a href="p50.lisp">p50.lisp</a> P50 (***) Huffman code.</li>
<h2>Binary Trees</h2>
<li><a href="p54a.lisp">p54a.lisp</a> P54A (*) Check whether a given term represents a binary tree</li>
<li><a href="p55.lisp">p55.lisp</a> P55 (**) Construct completely balanced binary trees</li>
<li><a href="p56.lisp">p56.lisp</a> P56 (**) Symmetric binary trees</li>
<li><a href="p57.lisp">p57.lisp</a> P57 (**) Binary search trees (dictionaries)</li>
<li><a href="p58.lisp">p58.lisp</a> P58 (**) Generate-and-test paradigm</li>
<li><a href="p59.lisp">p59.lisp</a> P59 (**) Construct height-balanced binary trees</li>
<li><a href="p60.lisp">p60.lisp</a> P60 (**) Construct height-balanced binary trees with a given number of nodes</li>
<li><a href="p61.lisp">p61.lisp</a> P61 (*) Count the leaves of a binary tree</li>
<li><a href="p61a.lisp">p61a.lisp</a> P61A (*) Collect the leaves of a binary tree in a list</li>
<li><a href="p62.lisp">p62.lisp</a> P62 (*) Collect the internal nodes of a binary tree in a list</li>
<li><a href="p62b.lisp">p62b.lisp</a> P62B (*) Collect the nodes at a given level in a list</li>
<li><a href="p63.lisp">p63.lisp</a> P63 (**) Construct a complete binary tree</li>
<li><a href="p64.lisp">p64.lisp</a> P64 (**) Layout a binary tree (1)</li>
<li><a href="p65.lisp">p65.lisp</a> P65 (**) Layout a binary tree (2)</li>
<li><a href="p66.lisp">p66.lisp</a> P66 (***) Layout a binary tree (3)</li>
<li><a href="p67.lisp">p67.lisp</a> P67 (**) A string representation of binary trees</li>
<li><a href="p68.lisp">p68.lisp</a> P68 (**) Preorder and inorder sequences of binary trees</li>
<li><a href="p69.lisp">p69.lisp</a> P69 (**) Dotstring representation of binary trees</li>
<h2>Multiway Trees</h2>
<li><a href="p70b.lisp">p70b.lisp</a> P70B (*) Check whether a given term represents a multiway tree</li>
<li><a href="p70c.lisp">p70c.lisp</a> P70C (*) Count the nodes of a multiway tree</li>
<li><a href="p70.lisp">p70.lisp</a> P70 (**) Tree construction from a node string</li>
<li><a href="p71.lisp">p71.lisp</a> P71 (*) Determine the internal path length of a tree</li>
<li><a href="p72.lisp">p72.lisp</a> P72 (*) Construct the bottom-up order sequence of the tree nodes</li>
<li><a href="p73.lisp">p73.lisp</a> P73 (**) Lisp-like tree representation</li>
<li><a href="p80.lisp">p80.lisp</a> P80 (***) Conversions</li>
<li><a href="p81.lisp">p81.lisp</a> P81 (**) Path from one node to another one</li>
<li><a href="p82.lisp">p82.lisp</a> P82 (*) Cycle from a given node</li>
<li><a href="p83.lisp">p83.lisp</a> P83 (**) Construct all spanning trees</li>
<li><a href="p84.lisp">p84.lisp</a> P84 (**) Construct the minimal spanning tree</li>
<li><a href="p85.lisp">p85.lisp</a> P85 (**) Graph isomorphism</li>
<li><a href="p86.lisp">p86.lisp</a> P86 (**) Node degree and graph coloration</li>
<li><a href="p87.lisp">p87.lisp</a> P87 (**) Depth-first order graph traversal (alternative solution)</li>
<li><a href="p88.lisp">p88.lisp</a> P88 (**) Connected components (alternative solution)</li>
<li><a href="p89.lisp">p89.lisp</a> P89 (**) Bipartite graphs</li>
<h2>Miscellaneous Problems</h2>
<li><a href="p90.lisp">p90.lisp</a> P90 (**) Eight queens problem</li>
<li><a href="p91.lisp">p91.lisp</a> P91 (**) Knight's tour</li>
<li><a href="p92.lisp">p92.lisp</a> P92 (***) Von Koch's conjecture</li>
<li><a href="p93.lisp">p93.lisp</a> P93 (***) An arithmetic puzzle</li>
<li><a href="p94.lisp">p94.lisp</a> P94 (***) Generate K-regular simple graphs with N nodes</li>
<li><a href="p95.lisp">p95.lisp</a> P95 (**) English number words</li>
<li><a href="p96.lisp">p96.lisp</a> P96 (**) Syntax checker (alternative solution with difference lists)</li>
<li><a href="p97.lisp">p97.lisp</a> P97 (**) Sudoku</li>
<li><a href="p98.lisp">p98.lisp</a> P98 (***) Nonograms</li>
<li><a href="p99.lisp">p99.lisp</a> P99 (***) Crossword puzzle</li>

<!-- This section is automatically generated by html-update, -->
<!-- from data in 'node.el'.    Please, do not edit it here. -->
 | <a href="http://www.informatimago.com//develop/lisp/l99/index.html">Mirror on informatimago.com</a>
 | <a href="http://informatimago.free.fr/i//develop/lisp/l99/index.html">Mirror on free.fr</a>
 | </small></code>

      <a href="http://validator.w3.org/check?uri=referer"><img
          alt="Valid HTML 4.01!" height="31" width="88"></a>
<!-- BOTTOM-END -->


grep -n 'TO BE DONE' *.lisp
p38.lisp:11:;; TO BE DONE.

P59 (**) Construct height-balanced binary trees
    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 predicate hbal-tree/2 to construct height-balanced binary trees for a given height. The predicate should generate all solutions via backtracking. Put the letter 'x' as information into all nodes of the tree.
    * hbal-tree(3,T).
    T = 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)) ;

P60 (**) Construct height-balanced binary trees with a given number of nodes
    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 predicate 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.

P82 (*) Cycle from a given node
    Write a predicate cycle(G,A,P) to find a closed path (cycle) P starting at a given node A in the graph G. The predicate should return all cycles via backtracking.


P83 (**) Construct all spanning trees
    Write a predicate s-tree(Graph,Tree) to construct (by backtracking) all spanning trees of a given graph. With this predicate, 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 predicate, use it to define two other useful predicates: is-tree(Graph) and is-connected(Graph). Both are five-minutes tasks!


P84 (**) Construct the minimal spanning tree
    Write a predicate 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.

P85 (**) 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 predicate that determines whether two graphs are isomorphic. Hint: Use an open-ended list to represent the function f.

P86 (**) Node degree and graph coloration
    a) Write a predicate degree(Graph,Node,Deg) that determines the degree of a given node.

    b) Write a predicate that generates a list of all nodes of a graph sorted according to decreasing degree.

    c) Use Welch-Powell's algorithm to paint the nodes of a graph in such a way that adjacent nodes have different colors.

P87 (**) Depth-first order graph traversal (alternative solution)
    Write a predicate 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).

P88 (**) Connected components (alternative solution)
    Write a predicate that splits a graph into its connected components.

P89 (**) Bipartite graphs
    Write a predicate that finds out whether a given graph is bipartite.

Miscellaneous Problems

P90 (**) 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

    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

P91 (**) Knight's tour
    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?

    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).

P92 (***) 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.

    [p92a]   [p92b]

    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 above?

P93 (***) 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 2-3+5+7 = 11 or 2 =
    (3*5+7)/11 (and ten others!).

P94 (***) Generate K-regular simple graphs with N nodes
    In a K-regular graph all nodes have a degree of K; i.e. the number of edges incident in each node is K. How many (non-isomorphic!) 3-regular graphs with 6 nodes are there? See also a table of results and a Java applet that can
    represent graphs geometrically.

P95 (**) English number words
    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.

P96 (**) 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 predicate identifier/1 that can check whether or not a given string is a legal identifier.

    % identifier(Str) :- Str is a legal identifier
P97 (**) Sudoku
    Sudoku puzzles go like this:

       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

    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.
P98 (***) Nonograms
    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.

P99 (***) 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

    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.lisp. Use 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.