I was in an interview today and the interviewer drew a bunch of binary op-trees on the board and said: "show me how you would process these." Since I had my trusty laptop with me, I said "can I write a program?" He said "sure."... so here is what I wrote. I would like to see this code optimized in terms of number of lines used. I am particularly keen on unifying my checks for simple versus complex right and left operands, in other words, the lines like
if (ref($op_tree->[0]) eq 'ARRAY') {
It just occurred to me that some people might be thinking this would help me with my interview. But it won't the interview is over and I am just trying to improve my skills.
use strict;
sub proc;
sub proc {
my $op_tree = shift;
if (ref($op_tree->[0]) eq 'ARRAY') {
$op_tree->[0] = proc $op_tree->[0] ;
}
if (ref($op_tree->[2]) eq 'ARRAY') {
$op_tree->[2] = proc $op_tree->[2] ;
}
my $expr = sprintf '%d %s %d', @$op_tree;
warn "EXPR $expr";
eval $expr;
}
my $sched1 = [ 1, '||', 0 ];
my $sched2 = [ 1, '&&', 0 ];
my $sched3 = [ $sched1, '&&', 1 ];
my $sched4 = [ $sched1, '&&', $sched2 ];
warn proc $sched1;
warn proc $sched2;
warn proc $sched3;
warn proc $sched4;
Edit Masem 2001-11-13 - Small code fix
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.