in reply to Re^6: Boolean math: Fill in the blanks.
in thread Boolean math: Fill in the blanks.
The output has more parentheses than strictly necessary
Don't add parens within runs of | and runs of &, just around them.
#!/usr/bin/perl use strict; use warnings; my $bits = shift; my $den = 2**$bits; for my $num (1 .. $den-1) { for ( sprintf "%0${bits}b", $num ) { s/10*$/R/; $_ .= ')' x s/(?<=1)(?=0)|(?<=0)(?=1)/(/g; s/0/R & /g; s/1/R | /g; print "E($num/$den) = $_\n"; } }
E(1/32) = R & R & R & R & R E(2/32) = R & R & R & R E(3/32) = R & R & R & (R | R) E(4/32) = R & R & R E(5/32) = R & R & (R | (R & R)) E(6/32) = R & R & (R | R) E(7/32) = R & R & (R | R | R) E(8/32) = R & R E(9/32) = R & (R | (R & R & R)) E(10/32) = R & (R | (R & R)) E(11/32) = R & (R | (R & (R | R))) E(12/32) = R & (R | R) E(13/32) = R & (R | R | (R & R)) E(14/32) = R & (R | R | R) E(15/32) = R & (R | R | R | R) E(16/32) = R E(17/32) = R | (R & R & R & R) E(18/32) = R | (R & R & R) E(19/32) = R | (R & R & (R | R)) E(20/32) = R | (R & R) E(21/32) = R | (R & (R | (R & R))) E(22/32) = R | (R & (R | R)) E(23/32) = R | (R & (R | R | R)) E(24/32) = R | R E(25/32) = R | R | (R & R & R) E(26/32) = R | R | (R & R) E(27/32) = R | R | (R & (R | R)) E(28/32) = R | R | R E(29/32) = R | R | R | (R & R) E(30/32) = R | R | R | R E(31/32) = R | R | R | R | R
More parens can be removed since | and & don't have the same precedence, but I think that would make it hard to read.
Update: I originally had this longer code:
#!/usr/bin/perl use strict; use warnings; my $bits = shift; my $den = 2**$bits; foreach my $num (1 .. $den-1) { my $str = sprintf "%0${bits}b", $num; $str =~ s/10*$//; my $t = 0; my @groups = grep $t^=1, $str =~ /((.)\2*)/g; s/0/R & /g, s/1/R | /g, s/^/(/ for @groups; $str = join('', @groups) . 'R' . (')'x@groups); $str =~ s/^\((.*)\)$/$1/; print "E($num/$den) = $str\n"; }
|
---|