-
Notifications
You must be signed in to change notification settings - Fork 135
/
99problems-41-to-50.t
412 lines (356 loc) · 12.3 KB
/
99problems-41-to-50.t
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
use v6;
use Test;
plan 13;
{
# P41 (**) A list of Goldbach compositions.
#
# Given a range of integers by its lower and upper limit, print 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 2..3000.
#
# Example (for a print limit of 50):
# * (goldbach-list 1 2000 50)
# 992 = 73 + 919
# 1382 = 61 + 1321
# 1856 = 67 + 1789
# 1928 = 61 + 1867
sub primes($from, $to) {
my @p = (2);
for 3..$to -> $x {
push @p, $x unless grep { $x % $_ == 0 }, 2..ceiling sqrt $x;
}
grep { $_ >= $from }, @p;
}
sub goldbach($n) {
my @p = primes(1, $n-1);
for @p -> $x {
for @p -> $y {
return ($x,$y) if $x+$y == $n;
}
}
0;
}
sub goldbachs($from, $to) {
[ map { [$_, goldbach $_] }, grep { $_ % 2 == 0 }, $from .. $to ]
}
is goldbachs(3, 11), [[4, 2, 2], [6, 3, 3], [8, 3, 5], [10, 3, 7]], 'P41 (**) A list of Goldbach compositions.';
}
{
# P46 (**) Truth tables for logical expressions.
#
# 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).
#
# 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 predicate table/3 which prints the truth table of a given logical
# expression in two variables.
#
# Example:
# * table(A,B,and(A,or(A,B))).
# true true true
# true fail true
# fail true fail
# fail fail fail
# --
grammar LogicalExpr {
rule TOP {
'table(' ~ ').' [
[ <id> ',' ]* <expr=.term>
]
}
token id {<[ A .. Z ]>}
proto token op {*}
token op:sym<and> {<sym>}
token op:sym<or> {<sym>}
token op:sym<nand> {<sym>}
token op:sym<nor> {<sym>}
token op:sym<xor> {<sym>}
token op:sym<impl> {<sym>}
token op:sym<equ> {<sym>}
proto token term {*}
token term:sym<var> {<id>}
token term:sym<func> {<op>'(' ~ ')' <expr=.term> **2% ','}
method truth-table($expr,$actions) {
$.parse($expr, :actions($actions) );
my @vars = @( $/.ast<vars> );
my $truth-func = $/.ast<func>;
sub the-truth(@vals) {
# setup symbol table and compute result
our %*VAR = @vars Z=> @vals;
@vals.push: $truth-func();
@vals.map: {$_ ?? 'true' !! 'fail'};
}
my @table;
# generate the truth table, as per spec
for (0 .. 2 ** @vars-1).reverse -> $mask {
my $n = @vars-1;
my @vals = @vars.map: {($mask +& (2**$n--))};
@table.push: ~the-truth(@vals);
}
make @table;
}
}
class LogicalExpr::Actions {
method TOP($/) {
make {
vars => @<id>>>.ast,
func => $<expr>.ast,
};
}
method id($/) {make ~$/}
# generate closures. defer processing
method op:sym<and>($/) {make sub ($a, $b){ $a and $b }}
method op:sym<or>($/) {make sub ($a, $b){ $a or $b }}
method op:sym<nand>($/) {make sub ($a, $b){ !($a and !$b) }}
method op:sym<nor>($/) {make sub ($a, $b){ !($a or $b) }}
method op:sym<xor>($/) {make sub ($a, $b){ $a != $b }}
method op:sym<impl>($/) {make sub ($a, $b){ !(!$a and $b) }}
method op:sym<equ>($/) {make sub ($a, $b){ $a == $b }}
method term:sym<var>($/) {
my $id = ~$<id>;
make sub () {
%*VAR{$id} // die "unknown variable: $id"
}
}
method term:sym<func>($/) {
my $func = $<op>.ast;
my @args = @<expr>>>.ast;
make sub () {
$func( |@args.map: {.()} )
}
}
}
my $parser = LogicalExpr.new;
my $actions = LogicalExpr::Actions.new;
is-deeply $parser.truth-table('table(A,B,and(A,or(A,B))).',$actions),
['true true true',
'true fail true',
'fail true fail',
'fail fail fail',],
'P46 (**) Truth tables for logical expressions.';
}
{
# P47 (*) 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 fail true
# fail true fail
# fail fail fail
grammar LogicalExpr::Infix is LogicalExpr {
rule TOP {
'table(' ~ ').' [
[ <id> ',' ]* <expr(3)>
]
}
# handle precedence via multi-dispatch and recursion
multi rule expr(0) { <term> }
multi rule expr($p) { <expr($p-1)> *%[ <?before <pred($p)>> <op> ] }
# precedence loosest to tightest - Supposedly Javaish.
multi token pred(3) {equ|impl}
multi token pred(2) {or|nor|xor}
multi token pred(1) {and|nand}
# assume tight binding for 'not'
rule term:sym<not> { <sym> <term=.expr(3)> }
rule term:sym<paren> { '(' ~ ')' [ <term=.expr(3)> ] }
}
class LogicalExpr::Infix::Actions is LogicalExpr::Actions {
method expr($/) {
if $<term> {
# simple term
make $<term>.ast;
}
else {
my @args = @<expr>>>.ast;
my @ops = @<op>>>.ast;
make sub {
# left associative chain expressions + infix operations
my $result = @args[0].();
for @ops.keys -> $i {
$result = @ops[$i]( $result, @args[$i+1].() );
}
return $result;
}
}
}
method term:sym<not>($/) {make sub {not $<term>.ast()} }
method term:sym<paren>($/) { make $<term>.ast }
}
my $parser = LogicalExpr::Infix.new;
my $actions = LogicalExpr::Infix::Actions.new;
is-deeply $parser.truth-table('table(A,B, A and (A or not B)).',$actions),
['true true true',
'true fail true',
'fail true fail',
'fail fail fail',],
'P47 (**) Truth tables for logical expressions (2).';
}
{
# P48 (**) 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 fail true
# true fail true true
# true fail fail true
# fail true true true
# fail true fail true
# fail fail true true
# fail fail fail true
# w'eve already done the heavy lifting
my $parser = LogicalExpr::Infix.new;
my $actions = LogicalExpr::Infix::Actions.new;
is-deeply $parser.truth-table('table(A,B,C, A and (B or C) equ A and B or A and C).',$actions),
['true true true true',
'true true fail true',
'true fail true true',
'true fail fail true',
'fail true true true',
'fail true fail true',
'fail fail true true',
'fail fail fail true',],
'P48 (**) Truth tables for logical expressions (3).';
}
{
# P49 (**) Gray code.
#
# An n-bit Gray code is a sequence of n-bit strings constructed according to
# certain rules. For example,
#
# n = 1: C(1) = ['0','1'].
# n = 2: C(2) = ['00','01','11','10'].
# n = 3: C(3) = ['000','001','011','010','110','111','101','100'].
#
# Find out the construction rules and write a predicate with the following
# specification:
#
# % gray(N,C) :- C is the N-bit Gray code
#
# Can you apply the method of "result caching" in order to make the predicate
# more efficient, when it is to be used repeatedly?
use experimental :cached;
sub gray($n) is cached {
return [''] if $n == 0;
[flat '0' xx 2**($n-1) >>~<< gray($n-1),
'1' xx 2 ** ($n-1) >>~<< gray($n-1).reverse];
}
is-deeply gray(0), [''];
is-deeply gray(1), [<0 1>».Str];
is-deeply gray(2), [<00 01 11 10>».Str];
is-deeply gray(3), [<000 001 011 010 110 111 101 100>».Str];
}
{
sub gray2($n) {
return [''] if $n == 0;
(state @g)[$n] //= [flat '0' xx 2**($n-1) >>~<< gray2($n-1),
'1' xx 2**($n-1) >>~<< gray2($n-1).reverse];
}
is-deeply gray2(0), [''];
is-deeply gray2(1), [<0 1>».Str];
is-deeply gray2(2), [<00 01 11 10>».Str];
is-deeply gray2(3), [<000 001 011 010 110 111 101 100>».Str];
}
{
# P50 (***) 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 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:
#
# % huffman(Fs,Hs) :- Hs is the Huffman code table for the frequency table Fs
#
# Binary Trees
#
# A binary tree is either empty or it is composed of a root element and two
# successors, which are binary trees themselves. 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:
#
# (a (b (d nil nil) (e nil nil)) (c nil (f (g nil nil) nil)))
#
# Other examples are a binary tree that consists of a root node only:
#
# (a nil nil) or an empty binary tree: nil.
#
# You can check your predicates using these example trees. They are given as test
# cases in p54.lisp.
my @fr = (
$['a', 45],
$['b', 13],
$['c', 12],
$['d', 16],
$['e', 9 ],
$['f', 5 ],
);
my %expected = (
'a' => '0',
'b' => '101',
'c' => '100',
'd' => '111',
'e' => '1101',
'f' => '1100'
);
my @c = @fr;
# build the tree:
while @c.elems > 1 {
# Choose lowest frequency nodes and combine. Break ties
# to create the tree the same way each time.
@c = sort { $^a[1] <=> $^b[1] || $^a[0] cmp $^b[0] }, @c;
my $a = shift @c;
my $b = shift @c;
unshift @c, $[ $[$a[0], $b[0]], $a[1] + $b[1]];
}
my %res;
sub traverse ($a, Str $code = "") {
if $a ~~ Str {
%res{$a} = $code;
} else {
traverse($a[0], $code ~ '0');
traverse($a[1], $code ~ '1');
}
}
traverse(@c[0][0]);
is(~%res.sort, ~%expected.sort, "P50 (**) Huffman tree builds correctly");
}
# vim: ft=perl6