Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Generate a truth table from input string

by Anonymous Monk
on May 14, 2008 at 11:29 UTC ( [id://686495]=note: print w/replies, xml ) Need Help??


in reply to Generate a truth table from input string

thanks guys... i am new to perl, with all ur suggestions and inputs from perlmonks, i finally came up with this small piece of code ---truthtable.pl
#my $bool_func = "((S0'*B)|((!S0)|A))'"; my $bool_func = "(a'+b'+c')"; #my $bool_func = "((A0)'+A1'+!(a2))'"; # convert the function into equivalent perl expression $bool_func =~ s/\((\w*)\)'/~($1)/g; # to convert the case where variable is represented as (A)' to ~(A) $bool_func =~ s/(\w*)'/~$1/g; # to convert the case where variable is represented as A' to ~A $bool_func =~ s/(^\(.*\))~$/~($1)/g; # to convert the case where expression is (EXPR)' to ~(EXPR) $bool_func =~ s/!/~/g; # to convert the case where not is represented by ! to ~ $bool_func =~ s/\+/|/g; $bool_func =~ s/\*/&/g; (my $perl_expr = $bool_func) =~ s/([a-zA-Z]\w*)/\$val{$1}/g; ## end conversion print "equivalent expression: $bool_func\n"; # get the variables my @vars = do { my %seen; grep !$seen{$_}++, $bool_func =~ /([a-zA-Z]\w*)/g; }; print "$vars[2], $vars[1], $vars[0], out\n"; # evaluate and print the output for my $assignment ( 0 .. (2**@vars)-1 ) { my %val; $val{$vars[$_]} = ( $assignment >> $_ ) & 1 for 0 .. $#vars; my $result = eval $perl_expr & 1; print join(", ", map { "$val{$_}" }keys %val)," =$result\n"; }
----end--- output---
equivalent expression: (~a|~b|~c) c, b, a, out 0, 0, 0 = 1 0, 1, 0 = 1 0, 0, 1 = 1 0, 1, 1 = 1 1, 0, 0 = 1 1, 1, 0 = 1 1, 0, 1 = 1 1, 1, 1 = 0
thanks again

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://686495]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-03-28 12:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found