]> gitweb.factorcode.org Git - factor.git/blob - extra/benchmark/backtrack/backtrack.factor
f62ca40719c7ab0de082896797086fbd365f6eb1
[factor.git] / extra / benchmark / backtrack / backtrack.factor
1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: backtrack shuffle math math.ranges quotations locals fry
4 kernel words io memoize macros prettyprint sequences assocs
5 combinators namespaces ;
6 IN: benchmark.backtrack
7
8 ! This was suggested by Dr_Ford. Compute the number of quadruples
9 ! (a,b,c,d) with 1 <= a,b,c,d <= 10 such that we can make 24 by
10 ! placing them on the stack, and applying the operations
11 ! +, -, * and rot as many times as we wish.
12
13 : nop ( -- ) ;
14
15 : do-something ( a b -- c )
16     { + - * } amb-execute ;
17
18 : some-rots ( a b c -- a b c )
19     ! Try to rot 0, 1 or 2 times.
20     { nop rot -rot } amb-execute ;
21
22 MEMO: 24-from-1 ( a -- ? )
23     24 = ;
24
25 MEMO: 24-from-2 ( a b -- ? )
26     [ do-something 24-from-1 ] [ 2drop ] if-amb ;
27
28 MEMO: 24-from-3 ( a b c -- ? )
29     [ some-rots do-something 24-from-2 ] [ 3drop ] if-amb ;
30
31 MEMO: 24-from-4 ( a b c d -- ? )
32     [ some-rots do-something 24-from-3 ] [ 4drop ] if-amb ;
33
34 : find-impossible-24 ( -- n )
35     10 [1..b] [| a |
36         10 [1..b] [| b |
37             10 [1..b] [| c |
38                 10 [1..b] [| d |
39                     a b c d 24-from-4
40                 ] count
41             ] map-sum
42         ] map-sum
43     ] map-sum ;
44
45 CONSTANT: 24-words { 24-from-1 24-from-2 24-from-3 24-from-4 }
46
47 : backtrack-benchmark ( -- )
48     24-words [ reset-memoized ] each
49     find-impossible-24 6479 assert=
50     24-words [ "memoize" word-prop assoc-size ] map
51     { 1588 5137 4995 10000 } assert= ;
52
53 MAIN: backtrack-benchmark