use strict; use warnings; sub operations { my($num_ops) = @_; #return (["M | M", 3 , 4], ["M & M", 1, 4]) # if($num_ops == 1); return ["M", 1, 2] if($num_ops == 0); my @result; for(my $i=0;$i<$num_ops;$i++) { my @first = operations($i); my @second = operations($num_ops - $i - 1); foreach my $first_part (@first) { my($fp_expr,$fp_top,$fp_bot) = @{$first_part}; foreach my $second_part (@second) { my($sp_expr,$sp_top,$sp_bot) = @{$second_part}; # Two choices & or | # (NY + M(X-N))/(X*Y) # (X*Y - ((X-N)Y + (Y-M)N))/(X*Y) push @result,["($fp_expr) & ($sp_expr)", $fp_bot*$sp_bot - ($fp_bot - $fp_top)*$sp_bot - ($sp_bot - $sp_top)*$fp_top, $fp_bot*$sp_bot], ["($fp_expr) | ($sp_expr)", $fp_top*$sp_bot + $sp_top*($fp_bot - $fp_top), $fp_bot*$sp_bot]; } } } return @result; } # Update: Edited the calling routine to provide easier to use results my @got; foreach my $count_expr (0..4) { foreach my $expr (operations($count_expr)) { my($sp_expr,$top,$bot) = @{$expr}; $top = $top * (32 / $bot); next if(defined $got[$top]); $sp_expr =~ s/\(M\)/M/g; $got[$top] = sprintf "%02d: $sp_expr\n",$top; } } for(my $i=1;$i<32;$i++) { print $got[$i]; }