Homework 2

This homework is based on notions of chapters 5 of the textbook.

Problem 1

You are required to code an abstraction for manipulating integer arithmetic expressions such as (1+2)*3. Expression should not have any arbitrarily preset size limit. The implementation language should be object-oriented, e.g., Java, C++, Python or Ruby. If you prefer to use a different language, please consult the instructor first. A language whose code is easy to read (expressive) is preferred.

Your implementation should consists of a base abstract class/interface called Expr and concrete subclasses of Expr for both values (such as 1, 2 and 3) and binary operator expressions (such as 1+2). The binary operator are +, -, * and /. Expressions in which a divisor is not a factor of the dividend have no value, e.g., 3/2 has no value, whereas 4/2 has value 2.

In addition to a device to create expressions, your code should have devices to (a) print an expression in a standard easy-to-read form (e.g., the object abstracting 1+2 should print to something very close to "1+2"; you can freely use parentheses) and (b) evaluate an expression (e.g., the value of the object abstracting 1+2 should be 3). The value of an expressions with no value should print as "error" or "None" or similar.

You must provide unit testing, in a separate file, for your code. You should have tests for each "interesting" case.

Submit your code and a trace/printout of the unit test execution.

Problem 2

Consider an arithmetic expression (called "of interest") constructed by four occurrences of the number 10, e.g.: (10+10)/(10+10). The value of this expression is 1. Can you construct another expression of interest whose value is 2? What about 3?

Code a program that determines which digits are the values of one such expression. Your program should execute the following intermediate steps: (1) construct all the expressions of interest and (2) print any expression whose value is between 0 and 9.

A simple (and general) solution constructs any expression of interest  as follows. Let X be the (multi)set of operands of an expression. Divide X into two parts Y and Z, there are many ways and you should consider all. Construct the expressions for Y and Z and join them with an arithmetic operator,  there are many ways and you should consider all. 

Remember that expressions in which a divisor is not a factor of its dividend have no value. This should be handled by the code of assignment 1. For your information, the number of expressions of interest is 320 (like this course!): in any expression there are 3 operators, 5 is the Catalan number of 3. There are 5 binary trees with 3 nodes, thus 5*4^3 is the number of distinct expressions. Some of these expressions have no value according to our convention.

Submit your code as for this problem.