-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblemBackUp.html
1310 lines (1194 loc) · 54.3 KB
/
problemBackUp.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<title>L-99: Ninety-Nine Lisp Problems</title>
</head>
<body bgcolor="ffffff">
<h1>
L-99: Ninety-Nine Lisp Problems</h1>
<h3>Based on a Prolog problem list by [email protected]</h3>
<h2>Working with lists</h2>
<DL>
<DT><STRONG><A href="p01.lisp">P01</A>
(*) Find the last box of a list.</STRONG>
<DD>Example:<BR>
* (my-last '(a b c d))<BR>
(D)<P>
<DT><STRONG><A href="p02.lisp">P02</A>
(*) Find the last but one box of a list.</STRONG>
<DD>Example:<BR>
* (my-but-last '(a b c d))<BR>
(C D)<P>
<DT><STRONG><A href="p03.lisp">P03</A>
(*) Find the K'th element of a list.</STRONG>
<DD>The first element in the list is number 1.<BR>
Example:<BR>
* (element-at '(a b c d e) 3)<BR>
C<P>
<DT><STRONG><A href="p04.lisp">P04</A>
(*) Find the number of elements of a list.</STRONG><P>
<DT><STRONG><A href="p05.lisp">P05</A>
(*) Reverse a list.</STRONG><P>
<DT><STRONG><A href="p06.lisp">P06</A>
(*) Find out whether a list is a palindrome.</STRONG>
<DD>A palindrome can be read forward or backward; e.g. (x a m a x).<P>
<DT><STRONG><A href="p07.lisp">P07</A>
(**) Flatten a nested list structure.</STRONG>
<DD>Transform a list, possibly holding lists as elements into a `flat'
list by replacing each list with its elements (recursively).<BR><BR>
Example:<BR>
* (my-flatten '(a (b (c d) e)))<BR>
(A B C D E)<BR><BR>
Hint: Use the predefined functions list and append.<P>
<DT><STRONG><A href="p08.lisp">P08</A>
(**) Eliminate consecutive duplicates of list elements.</STRONG>
<DD>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.<BR><BR>
Example:<BR>
* (compress '(a a a a b c c a a d e e e e))<BR>
(A B C A D E)<P>
<DT><STRONG><A href="p09.lisp">P09</A>
(**) Pack consecutive duplicates of list elements into sublists.</STRONG>
<DD>If a list contains repeated elements they should be placed
in separate sublists.<BR><BR>
Example:<BR>
* (pack '(a a a a b c c a a d e e e e))<BR>
((A A A A) (B) (C C) (A A) (D) (E E E E))<P>
<DT><STRONG><A href="p10.lisp">P10</A>
(*) Run-length encoding of a list.</STRONG>
<DD>Use the result of problem P09 to implement the so-called
run-length encoding data compression method. Consecutive duplicates
of elements are encoded as lists (N E) where N is the number
of duplicates of the element E.<BR><BR>
Example:<BR>
* (encode '(a a a a b c c a a d e e e e))<BR>
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))<P>
<DT><STRONG><A href="p11.lisp">P11</A>
(*) Modified run-length encoding.</STRONG>
<DD>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) lists.<BR><BR>
Example:<BR>
* (encode-modified '(a a a a b c c a a d e e e e))<BR>
((4 A) B (2 C) (2 A) D (4 E))<P>
<DT><STRONG><A href="p12.lisp">P12</A>
(**) Decode a run-length encoded list.</STRONG>
<DD>Given a run-length code list generated as specified
in problem P11. Construct its uncompressed version.<P>
<DT><STRONG><A href="p13.lisp">P13</A>
(**) Run-length encoding of a list (direct solution).</STRONG>
<DD>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
lists (1 X) by X.<BR><BR>
Example:<BR>
* (encode-direct '(a a a a b c c a a d e e e e))<BR>
((4 A) B (2 C) (2 A) D (4 E))<P>
<DT><STRONG><A href="p14.lisp">P14</A>
(*) Duplicate the elements of a list.</STRONG>
<DD>Example:<BR>
* (dupli '(a b c c d))<BR>
(A A B B C C C C D D)<P>
<DT><STRONG><A href="p15.lisp">P15</A>
(**) Replicate the elements of a list a given number of times.</STRONG>
<DD>Example:<BR>
* (repli '(a b c) 3)<BR>
(A A A B B B C C C)<BR><BR>
<DT><STRONG><A href="p16.lisp">P16</A>
(**) Drop every N'th element from a list.</STRONG>
<DD>Example:<BR>
* (drop '(a b c d e f g h i k) 3)<BR>
(A B D E G H K)<P>
<DT><STRONG><A href="p17.lisp">P17</A>
(*) Split a list into two parts; the length of the first
part is given.</STRONG>
<DD>Do not use any predefined predicates.<BR><BR>
Example:<BR>
* (split '(a b c d e f g h i k) 3)<BR>
( (A B C) (D E F G H I K))<P>
<DT><STRONG><A href="p18.lisp">P18</A>
(**) Extract a slice from a list.</STRONG>
<DD>Given two indices, I and K, the slice is the list
containing the elements between the I'th and K'th element
of the original list (both limits included). Start counting
the elements with 1.<BR><BR>
Example:<BR>
* (slice '(a b c d e f g h i k) 3 7)<BR>
(C D E F G)<P>
<DT><STRONG><A href="p19.lisp">P19</A>
(**) Rotate a list N places to the left.</STRONG>
<DD>Examples:<BR>
* (rotate '(a b c d e f g h) 3)<BR>
(D E F G H A B C)<BR><BR>
* (rotate '(a b c d e f g h) -2)<BR>
(G H A B C D E F)<BR><BR>
Hint: Use the predefined functions length and append,
as well as the result of problem P17.<P>
<DT><STRONG><A href="p20.lisp">P20</A>
(*) Remove the K'th element from a list.</STRONG>
<DD>Example:<BR>
* (remove-at '(a b c d) 2)<BR>
(A C D)<P>
<DT><STRONG><A href="p21.lisp">P21</A>
(*) Insert an element at a given position into a list.</STRONG>
<DD>Example:<BR>
* (insert-at 'alfa '(a b c d) 2)<BR>
(A ALFA B C D)<P>
<DT><STRONG><A href="p22.lisp">P22</A>
(*) Create a list containing all integers within a given range.</STRONG>
<DD>If first argument is smaller than second, produce a list in
decreasing order.<BR>
<DD>Example:<BR>
* (range 4 9)<BR>
(4 5 6 7 8 9)<P>
<DT><STRONG><A href="p23.lisp">P23</A>
(**) Extract a given number of randomly selected elements from a
list.</STRONG>
<DD>The selected items shall be returned in a list.<BR>
Example:<BR>
* (rnd-select '(a b c d e f g h) 3)<BR>
(E D A)<BR><BR>
Hint: Use the built-in random number generator and the
result of problem P20.<P>
<DT><STRONG><A href="p24.lisp">P24</A>
(*) Lotto: Draw N different random numbers from the set 1..M.</STRONG>
<DD>The selected numbers shall be returned in a list.<BR>
Example:<BR>
* (lotto-select 6 49)<BR>
(23 1 17 33 21 37)<BR><BR>
Hint: Combine the solutions of problems P22 and P23.<P>
<DT><STRONG><A href="p25.lisp">P25</A>
(*) Generate a random permutation of the elements of a list.</STRONG>
<DD>Example:<BR>
* (rnd-permu '(a b c d e f))<BR>
(B A D C E F)<BR><BR>
Hint: Use the solution of problem P23.<P>
<DT><STRONG><A href="p26.lisp">P26</A>
(**) Generate the combinations of K distinct objects
chosen from the N elements of a list</STRONG>
<DD>
In how many ways can a committee of 3 be chosen from a group of
12 people? We all know that there are C(12,3) = 220 possibilities
(C(N,K) denotes the well-known binomial coefficients). For pure
mathematicians, this result may be great. But <i>we</i> want to
really generate all the possibilities in a list.<br><br>
Example:<BR>
* (combination 3 '(a b c d e f))<BR>
((A B C) (A B D) (A B E) ... )
<p>
<DT><STRONG><A href="p27.lisp">P27</A>
(**) Group the elements of a set into disjoint subsets.</STRONG>
<DD>
a) 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 and returns them in a list.<br><br>
Example:<br>
* (group3 '(aldo beat carla david evi flip gary hugo ida))<br>
( ( (ALDO BEAT) (CARLA DAVID EVI) (FLIP GARY HUGO IDA) )<br>
... )<br><br>
b) Generalize the above predicate in a way that we can specify a list
of group sizes and the predicate will return a list of groups.<br><br>
Example:<br>
* (group '(aldo beat carla david evi flip gary hugo ida) '(2 2 5))<br>
( ( (ALDO BEAT) (CARLA DAVID) (EVI FLIP GARY HUGO IDA) )<br>
... )<br><br>
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) ...).<br><br>
You may find more about this combinatorial problem in a good book
on discrete mathematics under the term "multinomial coefficients".
<p>
<DT><STRONG><A href="p28.lisp">P28</A>
(**) Sorting a list of lists according to length of sublists</STRONG>
<DD>
a) We suppose that a list contains elements that are
lists themselves. The objective is to sort the elements of this list
according to their <b>length</b>. E.g. short lists first, longer lists
later, or vice versa.<br><br>
Example:<br>
* (lsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))<br>
((O) (D E) (D E) (M N) (A B C) (F G H) (I J K L))<br>
<br>
b) Again, we suppose that a list contains elements that are
lists themselves. But this time the objective is to sort the elements
of this list according to their <b>length frequency</b>; 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.<br><br>
Example:<br>
* (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))<br>
((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n))<br>
<br>
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 twice (there are two list of this
length). And finally, the last three lists have length 2. This is
the most frequent length.
<p>
</DL>
<h2>Arithmetic</h2>
<DL>
<DT><STRONG><A href="p31.lisp">P31</A>
(**) Determine whether a given integer number is prime.</STRONG>
<DD>Example:<BR>
* (is-prime 7)<BR>
T<P>
<DT><STRONG><A href="p32.lisp">P32</A>
(**) Determine the greatest common divisor of two positive integer
numbers.</STRONG>
<DD>Use Euclid's algorithm.<BR>
Example:<BR>
* (gcd 36 63)<BR>
9<P>
<DT><STRONG><A href="p33.lisp">P33</A>
(*) Determine whether two positive integer numbers are coprime.</STRONG>
<DD>Two numbers are coprime if their greatest common divisor equals 1.<BR>
Example:<BR>
* (coprime 35 64)<BR>
T<P>
<DT><STRONG><A href="p34.lisp">P34</A>
(**) Calculate Euler's totient function phi(m).</STRONG>
<DD>Euler's so-called totient function phi(m) is defined as the number
of positive integers r (1 <= r < m) that are coprime to m.<P>
Example: m = 10: r = 1,3,7,9; thus phi(m) = 4.
Note the special case: phi(1) = 1.<P>
* (totient-phi 10)<BR>
4<P>
Find out what the value of phi(m) is if m 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).<P>
<DT><STRONG><A href="p35.lisp">P35</A>
(**) Determine the prime factors of a given positive integer.</STRONG>
<DD>Construct a flat list containing the prime factors
in ascending order.<BR>
Example:<BR>
* (prime-factors 315)<BR>
(3 3 5 7)<P>
<DT><STRONG><A href="p36.lisp">P36</A>
(**) Determine the prime factors of a given positive integer (2).</STRONG>
<DD>Construct a list containing the prime factors and
their multiplicity.<BR>
Example:<BR>
* (prime-factors-mult 315)<BR>
((3 2) (5 1) (7 1))<P>
Hint: The problem is similar to problem
<A href="p13.lisp">P13</a>.<P>
<DT><STRONG><A href="p37.lisp">P37</A>
(**) Calculate Euler's totient function phi(m) (improved).</STRONG>
<DD>See problem P34 for the definition of Euler's totient function.
If the list of the prime factors of a number m is known in the form
of problem P36 then the function phi(m) 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 m. Then phi(m) can be calculated
with the following formula:<P>
phi(m) = (p1 - 1) * p1 ** (m1 - 1) + (p2 - 1) * p2 ** (m2 - 1) +
(p3 - 1) * p3 ** (m3 - 1) + ...<P>
Note that a ** b stands for the b'th power of a.<P>
<DT><STRONG><A href="p38.lisp">P38</A>
(*) Compare the two methods of calculating Euler's totient function.</STRONG>
<DD>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 phi(10090) as an example.<P>
<DT><STRONG><A href="p39.lisp">P39</A>
(*) A list of prime numbers.</STRONG>
<DD> Given a range of integers by its lower and upper limit, construct
a list of all prime numbers in that range.<P>
<DT><STRONG><A href="p40.lisp">P40</A>
(**) Goldbach's conjecture.</STRONG>
<DD>Goldbach's conjecture says that every positive even number
greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23.
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 <em>numerically</em>
confirmed up to very large numbers (much larger than we can go with our
Prolog system). Write a predicate to find the two prime numbers
that sum up to a given even integer.<P>
Example:<BR>
* (goldbach 28)<BR>
(5 23)<P>
<DT><STRONG><A href="p41.lisp">P41</A>
(**) A list of Goldbach compositions.</STRONG>
<DD> Given a range of integers by its lower and upper limit, print
a list of all even numbers and their Goldbach composition.<P>
Example:<BR>
* (goldbach-list 9 20)<BR>
10 = 3 + 7<BR>
12 = 5 + 7<BR>
14 = 3 + 11<BR>
16 = 3 + 13<BR>
18 = 5 + 13<BR>
20 = 3 + 17<P>
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 2..3000.<P>
Example (for a print limit of 50):<BR>
* (goldbach-list 1 2000 50)<BR>
992 = 73 + 919<BR>
1382 = 61 + 1321<BR>
1856 = 67 + 1789<BR>
1928 = 61 + 1867<P>
</DL>
<H2>Logic and Codes</H2>
<DL>
<DT><B><A HREF="p46.lisp">P46</A>
(**) Truth tables for logical expressions.</B>
<DD>Define predicates and/2, or/2, nand/2, nor/2, xor/2, impl/2
and equ/2 (for logical equivalence) which succeed or
fail according to the result of their respective operations; e.g.
and(A,B) will succeed, if and only if both A and B succeed.
Note that A and B can be Prolog goals (not only the constants
true and fail).<P>
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)).<P>
Now, write a predicate table/3 which prints the truth table of a
given logical expression in two variables.<P>
Example:<BR>
* table(A,B,and(A,or(A,B))).<BR>
<TT>
true true true<BR>
true fail true<BR>
fail true fail<BR>
fail fail fail<BR>
</TT>
<P>
<DT><B><A HREF="p47.lisp">P47</A>
(*) Truth tables for logical expressions (2).</B>
<DD>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.<P>
Example:<BR>
* table(A,B, A and (A or not B)).<BR>
<TT>
true true true<BR>
true fail true<BR>
fail true fail<BR>
fail fail fail<BR>
</TT>
<P>
<DT><B><A HREF="p48.lisp">P48</A>
(**) Truth tables for logical expressions (3).</B>
<DD> 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.<P>
Example:<BR>
* table([A,B,C], A and (B or C) equ A and B or A and C).<BR>
<TT>
true true true true<BR>
true true fail true<BR>
true fail true true<BR>
true fail fail true<BR>
fail true true true<BR>
fail true fail true<BR>
fail fail true true<BR>
fail fail fail true<BR>
</TT>
<P>
<DT><B><A HREF="p49.lisp">P49</A>
(**) Gray code.</B>
<DD> An n-bit Gray code is a sequence of n-bit strings constructed
according to certain rules. For example,<br>
n = 1: C(1) = ['0','1'].<br>
n = 2: C(2) = ['00','01','11','10'].<br>
n = 3: C(3) = ['000','001','011','010',´110´,´111´,´101´,´100´].<br><br>
Find out the construction rules and write a predicate with the following
specification:<br><br>
% gray(N,C) :- C is the N-bit Gray code<br><br>
Can you apply the method of "result caching" in order to make the predicate
more efficient, when it is to be used repeatedly?
<p>
<DT><B><A HREF="p50.lisp">P50</A>
(***) Huffman code.</B>
<DD> First of all, consult a good book on discrete mathematics or
algorithms for a detailed description of Huffman codes!<br><br>
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 Hs = [hc(a,'0'),
hc(b,'101'), hc(c,'100'), hc(d,'111'), hc(e,'1101'),
hc(f,'1100')] [hc(a,'01'),...etc.].
The task shall be performed by the predicate huffman/2 defined as follows:
<br><br>
% huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs
<p>
</DL>
<H2>Binary Trees</H2>
<p>
<strong>
<font color="red">A binary tree is either empty or it is composed of a root
element and two successors, which are binary trees themselves.</font></strong>
<img src="p67.gif" align="left" hspace="20">
<br>In Lisp we represent the empty tree by 'nil' and the
non-empty tree by the list (X L R), where X denotes the root
node and L and R denote the left and right subtree, respectively.
The example tree depicted opposite is therefore represented by the
following list: <br><br>
(a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil)))
<br><br>
Other examples are a binary tree that consists of a root node only:<br><br>
(a nil nil) or an empty binary tree: nil.
</p>
<p>
You can check your predicates using these example trees. They are
given as test cases in <a href="p54.lisp">p54.lisp</a>.
</p>
<DL>
<DT><B><A HREF="p54A.lisp">P54A</A>
(*) Check whether a given term represents a binary tree</B>
<DD>Write a predicate istree which returns true if and only if its argument
is a list representing a binary tree.<br>
Example:<br>
* (istree (a (b nil nil) nil))<br>
T<br>
* (istree (a (b nil nil)))<br>
NIL<p>
<DT><B><A HREF="p55.lisp">P55</A>
(**) Construct completely balanced binary trees</B>
<DD>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.<br><br>
Write a function cbal-tree to construct completely balanced
binary trees for a given number of nodes. The predicate should
generate all solutions via backtracking. Put the letter 'x'
as information into all nodes of the tree.<br>
Example:<br>
* cbal-tree(4,T).<br>
T = t(x, t(x, nil, nil), t(x, nil, t(x, nil, nil))) ;<br>
T = t(x, t(x, nil, nil), t(x, t(x, nil, nil), nil)) ;<br>
etc......No<p>
<DT><B><A HREF="p56.lisp">P56</A>
(**) Symmetric binary trees</B>
<DD>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 predicate symmetric/1 to check whether a given binary
tree is symmetric. <strong>Hint:</strong>
Write a predicate 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.<p>
<DT><B><A HREF="p57.lisp">P57</A>
(**) Binary search trees (dictionaries)</B>
<DD>Use the predicate add/3, developed in chapter 4 of the course,
to write a predicate to construct a binary search tree
from a list of integer numbers.<br>
Example:<br>
* construct([3,2,5,7,1],T).<br>
T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil)))<br><br>
Then use this predicate to test the solution of the problem P56.<br>
Example:<br>
* test-symmetric([5,3,18,1,4,12,21]).<br>
Yes<br>
* test-symmetric([3,2,5,7,1]).<br>
No<p>
<DT><B><A HREF="p58.lisp">P58</A>
(**) Generate-and-test paradigm</B>
<DD>Apply the generate-and-test paradigm to construct all symmetric,
completely balanced binary trees with a given number of nodes.
Example:<br>
* sym-cbal-trees(5,Ts).<br>
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)))]
<br><br>
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 predicate.<p>
<DT><B><A HREF="p59.lisp">P59</A>
(**) Construct height-balanced binary trees</B>
<DD>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.<br><br>
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.<br>
Example:<br>
* hbal-tree(3,T).<br>
T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil),
t(x, nil, nil))) ;<br>
T = t(x, t(x, t(x, nil, nil), t(x, nil, nil)), t(x, t(x, nil, nil),
nil)) ;<br>
etc......No<p>
<DT><B><A HREF="p60.lisp">P60</A>
(**) Construct height-balanced binary trees with a given number of nodes</B>
<DD>Consider a height-balanced binary tree of height H. What is the
maximum number of nodes it can contain?<br>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:<br>
<br>
% minNodes(H,N) :- N is the minimum number of nodes in a
height-balanced binary tree of height H.<br>
(integer,integer), (+,?)<br><br>
On the other hand, we might ask: what is the maximum height H a
height-balanced binary tree with N nodes can have?<br><br>
% maxHeight(N,H) :- H is the maximum height of a height-balanced
binary tree with N nodes<br>
(integer,integer), (+,?)<br><br>
Now, we can attack the main problem: construct all the
height-balanced binary trees with a given nuber of nodes.<br><br>
% hbal-tree-nodes(N,T) :- T is a height-balanced binary tree with
N nodes.<br><br>
Find out how many height-balanced trees exist for N = 15.<p>
<DT><B><A HREF="p61.lisp">P61</A>
(*) Count the leaves of a binary tree</B>
<DD>A leaf is a node with no successors. Write a predicate
count-leaves/2 to count them.
<br><br>
% count-leaves(T,N) :- the binary tree T has N leaves
<p>
<DT><B><A HREF="p61A.lisp">P61A</A>
(*) Collect the leaves of a binary tree in a list</B>
<DD>A leaf is a node with no successors. Write a predicate
leaves/2 to collect them in a list.
<br><br>
% leaves(T,S) :- S is the list of all leaves of the binary tree T
<p>
<DT><B><A HREF="p62.lisp">P62</A>
(*) Collect the internal nodes of a binary tree in a list</B>
<DD>An internal node of a binary tree has either one or two non-empty
successors. Write a predicate internals/2 to collect
them in a list.
<br><br>
% internals(T,S) :- S is the list of internal nodes of
the binary tree T.
<p>
<DT><B><A HREF="p62B.lisp">P62B</A>
(*) Collect the nodes at a given level in a list</B>
<DD>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 predicate atlevel/3 to collect all nodes at a given
level in a list.
<br><br>
% atlevel(T,L,S) :- S is the list of nodes of the binary tree
T at level L<br><br>
Using atlevel/3 it is easy to construct a predicate levelorder/2
which creates the level-order sequence of the nodes. However,
there are more efficient ways to do that.
<p>
<DT><B><A HREF="p63.lisp">P63</A>
(**) Construct a complete binary tree</B>
<DD>A <em>complete</em> 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.<br><br>
Particularly, complete binary trees are used as data structures
(or addressing schemes) for heaps.<br><br>
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 2*A and 2*A+1,
respectively, supposed the successors do exist. This fact can
be used to elegantly construct a complete binary tree structure.
Write a predicate complete-binary-tree/2 with the following
specification:
<br><br>
% complete-binary-tree(N,T) :- T is a complete binary tree with
N nodes. (+,?)<br><br>
Test your predicate in an appropriate way.<p>
<DT><B><A HREF="p64.lisp">P64</A>
(**) Layout a binary tree (1)</B>
<DD> 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.<br><br>
<img src="p64.gif" align="left" hspace="20">
In this layout strategy, the position of a node <i>v</i>
is obtained by the following two rules:<br><br>
<ul>
<li><i>x(v)</i> is equal to the position of the node <i>v</i>
in the <b>inorder</b> sequence</li>
<li><i>y(v)</i> is equal to the depth of the node <i>v</i> in
the tree</li>
</ul><br><br>
In order to store the position of the nodes, we extend the Prolog
term representing a node (and its successors) as follows:
<br clear="left"><br>
% nil represents the empty tree (as usual)<br>
% t(W,X,Y,L,R) represents a (non-empty) binary tree with root
W "positioned" at (X,Y), and subtrees L and R<br><br>
Write a predicate layout-binary-tree/2 with the following
specification:
<br><br>
% layout-binary-tree(T,PT) :- PT is the "positioned" binary
tree obtained from the binary tree T. (+,?)<br><br>
Test your predicate in an appropriate way.
<br clear="left"><p>
<DT><B><A HREF="p65.lisp">P65</A>
(**) Layout a binary tree (2)</B>
<DD><img src="p65.gif" align="left" hspace="20">
An alternative layout method is depicted in the illustration
opposite. Find out the rules and write the corresponding
Prolog predicate. Hint: On a given level, the horizontal
distance between neighboring nodes is constant.<br><br>
Use the same conventions as in problem P64 and test your
predicate in an appropriate way.
<br clear="left"><p>
<DT><B><A HREF="p66.lisp">P66</A>
(***) Layout a binary tree (3)</B>
<DD><img src="p66.gif" align="right" hspace="20">
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 predicate.
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?<br><br>
Use the same conventions as in problem P64 and P65 and
test your predicate in an appropriate way. Note: This is
a difficult problem. Don't give up too early!<br><br>
Which layout do you like most?
<br clear="right"><p>
<DT><B><A HREF="p67a.lisp">P67</A>
(**) A string representation of binary trees</B>
<DD><img src="p67.gif" align="left" hspace="20">
<br>Somebody represents binary trees as strings of the
following type (see example opposite):<br><br>
a(b(d,e),c(,f(g,)))<br><br>
<b><A HREF="p67a.lisp">a)</A></b>
Write a Prolog predicate which generates this string
representation, if the tree is given as usual (as nil or
t(X,L,R) term). Then write a predicate which does
this inverse; i.e. given the string representation,
construct the tree in the usual form. Finally, combine the
two predicates in a single predicate tree-string/2 which
can be used in both directions.<br><br>
<b><A HREF="p67b.lisp">b)</A></b>
Write the same predicate tree-string/2 using difference lists
and a single predicate tree-dlist/2 which does the conversion
between a tree and a difference list in both directions.<br><br>
For simplicity, suppose the information in the nodes is a single
letter and there are no spaces in the string.
<br clear="left"><p>
<DT><B><A HREF="p68a.lisp">P68</A>
(**) Preorder and inorder sequences of binary trees</B>
<DD>We consider binary trees with nodes that are identified by
single lower-case letters, as in the example of problem P67.<br><br>
<b><A HREF="p68a.lisp">a)</A></b>
Write predicates 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.<br><br>
<b><A HREF="p68b.lisp">b)</A></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.<br><br>
<b><A HREF="p68c.lisp">c)</A></b>
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 predicate pre-in-tree/3 that does
the job.<br><br>
<b><A HREF="p68d.lisp">d)</A></b>
Solve problems a) to c) using difference lists. Cool! Use the
predefined predicate time/1 to compare the solutions.<br><br>
What happens if the same character appears in more than one node.
Try for instance pre-in-tree(aba,baa,T).
<p>
<DT><B><A HREF="p69.lisp">P69</A>
(**) Dotstring representation of binary trees</B>
<DD>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 <tt>'abd..e..c.fg...'</tt>. First, try to establish a
syntax (BNF or syntax diagrams) and then write a predicate
tree-dotstring/2 which does the conversion in both directions.
Use difference lists.
<p>
</DL>
<H2>Multiway Trees</H2>
<strong>
<font color="red">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.</font></strong> <br><br>
<img src="p70.gif" align="left" hspace="20">
<br>In Prolog we represent a multiway tree by a term t(X,F), where X denotes
the root node and F denotes the forest of successor trees (a Prolog list).
The example tree depicted opposite is therefore represented by the
following Prolog term:
<pre>
T = t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])
</pre>
</p>
<br clear="left">
<DL>
<DT><B><A HREF="p70B.lisp">P70B</A>
(*) Check whether a given term represents a multiway tree</B>
<DD>Write a predicate istree/1 which succeeds if and only if its argument
is a Prolog term representing a multiway tree.<br>
Example:<br>
* istree(t(a,[t(f,[t(g,[])]),t(c,[]),t(b,[t(d,[]),t(e,[])])])).<br>
Yes<br><br>
<DT><B><A HREF="p70C.lisp">P70C</A>
(*) Count the nodes of a multiway tree</B>
<DD>Write a predicate nnodes/1 which counts the nodes of a given
multiway tree.<br>
Example:<br>
* nnodes(t(a,[t(f,[])]),N).<br>
N = 2<br><br>
Write another version of the predicate that allows
for a flow pattern (o,i).<br><br>
<DT><B><A HREF="p70.lisp">P70</A>
(**) Tree construction from a node string</B>
<img src="p70.gif" align="right" hspace="20">
<DD>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.<br><br>
By this rule, the tree in the figure opposite is
represented as: <tt>afg^^c^bd^e^^^</tt>
<br><br>
Define the syntax of the string and write a predicate tree(String,Tree)
to construct the Tree when the String is given. Work with atoms (instead
of strings). Make your predicate work in both directions.
<br clear="right">
<p>
<DT><B><A HREF="p71.lisp">P71</A>
(*) Determine the internal path length of a tree</B>
<DD>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 predicate ipl(Tree,IPL) for the flow
pattern (+,-).
<p>
<DT><B><A HREF="p72.lisp">P72</A>
(*) Construct the bottom-up order sequence of the tree nodes</B>
<DD>Write a predicate 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 predicate
backwords?
<p>
<DT><B><A HREF="p73.lisp">P73</A>
(**) Lisp-like tree representation</B>
<DD>There is a particular notation for multiway trees in <b>Lisp</b>.
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.
<br /><br />
The following pictures show how multiway tree structures are
represented in Lisp.
<br />
<img src="p73.png" vspace="15">
<br />
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 predicate tree-ltl(T,LTL) which constructs the "lispy
token list" LTL if the tree is given as term T in the usual
Prolog notation.<br /><br />
Example:<br>
* tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL).<br>
LTL = ['(', a, '(', b, c, ')', ')']
<p>
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.
<p>
</DL>
<H2>Graphs</H2>
<strong>
<font color="red">A graph is defined as a set of <i>nodes</i>
and a set of <i>edges</i>, where each edge is a pair of nodes.</font></strong>
<p>
There are several ways to represent graphs in Prolog. One method is to
represent each edge separately as one clause (fact). In this form,
the graph depicted below is represented as the following predicate:
<img src="graph1.gif" align="left" hspace="20" vspace="10">
<pre>
edge(h,g).
edge(k,f).
edge(f,b).
...
</pre>
We call this <i>edge-clause form</i>. 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 Prolog term to represent the example graph:
<pre>
graph([b,c,d,f,g,h,k],[e(b,c),e(b,f),e(c,f),e(f,k),e(g,h)])
</pre>
We call this <i>graph-term form</i>. Note, that the lists are kept sorted,
they are really <i>sets</i>, without duplicated elements. Each edge
appears only once in the edge list; i.e. an edge from
a node x to another node y is represented as e(x,y), the term e(y,x)
is not present. <b>The graph-term form is our default representation.</b>
In SWI-Prolog there are predefined predicates to work
with sets.
<p>
A third representation method is to associate with each node the set
of nodes that are adjacent to that node. We call this the
<i>adjacency-list form</i>. In our example:
<pre>
[n(b,[c,f]), n(c,[b,f]), n(d,[]), n(f,[b,c,k]), ...]
</pre>
The representations we introduced so far are Prolog terms 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 atoms and terms of
the type X-Y (i.e. functor '-' and arity 2). The atoms stand for
isolated nodes, the X-Y terms describe edges. If an X appears as an
endpoint of an edge, it is automatically defined as a node.
Our example could be written as:<br>
<pre>
[b-c, f-c, g-h, d, f-b, k-f, h-g]
</pre>
We call this the <i>human-friendly form</i>. 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. (Actually, isolated
nodes do not even have to be atoms in the Prolog sense, they can
be compound terms, as in <tt>d(3.75,blue)</tt> instead of d in the example).
<p>
<br clear="left">
<img src="graph2.gif" align="left" hspace="20" vspace="10">
When the edges are <i>directed</i> we call them <i>arcs</i>. These
are represented by <i>ordered</i> pairs. Such a graph is called
<b>directed graph</b>. To represent a directed graph, the forms
discussed above are slightly modified. The example graph opposite
is represented as follows:
<p>
<dl>
<dt><i>Arc-clause form</i></dt>
<dd><tt>arc(s,u).<br>arc(u,r).<br>...</tt></dd>
<p>
<dt><i>Graph-term form</i></dt>
<dd><tt>digraph([r,s,t,u,v],[a(s,r),a(s,u),a(u,r),a(u,s),a(v,u)])</tt></dd>
<p>
<dt><i>Adjacency-list form</i></dt>
<dd><tt>[n(r,[]),n(s,[r,u]),n(t,[]),n(u,[r]),n(v,[u])]</tt><br>
Note that the adjacency-list does not have the information on whether
it is a graph or a digraph.</dd>
<p>
<dt><i>Human-friendly form</i></dt>
<dd><tt>[s > r, t, u > r, s > u, u > s, v > u] </tt></dd>
<p>
</dl>
<p>
<br clear="left">
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 <tt>city('London',4711)</tt>. On the other hand, for
edges we have to extend our notation. Graphs with additional information
attached to edges are called <b>labelled graphs</b>.<p>
<img src="graph3.gif" align="left" hspace="20" vspace="10">
<dl>
<dt><i>Arc-clause form</i></dt>
<dd><tt>arc(m,q,7).<br>arc(p,q,9).<br>arc(p,m,5).</tt></dd>
<p>
<dt><i>Graph-term form</i></dt>
<dd><tt>digraph([k,m,p,q],[a(m,p,7),a(p,m,5),a(p,q,9)])</tt></dd>
<p>
<dt><i>Adjacency-list form</i></dt>
<dd><tt>[n(k,[]),n(m,[q/7]),n(p,[m/5,q/9]),n(q,[])]</tt><br>
Notice how the edge information has been packed into a term with
functor '/' and arity 2, together with the corresponding node.</dd>