When you are compiling code to a target architecture there are hardware specific optimizations that can be made. In this problem we will be taking a string of source text and compiling it to some variable architecture. The source text will be given as a String expression. expression should be a well-parenthesized mathematical formula that conforms to the following grammar:
<EXPR> ::= '('<EXPR><OP><EXPR>')' | <INT>
<OP> ::= '+' | '-' | '/' | '*'
<INT> ::= a positive integer with no leading 0s between 1 and 100, inclusive
For example, 9, (1+(2+((3+2)-2))), and ((1*2)/2) conform to the grammar while (1+2+3), (0+2), and ((1+2)) do not.
If expression does not conform to the above grammar your method should return -2. If it does conform, you will then have to determine which instructions should be used to implement the expression. The machine capabilities will be given in a String[] instructions. Each element will conform to the following grammar:<INST> ::= <COST>':'<VAREXPR>
<VAREXPR> ::= '('<VAREXPR><OP><VAREXPR>')' | 'X'
<OP> ::= '+' | '-' | '/' | '*'
<COST> ::= a positive integer with no leading 0s between 1 and 100, inclusive
An example element could be 10:(X+X) meaning that there is an instruction that will add 2 operands together at a cost of 10. Another example could be 12:(X*(X-X)) meaning that it will cost 12 to multiply 1 operand by the difference of two others. Each element of instruction will thus represent the possible operations the underlying hardware can perform along with their cost. Since instructions of the form "COST:X" are meaningless they will not be allowed as input. If the given expression cannot be computed on the given hardware your method should return -1. Otherwise it should return the minimum cost required to compute all of the operations in the expression. For example: expression = "((1+2)*(3+(4-2)))"
instructions = {"5:(X+X)",
"5:(X-X)",
"6:(X*X)",
"7:((X+X)*X)"}
Using instruction 0 on the (1+2) portion of the expression and instruction 1 on the (4-2) portion of the expression will produce the intermediate expression (3*(3+2)). Then applying expression 0 to the (3+2) portion we get the intermediate expression (3*5). Finally applying instruction 2 we get an expression that no longer contains any operations and is thus complete. The total cost of this method is 5+5+5+6 = 21. Alternatively we could have used instruction 1, then 0, and finally 3 for a smaller cost of 17. Your method should thus return 17, the minimum possible cost. The cost of applying no operations is 0. For example:expression = "84"
instructions = {"10:(X+X)"}
Since the expression only consists of a number, there are no operations to be processed, so the cost is simply 0.
Note that you are not allowed to apply any simplifications to the expression (i.e. no associativity, commutativity, distributivity, or identity laws). This means (3+(4*5)) cannot be processed by an instruction like 4:((X*X)+X). |