2
Problem 2: Generating Expressions [14 points]
This problem was worth a good number of points, because you needed to build a larger
algorithm to solve a more complicated problem.
My solution is straightforward, but it’s
more straightforward than I’d expect from students trying to solve the problem under time
constraints.
It’s certainly the case that you needed to generate all permutations of the digit string, and
for each determine all of the different ways you can construct an expression tree.
There’s a
lot of code to be written here.
void addToPossibilities(string digitOrder,
int start,
int end,
Set<int>& possibilities)
{
if (start == end) {
possibilities.add(digitOrder[start] - '0');
return;
}
for (int mid = start; mid < end; mid++) {
Set<int> left, right;
addToPossibilities(digitOrder, start, mid, left);
addToPossibilities(digitOrder, mid + 1, end, right);
foreach (int l in left) {
foreach (int r in right) {
possibilities.add(l + r);
possibilities.add(l - r);
possibilities.add(l * r);
if (r != 0) possibilities.add(l / r);
}
}
}
}
void addToPossibilities(string digitOrder,
Set<int>& possibilities)
{
addToPossibilities(digitOrder, 0, digitOrder.size() - 1, possibilities);
}
void computeAllPossibilities(string fixedPrefix,
string remaining,
Set<int>& possibilities) {
if (remaining.empty()) {
// fixedPrefix is a full ordering
addToPossibilities(fixedPrefix, possibilities);
return;
}
for (int i = 0; i < remaining.size(); i++) {
computeAllPossibilities(fixedPrefix + remaining[i],
remaining.substr(0, i) + remaining.substr(i + 1),
possibilities);
}
}