1 ! Copyright © 2008 Reginald Keith Ford II
3 USING: accessors backtrack combinators continuations formatting fry io
4 kernel math prettyprint quotations random sequences shuffle ;
9 : ?/ ( a b -- c ) [ drop 1/0. ] [ / ] if-zero ;
11 : do-operation ( a b -- c )
12 { + - * ?/ } amb-execute ;
14 : permute-2 ( a b -- a b )
15 { nop swap } amb-execute ;
17 : permute-3 ( a b c -- a b c )
18 { nop rot -rot swap spin swapd } amb-execute ;
20 : makes-24? ( a b c d -- ? )
22 permute-3 do-operation
23 permute-3 do-operation
24 permute-2 do-operation
28 : random-4 ( -- array )
29 4 [ 10 random ] replicate ;
31 : make-24 ( -- array )
32 f [ dup first4 makes-24? ] [ drop random-4 ] do until ;
34 : q ( -- obj ) "quit" ;
36 CONSTANT: (operators) { + - * / rot swap q }
38 : operators ( array -- operators )
39 length 3 < [ \ rot (operators) remove ] [ (operators) ] if ;
41 : find-operator ( operators string -- word/f )
42 '[ name>> _ = ] find nip ;
44 : get-operator ( operators -- word )
45 dup "Operators: %u\n" printf flush
46 dup readln find-operator [ ] [
47 "Operator not found..." print get-operator
50 : try-operator ( array -- array )
52 [ dup operators get-operator 1quotation with-datastack ]
55 : end-game ( array -- )
59 "%d is not 24... You lose." sprintf
62 : quit-game ( array -- )
63 drop "you're a quitter" print ;
65 : play-24 ( array -- )
67 { [ dup length 1 = ] [ end-game ] }
68 { [ dup last "quit" = ] [ quit-game ] }
69 [ try-operator play-24 ]
72 : 24-game ( -- ) make-24 play-24 ;