Since you only have binary operations, you can model any of the calculations as a binary tree where the leaves are numbers and all other nodes are representing operations, e.g. for your first two examples:
+ -
/ \ / \
9 + * +
/ \ /| / \
1 + 2 9 - 1
/ \ / \
4 2 5 4
So your algorithm would need the following parts:
- a tree generator for all possible binary trees up to a certain node count: starting with a number node, recursively replace each number node (leaf) with an operator node and two children (number nodes), thus generating a sequence of trees like this
.
N O O O ...
/ \ / \ / \
N N O N N O
/ \ / \
N N N N
- a "tree filler" that generates for a given binary tree (like above) all possible insertions of operations and numbers, like:
.
O : + + ... - ...
/ \ / \ / \ / \
N N 1 5 1 2 1 5
- a tree evaluator that calculates the result
Happy programming! :-)