Find all expressions of four 10s

2019-02-21 04:19发布

I was challenged with a CS problem.

The problem consists of recursively finding which expressions of the form ((10+10)/(10+10)) produces a number. For example, ((10+10)/(10+10)) produces 1. Find all the other expressions using the operators +, -, *, /, with 4 numbers of 10, and all the combinations of parentheses to enforce orders of operations.

I was referred to the Reverse Polish Notation, but that relies on postfix notation, which isn’t required to solve this problem.

Some pseudocode I have is this. I know using recursion is the easiest way to solve this problem. But don't know how to make sure I get all combinations.

build([10,10,10,10], Expression) :-
      Operator
     /       \
   [10]     [10,10,10]
             Operator
              /     \
           [10]     [10,10]
                    Operator
                     /    \
                   [10]   [10]

This is a problem I am trying to solve in Prolog but C++ is good as well.

标签: c++ prolog
1条回答
forever°为你锁心
2楼-- · 2019-02-21 05:05

I have a partial solution which I will outline here and hopefully it will get you moving and you can find the complete solution.

The first tool you need is the ability to make some expressions:

build_expr(X, Y, X+Y).
build_expr(X, Y, X*Y).
build_expr(X, Y, X-Y).
build_expr(X, Y, X/Y).

This defines build_expr/3, which takes two variables or expressions and produces a new expression. This is how we are going to permute the operators. Now we need a way to handle the lists, so let's define build_expr/2 that operates on a list at once:

% base case: we are down to two variables and call build_expr/3
build_expr([X,Y], Expr) :- build_expr(X, Y, Expr).

% inductive case: make the expression on the rest of the list and combine
% with the leading variable here
build_expr([X|Rest], Expr) :-
    build_expr(Rest, Expr0),
    build_expr(X, Expr0, Expr).

Let's get a few solutions so we get the flavor of what it's doing:

3 ?- build_expr([10,10,10,10],X).
X = 10+(10+(10+10)) ;
X = 10*(10+(10+10)) ;
X = 10-(10+(10+10)) ;
X = 10/(10+(10+10)) ;
X = 10+10*(10+10) ;
X = 10*(10*(10+10)) ;
X = 10-10*(10+10) ;
X = 10/(10*(10+10)) ;
X = 10+(10-(10+10)) ;
X = 10*(10-(10+10)) ;
X = 10-(10-(10+10)) ;
X = 10/(10-(10+10)) ;

This looks pretty good to me. But like I said, I'm only generating the right-leaning tree. You will have to modify or replace build_expr/2 to produce the other shapes, if they actually matter (which I'm not convinced they do).

Now let's make the next step simpler by bundling in evaluation:

build_eval(L, Value) :- build_expr(L, Expr), Value is Expr.

Now we should be able to find all the unique solutions using setof/3:

6 ?- setof(X, build_eval([10,10,10,10],X), Results).
ERROR: Arithmetic: evaluation error: `zero_divisor'
ERROR: In:
ERROR:   [15] _582 is 10/(10* ...)
ERROR:   [14] build_eval([10,10|...],_622) at /Users/dlyons/fourtens.pl:11
ERROR:   [13] '$bags':findall_loop(_664,user:build_eval(...,_682),_668,[]) at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/bags.pl:97
ERROR:   [12] setup_call_catcher_cleanup('$bags':'$new_findall_bag','$bags':findall_loop(_728,...,_732,[]),_710,'$bags':'$destroy_findall_bag') at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/init.pl:443
ERROR:    [8] '$bags':setof(_770,user:build_eval(...,_786),_774) at /usr/local/Cellar/swi-prolog/7.6.4/libexec/lib/swipl-7.6.4/boot/bags.pl:240
ERROR:    [7] <user>
ERROR:
ERROR: Note: some frames are missing due to last-call optimization.
ERROR: Re-run your program in debug mode (:- debug.) to get more detail.
ERROR:   [13] '$bags':findall_loop(_664,user:build_eval(...,_682),_668,[]) aabort
% Execution Aborted

Oops. Division by zero error. No problem, let's catch that and fail in those cases instead:

9 ?- setof(X, catch(build_eval([10,10,10,10],X), E, fail), Results), writeln(Results).
[-990,-900,-190,-100,-80,-20,-1,-0.1111111111111111,
 0,0.01,0.05,0.09090909090909091,0.3333333333333333,1.0,1,
 5.0,9.5,9.9,10,10.1,10.5,20.0,20,40,100.0,100,
 120,210,300,1010,1100,2000,10000]

I fiddled with the formatting there a little, but I think that's a pretty good solution, but I can already see one missing solution: (10+10)*(10+10)=400. So you will have to get more creative with build_expr/2 to make it produce other shapes of tree.

Edit: Adding the rest of the solutions

I found an answer by @gusbro that gives a way to enumerate the trees. I wasn't able to get it to work with the recursive trickery I was doing there (maybe someone else will show me a very easy trick) but I was able to adapt his answer to your problem, to wit:

build_tree([I1,I2|Items], Expr) :-
    append([L0|LR], [R0|RR], [I1,I2|Items]),
    build_tree([L0|LR], Left),
    build_tree([R0|RR], Right),
    build_expr(Left, Right, Expr).
build_tree([E], E).

Why am I using [L0|LR] and [R0|RR] instead of LeftList and RightList or some such? This is how I'm turning @gusbro's numeric constraints into list length constraints and ensuring that I always have at least one element in both the left and right lists, so my recursive calls to build_tree/2 will succeed.

Simplifying build_expr/3 from above down to a single operator you can see this generates all the various flavors you'd expect:

?- build_tree([10,10,10,10],X).
X = 10+(10+(10+10)) ;
X = 10+(10+10+10) ;
X = 10+10+(10+10) ;
X = 10+(10+10)+10 ;
X = 10+10+10+10 ;
false.

Switch it back, because we're still using the build_expr/3 function from the earlier example. I have simplified the evaluation somewhat using this build_eval/2 predicate:

build_eval(L, Value) :- 
    build_tree(L, Expr), catch(Value is Expr, _, fail).

Here's what the final solution looks like:

 ?- setof(X, build_eval([10,10,10,10], X), Res), writeln(Res).
[-990,-900,-190,-100,-99,-90,-80,-20,-19,-10,-9.9,-9.5,-9,
 -8,-1.1111111111111112,-1,-0.9,-0.1111111111111111,
 0,0.01,0.05,0.09090909090909091,0.1111111111111111,
 0.2,0.3333333333333333,0.9,0.9090909090909091,1.0,1,
 1.1,1.1111111111111112,2,3,5.0,5,8,9,9.5,9.9,10,10.1,10.5,11,
 12,19,20.0,20,21,40,80,90,99,100.0,100,101,110,120,190,
 200,210,300,400,900,990,1010,1100,2000,10000]

Wow, quite a few alternatives, 68 to be exact!

查看更多
登录 后发表回答