From 6c75a073c0c4e9c2e747bf127c3d5f52642fa28e Mon Sep 17 00:00:00 2001 From: Sergiu Ivanov Date: Fri, 20 Mar 2020 22:15:29 +0100 Subject: [PATCH] networks: Add random-boolean-table, random-boolean-function, random-boolean-function/list. --- networks-tests.rkt | 10 +++++++++- networks.rkt | 22 +++++++++++++++++----- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/networks-tests.rkt b/networks-tests.rkt index 1bc11b0..91aefbd 100644 --- a/networks-tests.rkt +++ b/networks-tests.rkt @@ -224,4 +224,12 @@ (let ([f1 (stream-first (enumerate-boolean-functions 1))] [f1/list (stream-first (enumerate-boolean-functions/list 1))]) (check-false (f1 #f)) (check-false (f1 #t)) - (check-false (f1/list '(#f))) (check-false (f1/list '(#t))))) + (check-false (f1/list '(#f))) (check-false (f1/list '(#t)))) + + (random-seed 0) + (check-equal? (random-boolean-table 2) '((#f #f #t) (#f #t #t) (#t #f #f) (#t #t #f))) + (let ([f (random-boolean-function 2)]) + (check-true (f #f #f)) (check-false (f #f #t)) (check-true (f #t #f)) (check-false (f #t #t))) + (let ([f (random-boolean-function/list 2)]) + (check-false (f '(#f #f))) (check-true (f '(#f #t))) + (check-true (f '(#t #f))) (check-false (f '(#t #t))))) diff --git a/networks.rkt b/networks.rkt index ed1db1c..fd2509c 100644 --- a/networks.rkt +++ b/networks.rkt @@ -65,7 +65,10 @@ [boolean-power/stream (-> number? (stream/c (listof boolean?)))] [enumerate-boolean-tables (-> number? (stream/c (listof (*list/c any/c any/c))))] [enumerate-boolean-functions (-> number? (stream/c procedure?))] - [enumerate-boolean-functions/list (-> number? (stream/c procedure?))]) + [enumerate-boolean-functions/list (-> number? (stream/c procedure?))] + [random-boolean-table (-> number? (*list/c any/c any/c))] + [random-boolean-function (-> number? procedure?)] + [random-boolean-function/list (-> number? procedure?)]) ;; Predicates (contract-out [variable? (-> any/c boolean?)] [state? (-> any/c boolean?)] @@ -475,7 +478,16 @@ (stream-map table->function/list (enumerate-boolean-tables n))) ;;; Generates a random truth table for a Boolean function of arity n. -#; -(define (random-boolean-function n) - (let ([inputs (boolean-power-n n)]) - )) +(define (random-boolean-table n) + (define/match (num->bool x) [(0) #f] [(1) #t]) + (define inputs (boolean-power n)) + (define outputs (stream-take (in-random 2) (expt 2 n))) + (for/list ([i inputs] [o outputs]) + (append i (list (num->bool o))))) + +;;; Generates a random Boolean function of arity n. +(define random-boolean-function (compose table->function random-boolean-table)) + +;;; Like random-boolean-function, but the constructed function takes a +;;; list of arguments. +(define random-boolean-function/list (compose table->function/list random-boolean-table))